three.module.js 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184
  1. /**
  2. * @license
  3. * Copyright 2010-2023 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '149';
  7. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  8. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  9. const CullFaceNone = 0;
  10. const CullFaceBack = 1;
  11. const CullFaceFront = 2;
  12. const CullFaceFrontBack = 3;
  13. const BasicShadowMap = 0;
  14. const PCFShadowMap = 1;
  15. const PCFSoftShadowMap = 2;
  16. const VSMShadowMap = 3;
  17. const FrontSide = 0;
  18. const BackSide = 1;
  19. const DoubleSide = 2;
  20. const TwoPassDoubleSide = 2; // r149
  21. const NoBlending = 0;
  22. const NormalBlending = 1;
  23. const AdditiveBlending = 2;
  24. const SubtractiveBlending = 3;
  25. const MultiplyBlending = 4;
  26. const CustomBlending = 5;
  27. const AddEquation = 100;
  28. const SubtractEquation = 101;
  29. const ReverseSubtractEquation = 102;
  30. const MinEquation = 103;
  31. const MaxEquation = 104;
  32. const ZeroFactor = 200;
  33. const OneFactor = 201;
  34. const SrcColorFactor = 202;
  35. const OneMinusSrcColorFactor = 203;
  36. const SrcAlphaFactor = 204;
  37. const OneMinusSrcAlphaFactor = 205;
  38. const DstAlphaFactor = 206;
  39. const OneMinusDstAlphaFactor = 207;
  40. const DstColorFactor = 208;
  41. const OneMinusDstColorFactor = 209;
  42. const SrcAlphaSaturateFactor = 210;
  43. const NeverDepth = 0;
  44. const AlwaysDepth = 1;
  45. const LessDepth = 2;
  46. const LessEqualDepth = 3;
  47. const EqualDepth = 4;
  48. const GreaterEqualDepth = 5;
  49. const GreaterDepth = 6;
  50. const NotEqualDepth = 7;
  51. const MultiplyOperation = 0;
  52. const MixOperation = 1;
  53. const AddOperation = 2;
  54. const NoToneMapping = 0;
  55. const LinearToneMapping = 1;
  56. const ReinhardToneMapping = 2;
  57. const CineonToneMapping = 3;
  58. const ACESFilmicToneMapping = 4;
  59. const CustomToneMapping = 5;
  60. const UVMapping = 300;
  61. const CubeReflectionMapping = 301;
  62. const CubeRefractionMapping = 302;
  63. const EquirectangularReflectionMapping = 303;
  64. const EquirectangularRefractionMapping = 304;
  65. const CubeUVReflectionMapping = 306;
  66. const RepeatWrapping = 1000;
  67. const ClampToEdgeWrapping = 1001;
  68. const MirroredRepeatWrapping = 1002;
  69. const NearestFilter = 1003;
  70. const NearestMipmapNearestFilter = 1004;
  71. const NearestMipMapNearestFilter = 1004;
  72. const NearestMipmapLinearFilter = 1005;
  73. const NearestMipMapLinearFilter = 1005;
  74. const LinearFilter = 1006;
  75. const LinearMipmapNearestFilter = 1007;
  76. const LinearMipMapNearestFilter = 1007;
  77. const LinearMipmapLinearFilter = 1008;
  78. const LinearMipMapLinearFilter = 1008;
  79. const UnsignedByteType = 1009;
  80. const ByteType = 1010;
  81. const ShortType = 1011;
  82. const UnsignedShortType = 1012;
  83. const IntType = 1013;
  84. const UnsignedIntType = 1014;
  85. const FloatType = 1015;
  86. const HalfFloatType = 1016;
  87. const UnsignedShort4444Type = 1017;
  88. const UnsignedShort5551Type = 1018;
  89. const UnsignedInt248Type = 1020;
  90. const AlphaFormat = 1021;
  91. const RGBAFormat = 1023;
  92. const LuminanceFormat = 1024;
  93. const LuminanceAlphaFormat = 1025;
  94. const DepthFormat = 1026;
  95. const DepthStencilFormat = 1027;
  96. const RedFormat = 1028;
  97. const RedIntegerFormat = 1029;
  98. const RGFormat = 1030;
  99. const RGIntegerFormat = 1031;
  100. const RGBAIntegerFormat = 1033;
  101. const RGB_S3TC_DXT1_Format = 33776;
  102. const RGBA_S3TC_DXT1_Format = 33777;
  103. const RGBA_S3TC_DXT3_Format = 33778;
  104. const RGBA_S3TC_DXT5_Format = 33779;
  105. const RGB_PVRTC_4BPPV1_Format = 35840;
  106. const RGB_PVRTC_2BPPV1_Format = 35841;
  107. const RGBA_PVRTC_4BPPV1_Format = 35842;
  108. const RGBA_PVRTC_2BPPV1_Format = 35843;
  109. const RGB_ETC1_Format = 36196;
  110. const RGB_ETC2_Format = 37492;
  111. const RGBA_ETC2_EAC_Format = 37496;
  112. const RGBA_ASTC_4x4_Format = 37808;
  113. const RGBA_ASTC_5x4_Format = 37809;
  114. const RGBA_ASTC_5x5_Format = 37810;
  115. const RGBA_ASTC_6x5_Format = 37811;
  116. const RGBA_ASTC_6x6_Format = 37812;
  117. const RGBA_ASTC_8x5_Format = 37813;
  118. const RGBA_ASTC_8x6_Format = 37814;
  119. const RGBA_ASTC_8x8_Format = 37815;
  120. const RGBA_ASTC_10x5_Format = 37816;
  121. const RGBA_ASTC_10x6_Format = 37817;
  122. const RGBA_ASTC_10x8_Format = 37818;
  123. const RGBA_ASTC_10x10_Format = 37819;
  124. const RGBA_ASTC_12x10_Format = 37820;
  125. const RGBA_ASTC_12x12_Format = 37821;
  126. const RGBA_BPTC_Format = 36492;
  127. const RED_RGTC1_Format = 36283;
  128. const SIGNED_RED_RGTC1_Format = 36284;
  129. const RED_GREEN_RGTC2_Format = 36285;
  130. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  131. const LoopOnce = 2200;
  132. const LoopRepeat = 2201;
  133. const LoopPingPong = 2202;
  134. const InterpolateDiscrete = 2300;
  135. const InterpolateLinear = 2301;
  136. const InterpolateSmooth = 2302;
  137. const ZeroCurvatureEnding = 2400;
  138. const ZeroSlopeEnding = 2401;
  139. const WrapAroundEnding = 2402;
  140. const NormalAnimationBlendMode = 2500;
  141. const AdditiveAnimationBlendMode = 2501;
  142. const TrianglesDrawMode = 0;
  143. const TriangleStripDrawMode = 1;
  144. const TriangleFanDrawMode = 2;
  145. const LinearEncoding = 3000;
  146. const sRGBEncoding = 3001;
  147. const BasicDepthPacking = 3200;
  148. const RGBADepthPacking = 3201;
  149. const TangentSpaceNormalMap = 0;
  150. const ObjectSpaceNormalMap = 1;
  151. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  152. const NoColorSpace = '';
  153. const SRGBColorSpace = 'srgb';
  154. const LinearSRGBColorSpace = 'srgb-linear';
  155. const ZeroStencilOp = 0;
  156. const KeepStencilOp = 7680;
  157. const ReplaceStencilOp = 7681;
  158. const IncrementStencilOp = 7682;
  159. const DecrementStencilOp = 7683;
  160. const IncrementWrapStencilOp = 34055;
  161. const DecrementWrapStencilOp = 34056;
  162. const InvertStencilOp = 5386;
  163. const NeverStencilFunc = 512;
  164. const LessStencilFunc = 513;
  165. const EqualStencilFunc = 514;
  166. const LessEqualStencilFunc = 515;
  167. const GreaterStencilFunc = 516;
  168. const NotEqualStencilFunc = 517;
  169. const GreaterEqualStencilFunc = 518;
  170. const AlwaysStencilFunc = 519;
  171. const StaticDrawUsage = 35044;
  172. const DynamicDrawUsage = 35048;
  173. const StreamDrawUsage = 35040;
  174. const StaticReadUsage = 35045;
  175. const DynamicReadUsage = 35049;
  176. const StreamReadUsage = 35041;
  177. const StaticCopyUsage = 35046;
  178. const DynamicCopyUsage = 35050;
  179. const StreamCopyUsage = 35042;
  180. const GLSL1 = '100';
  181. const GLSL3 = '300 es';
  182. const _SRGBAFormat = 1035; // fallback for WebGL 1
  183. /**
  184. * https://github.com/mrdoob/eventdispatcher.js/
  185. */
  186. class EventDispatcher {
  187. addEventListener( type, listener ) {
  188. if ( this._listeners === undefined ) this._listeners = {};
  189. const listeners = this._listeners;
  190. if ( listeners[ type ] === undefined ) {
  191. listeners[ type ] = [];
  192. }
  193. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  194. listeners[ type ].push( listener );
  195. }
  196. }
  197. hasEventListener( type, listener ) {
  198. if ( this._listeners === undefined ) return false;
  199. const listeners = this._listeners;
  200. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  201. }
  202. removeEventListener( type, listener ) {
  203. if ( this._listeners === undefined ) return;
  204. const listeners = this._listeners;
  205. const listenerArray = listeners[ type ];
  206. if ( listenerArray !== undefined ) {
  207. const index = listenerArray.indexOf( listener );
  208. if ( index !== - 1 ) {
  209. listenerArray.splice( index, 1 );
  210. }
  211. }
  212. }
  213. dispatchEvent( event ) {
  214. if ( this._listeners === undefined ) return;
  215. const listeners = this._listeners;
  216. const listenerArray = listeners[ event.type ];
  217. if ( listenerArray !== undefined ) {
  218. event.target = this;
  219. // Make a copy, in case listeners are removed while iterating.
  220. const array = listenerArray.slice( 0 );
  221. for ( let i = 0, l = array.length; i < l; i ++ ) {
  222. array[ i ].call( this, event );
  223. }
  224. event.target = null;
  225. }
  226. }
  227. }
  228. 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' ];
  229. let _seed = 1234567;
  230. const DEG2RAD = Math.PI / 180;
  231. const RAD2DEG = 180 / Math.PI;
  232. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  233. function generateUUID() {
  234. const d0 = Math.random() * 0xffffffff | 0;
  235. const d1 = Math.random() * 0xffffffff | 0;
  236. const d2 = Math.random() * 0xffffffff | 0;
  237. const d3 = Math.random() * 0xffffffff | 0;
  238. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  239. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  240. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  241. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  242. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  243. return uuid.toLowerCase();
  244. }
  245. function clamp( value, min, max ) {
  246. return Math.max( min, Math.min( max, value ) );
  247. }
  248. // compute euclidean modulo of m % n
  249. // https://en.wikipedia.org/wiki/Modulo_operation
  250. function euclideanModulo( n, m ) {
  251. return ( ( n % m ) + m ) % m;
  252. }
  253. // Linear mapping from range <a1, a2> to range <b1, b2>
  254. function mapLinear( x, a1, a2, b1, b2 ) {
  255. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  256. }
  257. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  258. function inverseLerp( x, y, value ) {
  259. if ( x !== y ) {
  260. return ( value - x ) / ( y - x );
  261. } else {
  262. return 0;
  263. }
  264. }
  265. // https://en.wikipedia.org/wiki/Linear_interpolation
  266. function lerp( x, y, t ) {
  267. return ( 1 - t ) * x + t * y;
  268. }
  269. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  270. function damp( x, y, lambda, dt ) {
  271. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  272. }
  273. // https://www.desmos.com/calculator/vcsjnyz7x4
  274. function pingpong( x, length = 1 ) {
  275. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  276. }
  277. // http://en.wikipedia.org/wiki/Smoothstep
  278. function smoothstep( x, min, max ) {
  279. if ( x <= min ) return 0;
  280. if ( x >= max ) return 1;
  281. x = ( x - min ) / ( max - min );
  282. return x * x * ( 3 - 2 * x );
  283. }
  284. function smootherstep( x, min, max ) {
  285. if ( x <= min ) return 0;
  286. if ( x >= max ) return 1;
  287. x = ( x - min ) / ( max - min );
  288. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  289. }
  290. // Random integer from <low, high> interval
  291. function randInt( low, high ) {
  292. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  293. }
  294. // Random float from <low, high> interval
  295. function randFloat( low, high ) {
  296. return low + Math.random() * ( high - low );
  297. }
  298. // Random float from <-range/2, range/2> interval
  299. function randFloatSpread( range ) {
  300. return range * ( 0.5 - Math.random() );
  301. }
  302. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  303. function seededRandom( s ) {
  304. if ( s !== undefined ) _seed = s;
  305. // Mulberry32 generator
  306. let t = _seed += 0x6D2B79F5;
  307. t = Math.imul( t ^ t >>> 15, t | 1 );
  308. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  309. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  310. }
  311. function degToRad( degrees ) {
  312. return degrees * DEG2RAD;
  313. }
  314. function radToDeg( radians ) {
  315. return radians * RAD2DEG;
  316. }
  317. function isPowerOfTwo( value ) {
  318. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  319. }
  320. function ceilPowerOfTwo( value ) {
  321. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  322. }
  323. function floorPowerOfTwo( value ) {
  324. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  325. }
  326. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  327. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  328. // rotations are applied to the axes in the order specified by 'order'
  329. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  330. // angles are in radians
  331. const cos = Math.cos;
  332. const sin = Math.sin;
  333. const c2 = cos( b / 2 );
  334. const s2 = sin( b / 2 );
  335. const c13 = cos( ( a + c ) / 2 );
  336. const s13 = sin( ( a + c ) / 2 );
  337. const c1_3 = cos( ( a - c ) / 2 );
  338. const s1_3 = sin( ( a - c ) / 2 );
  339. const c3_1 = cos( ( c - a ) / 2 );
  340. const s3_1 = sin( ( c - a ) / 2 );
  341. switch ( order ) {
  342. case 'XYX':
  343. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  344. break;
  345. case 'YZY':
  346. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  347. break;
  348. case 'ZXZ':
  349. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  350. break;
  351. case 'XZX':
  352. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  353. break;
  354. case 'YXY':
  355. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  356. break;
  357. case 'ZYZ':
  358. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  359. break;
  360. default:
  361. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  362. }
  363. }
  364. function denormalize( value, array ) {
  365. switch ( array.constructor ) {
  366. case Float32Array:
  367. return value;
  368. case Uint16Array:
  369. return value / 65535.0;
  370. case Uint8Array:
  371. return value / 255.0;
  372. case Int16Array:
  373. return Math.max( value / 32767.0, - 1.0 );
  374. case Int8Array:
  375. return Math.max( value / 127.0, - 1.0 );
  376. default:
  377. throw new Error( 'Invalid component type.' );
  378. }
  379. }
  380. function normalize( value, array ) {
  381. switch ( array.constructor ) {
  382. case Float32Array:
  383. return value;
  384. case Uint16Array:
  385. return Math.round( value * 65535.0 );
  386. case Uint8Array:
  387. return Math.round( value * 255.0 );
  388. case Int16Array:
  389. return Math.round( value * 32767.0 );
  390. case Int8Array:
  391. return Math.round( value * 127.0 );
  392. default:
  393. throw new Error( 'Invalid component type.' );
  394. }
  395. }
  396. var MathUtils = /*#__PURE__*/Object.freeze({
  397. __proto__: null,
  398. DEG2RAD: DEG2RAD,
  399. RAD2DEG: RAD2DEG,
  400. ceilPowerOfTwo: ceilPowerOfTwo,
  401. clamp: clamp,
  402. damp: damp,
  403. degToRad: degToRad,
  404. denormalize: denormalize,
  405. euclideanModulo: euclideanModulo,
  406. floorPowerOfTwo: floorPowerOfTwo,
  407. generateUUID: generateUUID,
  408. inverseLerp: inverseLerp,
  409. isPowerOfTwo: isPowerOfTwo,
  410. lerp: lerp,
  411. mapLinear: mapLinear,
  412. normalize: normalize,
  413. pingpong: pingpong,
  414. radToDeg: radToDeg,
  415. randFloat: randFloat,
  416. randFloatSpread: randFloatSpread,
  417. randInt: randInt,
  418. seededRandom: seededRandom,
  419. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  420. smootherstep: smootherstep,
  421. smoothstep: smoothstep
  422. });
  423. class Vector2 {
  424. constructor( x = 0, y = 0 ) {
  425. Vector2.prototype.isVector2 = true;
  426. this.x = x;
  427. this.y = y;
  428. }
  429. get width() {
  430. return this.x;
  431. }
  432. set width( value ) {
  433. this.x = value;
  434. }
  435. get height() {
  436. return this.y;
  437. }
  438. set height( value ) {
  439. this.y = value;
  440. }
  441. set( x, y ) {
  442. this.x = x;
  443. this.y = y;
  444. return this;
  445. }
  446. setScalar( scalar ) {
  447. this.x = scalar;
  448. this.y = scalar;
  449. return this;
  450. }
  451. setX( x ) {
  452. this.x = x;
  453. return this;
  454. }
  455. setY( y ) {
  456. this.y = y;
  457. return this;
  458. }
  459. setComponent( index, value ) {
  460. switch ( index ) {
  461. case 0: this.x = value; break;
  462. case 1: this.y = value; break;
  463. default: throw new Error( 'index is out of range: ' + index );
  464. }
  465. return this;
  466. }
  467. getComponent( index ) {
  468. switch ( index ) {
  469. case 0: return this.x;
  470. case 1: return this.y;
  471. default: throw new Error( 'index is out of range: ' + index );
  472. }
  473. }
  474. clone() {
  475. return new this.constructor( this.x, this.y );
  476. }
  477. copy( v ) {
  478. this.x = v.x;
  479. this.y = v.y;
  480. return this;
  481. }
  482. add( v ) {
  483. this.x += v.x;
  484. this.y += v.y;
  485. return this;
  486. }
  487. addScalar( s ) {
  488. this.x += s;
  489. this.y += s;
  490. return this;
  491. }
  492. addVectors( a, b ) {
  493. this.x = a.x + b.x;
  494. this.y = a.y + b.y;
  495. return this;
  496. }
  497. addScaledVector( v, s ) {
  498. this.x += v.x * s;
  499. this.y += v.y * s;
  500. return this;
  501. }
  502. sub( v ) {
  503. this.x -= v.x;
  504. this.y -= v.y;
  505. return this;
  506. }
  507. subScalar( s ) {
  508. this.x -= s;
  509. this.y -= s;
  510. return this;
  511. }
  512. subVectors( a, b ) {
  513. this.x = a.x - b.x;
  514. this.y = a.y - b.y;
  515. return this;
  516. }
  517. multiply( v ) {
  518. this.x *= v.x;
  519. this.y *= v.y;
  520. return this;
  521. }
  522. multiplyScalar( scalar ) {
  523. this.x *= scalar;
  524. this.y *= scalar;
  525. return this;
  526. }
  527. divide( v ) {
  528. this.x /= v.x;
  529. this.y /= v.y;
  530. return this;
  531. }
  532. divideScalar( scalar ) {
  533. return this.multiplyScalar( 1 / scalar );
  534. }
  535. applyMatrix3( m ) {
  536. const x = this.x, y = this.y;
  537. const e = m.elements;
  538. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  539. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  540. return this;
  541. }
  542. min( v ) {
  543. this.x = Math.min( this.x, v.x );
  544. this.y = Math.min( this.y, v.y );
  545. return this;
  546. }
  547. max( v ) {
  548. this.x = Math.max( this.x, v.x );
  549. this.y = Math.max( this.y, v.y );
  550. return this;
  551. }
  552. clamp( min, max ) {
  553. // assumes min < max, componentwise
  554. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  555. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  556. return this;
  557. }
  558. clampScalar( minVal, maxVal ) {
  559. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  560. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  561. return this;
  562. }
  563. clampLength( min, max ) {
  564. const length = this.length();
  565. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  566. }
  567. floor() {
  568. this.x = Math.floor( this.x );
  569. this.y = Math.floor( this.y );
  570. return this;
  571. }
  572. ceil() {
  573. this.x = Math.ceil( this.x );
  574. this.y = Math.ceil( this.y );
  575. return this;
  576. }
  577. round() {
  578. this.x = Math.round( this.x );
  579. this.y = Math.round( this.y );
  580. return this;
  581. }
  582. roundToZero() {
  583. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  584. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  585. return this;
  586. }
  587. negate() {
  588. this.x = - this.x;
  589. this.y = - this.y;
  590. return this;
  591. }
  592. dot( v ) {
  593. return this.x * v.x + this.y * v.y;
  594. }
  595. cross( v ) {
  596. return this.x * v.y - this.y * v.x;
  597. }
  598. lengthSq() {
  599. return this.x * this.x + this.y * this.y;
  600. }
  601. length() {
  602. return Math.sqrt( this.x * this.x + this.y * this.y );
  603. }
  604. manhattanLength() {
  605. return Math.abs( this.x ) + Math.abs( this.y );
  606. }
  607. normalize() {
  608. return this.divideScalar( this.length() || 1 );
  609. }
  610. angle() {
  611. // computes the angle in radians with respect to the positive x-axis
  612. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  613. return angle;
  614. }
  615. distanceTo( v ) {
  616. return Math.sqrt( this.distanceToSquared( v ) );
  617. }
  618. distanceToSquared( v ) {
  619. const dx = this.x - v.x, dy = this.y - v.y;
  620. return dx * dx + dy * dy;
  621. }
  622. manhattanDistanceTo( v ) {
  623. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  624. }
  625. setLength( length ) {
  626. return this.normalize().multiplyScalar( length );
  627. }
  628. lerp( v, alpha ) {
  629. this.x += ( v.x - this.x ) * alpha;
  630. this.y += ( v.y - this.y ) * alpha;
  631. return this;
  632. }
  633. lerpVectors( v1, v2, alpha ) {
  634. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  635. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  636. return this;
  637. }
  638. equals( v ) {
  639. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  640. }
  641. fromArray( array, offset = 0 ) {
  642. this.x = array[ offset ];
  643. this.y = array[ offset + 1 ];
  644. return this;
  645. }
  646. toArray( array = [], offset = 0 ) {
  647. array[ offset ] = this.x;
  648. array[ offset + 1 ] = this.y;
  649. return array;
  650. }
  651. fromBufferAttribute( attribute, index ) {
  652. this.x = attribute.getX( index );
  653. this.y = attribute.getY( index );
  654. return this;
  655. }
  656. rotateAround( center, angle ) {
  657. const c = Math.cos( angle ), s = Math.sin( angle );
  658. const x = this.x - center.x;
  659. const y = this.y - center.y;
  660. this.x = x * c - y * s + center.x;
  661. this.y = x * s + y * c + center.y;
  662. return this;
  663. }
  664. random() {
  665. this.x = Math.random();
  666. this.y = Math.random();
  667. return this;
  668. }
  669. *[ Symbol.iterator ]() {
  670. yield this.x;
  671. yield this.y;
  672. }
  673. }
  674. class Matrix3 {
  675. constructor() {
  676. Matrix3.prototype.isMatrix3 = true;
  677. this.elements = [
  678. 1, 0, 0,
  679. 0, 1, 0,
  680. 0, 0, 1
  681. ];
  682. }
  683. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  684. const te = this.elements;
  685. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  686. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  687. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  688. return this;
  689. }
  690. identity() {
  691. this.set(
  692. 1, 0, 0,
  693. 0, 1, 0,
  694. 0, 0, 1
  695. );
  696. return this;
  697. }
  698. copy( m ) {
  699. const te = this.elements;
  700. const me = m.elements;
  701. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  702. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  703. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  704. return this;
  705. }
  706. extractBasis( xAxis, yAxis, zAxis ) {
  707. xAxis.setFromMatrix3Column( this, 0 );
  708. yAxis.setFromMatrix3Column( this, 1 );
  709. zAxis.setFromMatrix3Column( this, 2 );
  710. return this;
  711. }
  712. setFromMatrix4( m ) {
  713. const me = m.elements;
  714. this.set(
  715. me[ 0 ], me[ 4 ], me[ 8 ],
  716. me[ 1 ], me[ 5 ], me[ 9 ],
  717. me[ 2 ], me[ 6 ], me[ 10 ]
  718. );
  719. return this;
  720. }
  721. multiply( m ) {
  722. return this.multiplyMatrices( this, m );
  723. }
  724. premultiply( m ) {
  725. return this.multiplyMatrices( m, this );
  726. }
  727. multiplyMatrices( a, b ) {
  728. const ae = a.elements;
  729. const be = b.elements;
  730. const te = this.elements;
  731. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  732. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  733. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  734. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  735. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  736. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  737. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  738. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  739. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  740. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  741. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  742. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  743. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  744. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  745. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  746. return this;
  747. }
  748. multiplyScalar( s ) {
  749. const te = this.elements;
  750. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  751. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  752. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  753. return this;
  754. }
  755. determinant() {
  756. const te = this.elements;
  757. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  758. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  759. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  760. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  761. }
  762. invert() {
  763. const te = this.elements,
  764. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  765. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  766. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  767. t11 = n33 * n22 - n32 * n23,
  768. t12 = n32 * n13 - n33 * n12,
  769. t13 = n23 * n12 - n22 * n13,
  770. det = n11 * t11 + n21 * t12 + n31 * t13;
  771. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  772. const detInv = 1 / det;
  773. te[ 0 ] = t11 * detInv;
  774. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  775. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  776. te[ 3 ] = t12 * detInv;
  777. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  778. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  779. te[ 6 ] = t13 * detInv;
  780. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  781. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  782. return this;
  783. }
  784. transpose() {
  785. let tmp;
  786. const m = this.elements;
  787. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  788. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  789. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  790. return this;
  791. }
  792. getNormalMatrix( matrix4 ) {
  793. return this.setFromMatrix4( matrix4 ).invert().transpose();
  794. }
  795. transposeIntoArray( r ) {
  796. const m = this.elements;
  797. r[ 0 ] = m[ 0 ];
  798. r[ 1 ] = m[ 3 ];
  799. r[ 2 ] = m[ 6 ];
  800. r[ 3 ] = m[ 1 ];
  801. r[ 4 ] = m[ 4 ];
  802. r[ 5 ] = m[ 7 ];
  803. r[ 6 ] = m[ 2 ];
  804. r[ 7 ] = m[ 5 ];
  805. r[ 8 ] = m[ 8 ];
  806. return this;
  807. }
  808. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  809. const c = Math.cos( rotation );
  810. const s = Math.sin( rotation );
  811. this.set(
  812. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  813. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  814. 0, 0, 1
  815. );
  816. return this;
  817. }
  818. //
  819. scale( sx, sy ) {
  820. this.premultiply( _m3.makeScale( sx, sy ) );
  821. return this;
  822. }
  823. rotate( theta ) {
  824. this.premultiply( _m3.makeRotation( - theta ) );
  825. return this;
  826. }
  827. translate( tx, ty ) {
  828. this.premultiply( _m3.makeTranslation( tx, ty ) );
  829. return this;
  830. }
  831. // for 2D Transforms
  832. makeTranslation( x, y ) {
  833. this.set(
  834. 1, 0, x,
  835. 0, 1, y,
  836. 0, 0, 1
  837. );
  838. return this;
  839. }
  840. makeRotation( theta ) {
  841. // counterclockwise
  842. const c = Math.cos( theta );
  843. const s = Math.sin( theta );
  844. this.set(
  845. c, - s, 0,
  846. s, c, 0,
  847. 0, 0, 1
  848. );
  849. return this;
  850. }
  851. makeScale( x, y ) {
  852. this.set(
  853. x, 0, 0,
  854. 0, y, 0,
  855. 0, 0, 1
  856. );
  857. return this;
  858. }
  859. //
  860. equals( matrix ) {
  861. const te = this.elements;
  862. const me = matrix.elements;
  863. for ( let i = 0; i < 9; i ++ ) {
  864. if ( te[ i ] !== me[ i ] ) return false;
  865. }
  866. return true;
  867. }
  868. fromArray( array, offset = 0 ) {
  869. for ( let i = 0; i < 9; i ++ ) {
  870. this.elements[ i ] = array[ i + offset ];
  871. }
  872. return this;
  873. }
  874. toArray( array = [], offset = 0 ) {
  875. const te = this.elements;
  876. array[ offset ] = te[ 0 ];
  877. array[ offset + 1 ] = te[ 1 ];
  878. array[ offset + 2 ] = te[ 2 ];
  879. array[ offset + 3 ] = te[ 3 ];
  880. array[ offset + 4 ] = te[ 4 ];
  881. array[ offset + 5 ] = te[ 5 ];
  882. array[ offset + 6 ] = te[ 6 ];
  883. array[ offset + 7 ] = te[ 7 ];
  884. array[ offset + 8 ] = te[ 8 ];
  885. return array;
  886. }
  887. clone() {
  888. return new this.constructor().fromArray( this.elements );
  889. }
  890. }
  891. const _m3 = /*@__PURE__*/ new Matrix3();
  892. function arrayNeedsUint32( array ) {
  893. // assumes larger values usually on last
  894. for ( let i = array.length - 1; i >= 0; -- i ) {
  895. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  896. }
  897. return false;
  898. }
  899. const TYPED_ARRAYS = {
  900. Int8Array: Int8Array,
  901. Uint8Array: Uint8Array,
  902. Uint8ClampedArray: Uint8ClampedArray,
  903. Int16Array: Int16Array,
  904. Uint16Array: Uint16Array,
  905. Int32Array: Int32Array,
  906. Uint32Array: Uint32Array,
  907. Float32Array: Float32Array,
  908. Float64Array: Float64Array
  909. };
  910. function getTypedArray( type, buffer ) {
  911. return new TYPED_ARRAYS[ type ]( buffer );
  912. }
  913. function createElementNS( name ) {
  914. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  915. }
  916. function SRGBToLinear( c ) {
  917. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  918. }
  919. function LinearToSRGB( c ) {
  920. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  921. }
  922. // JavaScript RGB-to-RGB transforms, defined as
  923. // FN[InputColorSpace][OutputColorSpace] callback functions.
  924. const FN = {
  925. [ SRGBColorSpace ]: { [ LinearSRGBColorSpace ]: SRGBToLinear },
  926. [ LinearSRGBColorSpace ]: { [ SRGBColorSpace ]: LinearToSRGB },
  927. };
  928. const ColorManagement = {
  929. legacyMode: true,
  930. get workingColorSpace() {
  931. return LinearSRGBColorSpace;
  932. },
  933. set workingColorSpace( colorSpace ) {
  934. console.warn( 'THREE.ColorManagement: .workingColorSpace is readonly.' );
  935. },
  936. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  937. if ( this.legacyMode || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  938. return color;
  939. }
  940. if ( FN[ sourceColorSpace ] && FN[ sourceColorSpace ][ targetColorSpace ] !== undefined ) {
  941. const fn = FN[ sourceColorSpace ][ targetColorSpace ];
  942. color.r = fn( color.r );
  943. color.g = fn( color.g );
  944. color.b = fn( color.b );
  945. return color;
  946. }
  947. throw new Error( 'Unsupported color space conversion.' );
  948. },
  949. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  950. return this.convert( color, this.workingColorSpace, targetColorSpace );
  951. },
  952. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  953. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  954. },
  955. };
  956. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  957. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  958. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  959. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  960. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  961. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  962. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  963. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  964. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  965. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  966. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  967. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  968. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  969. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  970. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  971. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  972. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  973. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  974. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  975. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  976. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  977. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  978. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  979. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  980. const _rgb$1 = { r: 0, g: 0, b: 0 };
  981. const _hslA = { h: 0, s: 0, l: 0 };
  982. const _hslB = { h: 0, s: 0, l: 0 };
  983. function hue2rgb( p, q, t ) {
  984. if ( t < 0 ) t += 1;
  985. if ( t > 1 ) t -= 1;
  986. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  987. if ( t < 1 / 2 ) return q;
  988. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  989. return p;
  990. }
  991. function toComponents( source, target ) {
  992. target.r = source.r;
  993. target.g = source.g;
  994. target.b = source.b;
  995. return target;
  996. }
  997. class Color {
  998. constructor( r, g, b ) {
  999. this.isColor = true;
  1000. this.r = 1;
  1001. this.g = 1;
  1002. this.b = 1;
  1003. if ( g === undefined && b === undefined ) {
  1004. // r is THREE.Color, hex or string
  1005. return this.set( r );
  1006. }
  1007. return this.setRGB( r, g, b );
  1008. }
  1009. set( value ) {
  1010. if ( value && value.isColor ) {
  1011. this.copy( value );
  1012. } else if ( typeof value === 'number' ) {
  1013. this.setHex( value );
  1014. } else if ( typeof value === 'string' ) {
  1015. this.setStyle( value );
  1016. }
  1017. return this;
  1018. }
  1019. setScalar( scalar ) {
  1020. this.r = scalar;
  1021. this.g = scalar;
  1022. this.b = scalar;
  1023. return this;
  1024. }
  1025. setHex( hex, colorSpace = SRGBColorSpace ) {
  1026. hex = Math.floor( hex );
  1027. this.r = ( hex >> 16 & 255 ) / 255;
  1028. this.g = ( hex >> 8 & 255 ) / 255;
  1029. this.b = ( hex & 255 ) / 255;
  1030. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1031. return this;
  1032. }
  1033. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  1034. this.r = r;
  1035. this.g = g;
  1036. this.b = b;
  1037. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1038. return this;
  1039. }
  1040. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  1041. // h,s,l ranges are in 0.0 - 1.0
  1042. h = euclideanModulo( h, 1 );
  1043. s = clamp( s, 0, 1 );
  1044. l = clamp( l, 0, 1 );
  1045. if ( s === 0 ) {
  1046. this.r = this.g = this.b = l;
  1047. } else {
  1048. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  1049. const q = ( 2 * l ) - p;
  1050. this.r = hue2rgb( q, p, h + 1 / 3 );
  1051. this.g = hue2rgb( q, p, h );
  1052. this.b = hue2rgb( q, p, h - 1 / 3 );
  1053. }
  1054. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1055. return this;
  1056. }
  1057. setStyle( style, colorSpace = SRGBColorSpace ) {
  1058. function handleAlpha( string ) {
  1059. if ( string === undefined ) return;
  1060. if ( parseFloat( string ) < 1 ) {
  1061. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  1062. }
  1063. }
  1064. let m;
  1065. if ( m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec( style ) ) {
  1066. // rgb / hsl
  1067. let color;
  1068. const name = m[ 1 ];
  1069. const components = m[ 2 ];
  1070. switch ( name ) {
  1071. case 'rgb':
  1072. case 'rgba':
  1073. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  1074. // rgb(255,0,0) rgba(255,0,0,0.5)
  1075. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  1076. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  1077. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  1078. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1079. handleAlpha( color[ 4 ] );
  1080. return this;
  1081. }
  1082. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  1083. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  1084. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  1085. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  1086. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  1087. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1088. handleAlpha( color[ 4 ] );
  1089. return this;
  1090. }
  1091. break;
  1092. case 'hsl':
  1093. case 'hsla':
  1094. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  1095. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  1096. const h = parseFloat( color[ 1 ] ) / 360;
  1097. const s = parseFloat( color[ 2 ] ) / 100;
  1098. const l = parseFloat( color[ 3 ] ) / 100;
  1099. handleAlpha( color[ 4 ] );
  1100. return this.setHSL( h, s, l, colorSpace );
  1101. }
  1102. break;
  1103. }
  1104. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  1105. // hex color
  1106. const hex = m[ 1 ];
  1107. const size = hex.length;
  1108. if ( size === 3 ) {
  1109. // #ff0
  1110. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  1111. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  1112. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  1113. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1114. return this;
  1115. } else if ( size === 6 ) {
  1116. // #ff0000
  1117. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  1118. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  1119. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  1120. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1121. return this;
  1122. }
  1123. }
  1124. if ( style && style.length > 0 ) {
  1125. return this.setColorName( style, colorSpace );
  1126. }
  1127. return this;
  1128. }
  1129. setColorName( style, colorSpace = SRGBColorSpace ) {
  1130. // color keywords
  1131. const hex = _colorKeywords[ style.toLowerCase() ];
  1132. if ( hex !== undefined ) {
  1133. // red
  1134. this.setHex( hex, colorSpace );
  1135. } else {
  1136. // unknown color
  1137. console.warn( 'THREE.Color: Unknown color ' + style );
  1138. }
  1139. return this;
  1140. }
  1141. clone() {
  1142. return new this.constructor( this.r, this.g, this.b );
  1143. }
  1144. copy( color ) {
  1145. this.r = color.r;
  1146. this.g = color.g;
  1147. this.b = color.b;
  1148. return this;
  1149. }
  1150. copySRGBToLinear( color ) {
  1151. this.r = SRGBToLinear( color.r );
  1152. this.g = SRGBToLinear( color.g );
  1153. this.b = SRGBToLinear( color.b );
  1154. return this;
  1155. }
  1156. copyLinearToSRGB( color ) {
  1157. this.r = LinearToSRGB( color.r );
  1158. this.g = LinearToSRGB( color.g );
  1159. this.b = LinearToSRGB( color.b );
  1160. return this;
  1161. }
  1162. convertSRGBToLinear() {
  1163. this.copySRGBToLinear( this );
  1164. return this;
  1165. }
  1166. convertLinearToSRGB() {
  1167. this.copyLinearToSRGB( this );
  1168. return this;
  1169. }
  1170. getHex( colorSpace = SRGBColorSpace ) {
  1171. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb$1 ), colorSpace );
  1172. return clamp( _rgb$1.r * 255, 0, 255 ) << 16 ^ clamp( _rgb$1.g * 255, 0, 255 ) << 8 ^ clamp( _rgb$1.b * 255, 0, 255 ) << 0;
  1173. }
  1174. getHexString( colorSpace = SRGBColorSpace ) {
  1175. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  1176. }
  1177. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  1178. // h,s,l ranges are in 0.0 - 1.0
  1179. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb$1 ), colorSpace );
  1180. const r = _rgb$1.r, g = _rgb$1.g, b = _rgb$1.b;
  1181. const max = Math.max( r, g, b );
  1182. const min = Math.min( r, g, b );
  1183. let hue, saturation;
  1184. const lightness = ( min + max ) / 2.0;
  1185. if ( min === max ) {
  1186. hue = 0;
  1187. saturation = 0;
  1188. } else {
  1189. const delta = max - min;
  1190. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  1191. switch ( max ) {
  1192. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  1193. case g: hue = ( b - r ) / delta + 2; break;
  1194. case b: hue = ( r - g ) / delta + 4; break;
  1195. }
  1196. hue /= 6;
  1197. }
  1198. target.h = hue;
  1199. target.s = saturation;
  1200. target.l = lightness;
  1201. return target;
  1202. }
  1203. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  1204. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb$1 ), colorSpace );
  1205. target.r = _rgb$1.r;
  1206. target.g = _rgb$1.g;
  1207. target.b = _rgb$1.b;
  1208. return target;
  1209. }
  1210. getStyle( colorSpace = SRGBColorSpace ) {
  1211. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb$1 ), colorSpace );
  1212. if ( colorSpace !== SRGBColorSpace ) {
  1213. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  1214. return `color(${ colorSpace } ${ _rgb$1.r } ${ _rgb$1.g } ${ _rgb$1.b })`;
  1215. }
  1216. return `rgb(${( _rgb$1.r * 255 ) | 0},${( _rgb$1.g * 255 ) | 0},${( _rgb$1.b * 255 ) | 0})`;
  1217. }
  1218. offsetHSL( h, s, l ) {
  1219. this.getHSL( _hslA );
  1220. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  1221. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  1222. return this;
  1223. }
  1224. add( color ) {
  1225. this.r += color.r;
  1226. this.g += color.g;
  1227. this.b += color.b;
  1228. return this;
  1229. }
  1230. addColors( color1, color2 ) {
  1231. this.r = color1.r + color2.r;
  1232. this.g = color1.g + color2.g;
  1233. this.b = color1.b + color2.b;
  1234. return this;
  1235. }
  1236. addScalar( s ) {
  1237. this.r += s;
  1238. this.g += s;
  1239. this.b += s;
  1240. return this;
  1241. }
  1242. sub( color ) {
  1243. this.r = Math.max( 0, this.r - color.r );
  1244. this.g = Math.max( 0, this.g - color.g );
  1245. this.b = Math.max( 0, this.b - color.b );
  1246. return this;
  1247. }
  1248. multiply( color ) {
  1249. this.r *= color.r;
  1250. this.g *= color.g;
  1251. this.b *= color.b;
  1252. return this;
  1253. }
  1254. multiplyScalar( s ) {
  1255. this.r *= s;
  1256. this.g *= s;
  1257. this.b *= s;
  1258. return this;
  1259. }
  1260. lerp( color, alpha ) {
  1261. this.r += ( color.r - this.r ) * alpha;
  1262. this.g += ( color.g - this.g ) * alpha;
  1263. this.b += ( color.b - this.b ) * alpha;
  1264. return this;
  1265. }
  1266. lerpColors( color1, color2, alpha ) {
  1267. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  1268. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  1269. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  1270. return this;
  1271. }
  1272. lerpHSL( color, alpha ) {
  1273. this.getHSL( _hslA );
  1274. color.getHSL( _hslB );
  1275. const h = lerp( _hslA.h, _hslB.h, alpha );
  1276. const s = lerp( _hslA.s, _hslB.s, alpha );
  1277. const l = lerp( _hslA.l, _hslB.l, alpha );
  1278. this.setHSL( h, s, l );
  1279. return this;
  1280. }
  1281. equals( c ) {
  1282. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  1283. }
  1284. fromArray( array, offset = 0 ) {
  1285. this.r = array[ offset ];
  1286. this.g = array[ offset + 1 ];
  1287. this.b = array[ offset + 2 ];
  1288. return this;
  1289. }
  1290. toArray( array = [], offset = 0 ) {
  1291. array[ offset ] = this.r;
  1292. array[ offset + 1 ] = this.g;
  1293. array[ offset + 2 ] = this.b;
  1294. return array;
  1295. }
  1296. fromBufferAttribute( attribute, index ) {
  1297. this.r = attribute.getX( index );
  1298. this.g = attribute.getY( index );
  1299. this.b = attribute.getZ( index );
  1300. return this;
  1301. }
  1302. toJSON() {
  1303. return this.getHex();
  1304. }
  1305. *[ Symbol.iterator ]() {
  1306. yield this.r;
  1307. yield this.g;
  1308. yield this.b;
  1309. }
  1310. }
  1311. Color.NAMES = _colorKeywords;
  1312. let _canvas;
  1313. class ImageUtils {
  1314. static getDataURL( image ) {
  1315. if ( /^data:/i.test( image.src ) ) {
  1316. return image.src;
  1317. }
  1318. if ( typeof HTMLCanvasElement == 'undefined' ) {
  1319. return image.src;
  1320. }
  1321. let canvas;
  1322. if ( image instanceof HTMLCanvasElement ) {
  1323. canvas = image;
  1324. } else {
  1325. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1326. _canvas.width = image.width;
  1327. _canvas.height = image.height;
  1328. const context = _canvas.getContext( '2d' );
  1329. if ( image instanceof ImageData ) {
  1330. context.putImageData( image, 0, 0 );
  1331. } else {
  1332. context.drawImage( image, 0, 0, image.width, image.height );
  1333. }
  1334. canvas = _canvas;
  1335. }
  1336. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1337. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1338. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1339. } else {
  1340. return canvas.toDataURL( 'image/png' );
  1341. }
  1342. }
  1343. static sRGBToLinear( image ) {
  1344. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1345. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1346. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1347. const canvas = createElementNS( 'canvas' );
  1348. canvas.width = image.width;
  1349. canvas.height = image.height;
  1350. const context = canvas.getContext( '2d' );
  1351. context.drawImage( image, 0, 0, image.width, image.height );
  1352. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1353. const data = imageData.data;
  1354. for ( let i = 0; i < data.length; i ++ ) {
  1355. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1356. }
  1357. context.putImageData( imageData, 0, 0 );
  1358. return canvas;
  1359. } else if ( image.data ) {
  1360. const data = image.data.slice( 0 );
  1361. for ( let i = 0; i < data.length; i ++ ) {
  1362. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1363. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1364. } else {
  1365. // assuming float
  1366. data[ i ] = SRGBToLinear( data[ i ] );
  1367. }
  1368. }
  1369. return {
  1370. data: data,
  1371. width: image.width,
  1372. height: image.height
  1373. };
  1374. } else {
  1375. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1376. return image;
  1377. }
  1378. }
  1379. }
  1380. class Source {
  1381. constructor( data = null ) {
  1382. this.isSource = true;
  1383. this.uuid = generateUUID();
  1384. this.data = data;
  1385. this.version = 0;
  1386. }
  1387. set needsUpdate( value ) {
  1388. if ( value === true ) this.version ++;
  1389. }
  1390. toJSON( meta ) {
  1391. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1392. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1393. return meta.images[ this.uuid ];
  1394. }
  1395. const output = {
  1396. uuid: this.uuid,
  1397. url: ''
  1398. };
  1399. const data = this.data;
  1400. if ( data !== null ) {
  1401. let url;
  1402. if ( Array.isArray( data ) ) {
  1403. // cube texture
  1404. url = [];
  1405. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1406. if ( data[ i ].isDataTexture ) {
  1407. url.push( serializeImage( data[ i ].image ) );
  1408. } else {
  1409. url.push( serializeImage( data[ i ] ) );
  1410. }
  1411. }
  1412. } else {
  1413. // texture
  1414. url = serializeImage( data );
  1415. }
  1416. output.url = url;
  1417. }
  1418. if ( ! isRootObject ) {
  1419. meta.images[ this.uuid ] = output;
  1420. }
  1421. return output;
  1422. }
  1423. }
  1424. function serializeImage( image ) {
  1425. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1426. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1427. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1428. // default images
  1429. return ImageUtils.getDataURL( image );
  1430. } else {
  1431. if ( image.data ) {
  1432. // images of DataTexture
  1433. return {
  1434. data: Array.from( image.data ),
  1435. width: image.width,
  1436. height: image.height,
  1437. type: image.data.constructor.name
  1438. };
  1439. } else {
  1440. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1441. return {};
  1442. }
  1443. }
  1444. }
  1445. let textureId = 0;
  1446. class Texture extends EventDispatcher {
  1447. 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, encoding = LinearEncoding ) {
  1448. super();
  1449. this.isTexture = true;
  1450. Object.defineProperty( this, 'id', { value: textureId ++ } );
  1451. this.uuid = generateUUID();
  1452. this.name = '';
  1453. this.source = new Source( image );
  1454. this.mipmaps = [];
  1455. this.mapping = mapping;
  1456. this.wrapS = wrapS;
  1457. this.wrapT = wrapT;
  1458. this.magFilter = magFilter;
  1459. this.minFilter = minFilter;
  1460. this.anisotropy = anisotropy;
  1461. this.format = format;
  1462. this.internalFormat = null;
  1463. this.type = type;
  1464. this.offset = new Vector2( 0, 0 );
  1465. this.repeat = new Vector2( 1, 1 );
  1466. this.center = new Vector2( 0, 0 );
  1467. this.rotation = 0;
  1468. this.matrixAutoUpdate = true;
  1469. this.matrix = new Matrix3();
  1470. this.generateMipmaps = true;
  1471. this.premultiplyAlpha = false;
  1472. this.flipY = true;
  1473. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1474. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1475. //
  1476. // Also changing the encoding after already used by a Material will not automatically make the Material
  1477. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1478. this.encoding = encoding;
  1479. this.userData = {};
  1480. this.version = 0;
  1481. this.onUpdate = null;
  1482. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1483. this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1484. }
  1485. get image() {
  1486. return this.source.data;
  1487. }
  1488. set image( value ) {
  1489. this.source.data = value;
  1490. }
  1491. updateMatrix() {
  1492. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1493. }
  1494. clone() {
  1495. return new this.constructor().copy( this );
  1496. }
  1497. copy( source ) {
  1498. this.name = source.name;
  1499. this.source = source.source;
  1500. this.mipmaps = source.mipmaps.slice( 0 );
  1501. this.mapping = source.mapping;
  1502. this.wrapS = source.wrapS;
  1503. this.wrapT = source.wrapT;
  1504. this.magFilter = source.magFilter;
  1505. this.minFilter = source.minFilter;
  1506. this.anisotropy = source.anisotropy;
  1507. this.format = source.format;
  1508. this.internalFormat = source.internalFormat;
  1509. this.type = source.type;
  1510. this.offset.copy( source.offset );
  1511. this.repeat.copy( source.repeat );
  1512. this.center.copy( source.center );
  1513. this.rotation = source.rotation;
  1514. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1515. this.matrix.copy( source.matrix );
  1516. this.generateMipmaps = source.generateMipmaps;
  1517. this.premultiplyAlpha = source.premultiplyAlpha;
  1518. this.flipY = source.flipY;
  1519. this.unpackAlignment = source.unpackAlignment;
  1520. this.encoding = source.encoding;
  1521. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1522. this.needsUpdate = true;
  1523. return this;
  1524. }
  1525. toJSON( meta ) {
  1526. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1527. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1528. return meta.textures[ this.uuid ];
  1529. }
  1530. const output = {
  1531. metadata: {
  1532. version: 4.5,
  1533. type: 'Texture',
  1534. generator: 'Texture.toJSON'
  1535. },
  1536. uuid: this.uuid,
  1537. name: this.name,
  1538. image: this.source.toJSON( meta ).uuid,
  1539. mapping: this.mapping,
  1540. repeat: [ this.repeat.x, this.repeat.y ],
  1541. offset: [ this.offset.x, this.offset.y ],
  1542. center: [ this.center.x, this.center.y ],
  1543. rotation: this.rotation,
  1544. wrap: [ this.wrapS, this.wrapT ],
  1545. format: this.format,
  1546. type: this.type,
  1547. encoding: this.encoding,
  1548. minFilter: this.minFilter,
  1549. magFilter: this.magFilter,
  1550. anisotropy: this.anisotropy,
  1551. flipY: this.flipY,
  1552. generateMipmaps: this.generateMipmaps,
  1553. premultiplyAlpha: this.premultiplyAlpha,
  1554. unpackAlignment: this.unpackAlignment
  1555. };
  1556. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  1557. if ( ! isRootObject ) {
  1558. meta.textures[ this.uuid ] = output;
  1559. }
  1560. return output;
  1561. }
  1562. dispose() {
  1563. this.dispatchEvent( { type: 'dispose' } );
  1564. }
  1565. transformUv( uv ) {
  1566. if ( this.mapping !== UVMapping ) return uv;
  1567. uv.applyMatrix3( this.matrix );
  1568. if ( uv.x < 0 || uv.x > 1 ) {
  1569. switch ( this.wrapS ) {
  1570. case RepeatWrapping:
  1571. uv.x = uv.x - Math.floor( uv.x );
  1572. break;
  1573. case ClampToEdgeWrapping:
  1574. uv.x = uv.x < 0 ? 0 : 1;
  1575. break;
  1576. case MirroredRepeatWrapping:
  1577. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1578. uv.x = Math.ceil( uv.x ) - uv.x;
  1579. } else {
  1580. uv.x = uv.x - Math.floor( uv.x );
  1581. }
  1582. break;
  1583. }
  1584. }
  1585. if ( uv.y < 0 || uv.y > 1 ) {
  1586. switch ( this.wrapT ) {
  1587. case RepeatWrapping:
  1588. uv.y = uv.y - Math.floor( uv.y );
  1589. break;
  1590. case ClampToEdgeWrapping:
  1591. uv.y = uv.y < 0 ? 0 : 1;
  1592. break;
  1593. case MirroredRepeatWrapping:
  1594. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1595. uv.y = Math.ceil( uv.y ) - uv.y;
  1596. } else {
  1597. uv.y = uv.y - Math.floor( uv.y );
  1598. }
  1599. break;
  1600. }
  1601. }
  1602. if ( this.flipY ) {
  1603. uv.y = 1 - uv.y;
  1604. }
  1605. return uv;
  1606. }
  1607. set needsUpdate( value ) {
  1608. if ( value === true ) {
  1609. this.version ++;
  1610. this.source.needsUpdate = true;
  1611. }
  1612. }
  1613. }
  1614. Texture.DEFAULT_IMAGE = null;
  1615. Texture.DEFAULT_MAPPING = UVMapping;
  1616. Texture.DEFAULT_ANISOTROPY = 1;
  1617. class Vector4 {
  1618. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1619. Vector4.prototype.isVector4 = true;
  1620. this.x = x;
  1621. this.y = y;
  1622. this.z = z;
  1623. this.w = w;
  1624. }
  1625. get width() {
  1626. return this.z;
  1627. }
  1628. set width( value ) {
  1629. this.z = value;
  1630. }
  1631. get height() {
  1632. return this.w;
  1633. }
  1634. set height( value ) {
  1635. this.w = value;
  1636. }
  1637. set( x, y, z, w ) {
  1638. this.x = x;
  1639. this.y = y;
  1640. this.z = z;
  1641. this.w = w;
  1642. return this;
  1643. }
  1644. setScalar( scalar ) {
  1645. this.x = scalar;
  1646. this.y = scalar;
  1647. this.z = scalar;
  1648. this.w = scalar;
  1649. return this;
  1650. }
  1651. setX( x ) {
  1652. this.x = x;
  1653. return this;
  1654. }
  1655. setY( y ) {
  1656. this.y = y;
  1657. return this;
  1658. }
  1659. setZ( z ) {
  1660. this.z = z;
  1661. return this;
  1662. }
  1663. setW( w ) {
  1664. this.w = w;
  1665. return this;
  1666. }
  1667. setComponent( index, value ) {
  1668. switch ( index ) {
  1669. case 0: this.x = value; break;
  1670. case 1: this.y = value; break;
  1671. case 2: this.z = value; break;
  1672. case 3: this.w = value; break;
  1673. default: throw new Error( 'index is out of range: ' + index );
  1674. }
  1675. return this;
  1676. }
  1677. getComponent( index ) {
  1678. switch ( index ) {
  1679. case 0: return this.x;
  1680. case 1: return this.y;
  1681. case 2: return this.z;
  1682. case 3: return this.w;
  1683. default: throw new Error( 'index is out of range: ' + index );
  1684. }
  1685. }
  1686. clone() {
  1687. return new this.constructor( this.x, this.y, this.z, this.w );
  1688. }
  1689. copy( v ) {
  1690. this.x = v.x;
  1691. this.y = v.y;
  1692. this.z = v.z;
  1693. this.w = ( v.w !== undefined ) ? v.w : 1;
  1694. return this;
  1695. }
  1696. add( v ) {
  1697. this.x += v.x;
  1698. this.y += v.y;
  1699. this.z += v.z;
  1700. this.w += v.w;
  1701. return this;
  1702. }
  1703. addScalar( s ) {
  1704. this.x += s;
  1705. this.y += s;
  1706. this.z += s;
  1707. this.w += s;
  1708. return this;
  1709. }
  1710. addVectors( a, b ) {
  1711. this.x = a.x + b.x;
  1712. this.y = a.y + b.y;
  1713. this.z = a.z + b.z;
  1714. this.w = a.w + b.w;
  1715. return this;
  1716. }
  1717. addScaledVector( v, s ) {
  1718. this.x += v.x * s;
  1719. this.y += v.y * s;
  1720. this.z += v.z * s;
  1721. this.w += v.w * s;
  1722. return this;
  1723. }
  1724. sub( v ) {
  1725. this.x -= v.x;
  1726. this.y -= v.y;
  1727. this.z -= v.z;
  1728. this.w -= v.w;
  1729. return this;
  1730. }
  1731. subScalar( s ) {
  1732. this.x -= s;
  1733. this.y -= s;
  1734. this.z -= s;
  1735. this.w -= s;
  1736. return this;
  1737. }
  1738. subVectors( a, b ) {
  1739. this.x = a.x - b.x;
  1740. this.y = a.y - b.y;
  1741. this.z = a.z - b.z;
  1742. this.w = a.w - b.w;
  1743. return this;
  1744. }
  1745. multiply( v ) {
  1746. this.x *= v.x;
  1747. this.y *= v.y;
  1748. this.z *= v.z;
  1749. this.w *= v.w;
  1750. return this;
  1751. }
  1752. multiplyScalar( scalar ) {
  1753. this.x *= scalar;
  1754. this.y *= scalar;
  1755. this.z *= scalar;
  1756. this.w *= scalar;
  1757. return this;
  1758. }
  1759. applyMatrix4( m ) {
  1760. const x = this.x, y = this.y, z = this.z, w = this.w;
  1761. const e = m.elements;
  1762. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1763. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1764. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1765. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1766. return this;
  1767. }
  1768. divideScalar( scalar ) {
  1769. return this.multiplyScalar( 1 / scalar );
  1770. }
  1771. setAxisAngleFromQuaternion( q ) {
  1772. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1773. // q is assumed to be normalized
  1774. this.w = 2 * Math.acos( q.w );
  1775. const s = Math.sqrt( 1 - q.w * q.w );
  1776. if ( s < 0.0001 ) {
  1777. this.x = 1;
  1778. this.y = 0;
  1779. this.z = 0;
  1780. } else {
  1781. this.x = q.x / s;
  1782. this.y = q.y / s;
  1783. this.z = q.z / s;
  1784. }
  1785. return this;
  1786. }
  1787. setAxisAngleFromRotationMatrix( m ) {
  1788. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1789. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1790. let angle, x, y, z; // variables for result
  1791. const epsilon = 0.01, // margin to allow for rounding errors
  1792. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1793. te = m.elements,
  1794. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1795. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1796. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1797. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1798. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1799. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1800. // singularity found
  1801. // first check for identity matrix which must have +1 for all terms
  1802. // in leading diagonal and zero in other terms
  1803. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1804. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1805. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1806. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1807. // this singularity is identity matrix so angle = 0
  1808. this.set( 1, 0, 0, 0 );
  1809. return this; // zero angle, arbitrary axis
  1810. }
  1811. // otherwise this singularity is angle = 180
  1812. angle = Math.PI;
  1813. const xx = ( m11 + 1 ) / 2;
  1814. const yy = ( m22 + 1 ) / 2;
  1815. const zz = ( m33 + 1 ) / 2;
  1816. const xy = ( m12 + m21 ) / 4;
  1817. const xz = ( m13 + m31 ) / 4;
  1818. const yz = ( m23 + m32 ) / 4;
  1819. if ( ( xx > yy ) && ( xx > zz ) ) {
  1820. // m11 is the largest diagonal term
  1821. if ( xx < epsilon ) {
  1822. x = 0;
  1823. y = 0.707106781;
  1824. z = 0.707106781;
  1825. } else {
  1826. x = Math.sqrt( xx );
  1827. y = xy / x;
  1828. z = xz / x;
  1829. }
  1830. } else if ( yy > zz ) {
  1831. // m22 is the largest diagonal term
  1832. if ( yy < epsilon ) {
  1833. x = 0.707106781;
  1834. y = 0;
  1835. z = 0.707106781;
  1836. } else {
  1837. y = Math.sqrt( yy );
  1838. x = xy / y;
  1839. z = yz / y;
  1840. }
  1841. } else {
  1842. // m33 is the largest diagonal term so base result on this
  1843. if ( zz < epsilon ) {
  1844. x = 0.707106781;
  1845. y = 0.707106781;
  1846. z = 0;
  1847. } else {
  1848. z = Math.sqrt( zz );
  1849. x = xz / z;
  1850. y = yz / z;
  1851. }
  1852. }
  1853. this.set( x, y, z, angle );
  1854. return this; // return 180 deg rotation
  1855. }
  1856. // as we have reached here there are no singularities so we can handle normally
  1857. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1858. ( m13 - m31 ) * ( m13 - m31 ) +
  1859. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1860. if ( Math.abs( s ) < 0.001 ) s = 1;
  1861. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1862. // caught by singularity test above, but I've left it in just in case
  1863. this.x = ( m32 - m23 ) / s;
  1864. this.y = ( m13 - m31 ) / s;
  1865. this.z = ( m21 - m12 ) / s;
  1866. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1867. return this;
  1868. }
  1869. min( v ) {
  1870. this.x = Math.min( this.x, v.x );
  1871. this.y = Math.min( this.y, v.y );
  1872. this.z = Math.min( this.z, v.z );
  1873. this.w = Math.min( this.w, v.w );
  1874. return this;
  1875. }
  1876. max( v ) {
  1877. this.x = Math.max( this.x, v.x );
  1878. this.y = Math.max( this.y, v.y );
  1879. this.z = Math.max( this.z, v.z );
  1880. this.w = Math.max( this.w, v.w );
  1881. return this;
  1882. }
  1883. clamp( min, max ) {
  1884. // assumes min < max, componentwise
  1885. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1886. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1887. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1888. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1889. return this;
  1890. }
  1891. clampScalar( minVal, maxVal ) {
  1892. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1893. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1894. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1895. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1896. return this;
  1897. }
  1898. clampLength( min, max ) {
  1899. const length = this.length();
  1900. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1901. }
  1902. floor() {
  1903. this.x = Math.floor( this.x );
  1904. this.y = Math.floor( this.y );
  1905. this.z = Math.floor( this.z );
  1906. this.w = Math.floor( this.w );
  1907. return this;
  1908. }
  1909. ceil() {
  1910. this.x = Math.ceil( this.x );
  1911. this.y = Math.ceil( this.y );
  1912. this.z = Math.ceil( this.z );
  1913. this.w = Math.ceil( this.w );
  1914. return this;
  1915. }
  1916. round() {
  1917. this.x = Math.round( this.x );
  1918. this.y = Math.round( this.y );
  1919. this.z = Math.round( this.z );
  1920. this.w = Math.round( this.w );
  1921. return this;
  1922. }
  1923. roundToZero() {
  1924. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1925. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1926. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1927. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1928. return this;
  1929. }
  1930. negate() {
  1931. this.x = - this.x;
  1932. this.y = - this.y;
  1933. this.z = - this.z;
  1934. this.w = - this.w;
  1935. return this;
  1936. }
  1937. dot( v ) {
  1938. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1939. }
  1940. lengthSq() {
  1941. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1942. }
  1943. length() {
  1944. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1945. }
  1946. manhattanLength() {
  1947. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1948. }
  1949. normalize() {
  1950. return this.divideScalar( this.length() || 1 );
  1951. }
  1952. setLength( length ) {
  1953. return this.normalize().multiplyScalar( length );
  1954. }
  1955. lerp( v, alpha ) {
  1956. this.x += ( v.x - this.x ) * alpha;
  1957. this.y += ( v.y - this.y ) * alpha;
  1958. this.z += ( v.z - this.z ) * alpha;
  1959. this.w += ( v.w - this.w ) * alpha;
  1960. return this;
  1961. }
  1962. lerpVectors( v1, v2, alpha ) {
  1963. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1964. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1965. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1966. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1967. return this;
  1968. }
  1969. equals( v ) {
  1970. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1971. }
  1972. fromArray( array, offset = 0 ) {
  1973. this.x = array[ offset ];
  1974. this.y = array[ offset + 1 ];
  1975. this.z = array[ offset + 2 ];
  1976. this.w = array[ offset + 3 ];
  1977. return this;
  1978. }
  1979. toArray( array = [], offset = 0 ) {
  1980. array[ offset ] = this.x;
  1981. array[ offset + 1 ] = this.y;
  1982. array[ offset + 2 ] = this.z;
  1983. array[ offset + 3 ] = this.w;
  1984. return array;
  1985. }
  1986. fromBufferAttribute( attribute, index ) {
  1987. this.x = attribute.getX( index );
  1988. this.y = attribute.getY( index );
  1989. this.z = attribute.getZ( index );
  1990. this.w = attribute.getW( index );
  1991. return this;
  1992. }
  1993. random() {
  1994. this.x = Math.random();
  1995. this.y = Math.random();
  1996. this.z = Math.random();
  1997. this.w = Math.random();
  1998. return this;
  1999. }
  2000. *[ Symbol.iterator ]() {
  2001. yield this.x;
  2002. yield this.y;
  2003. yield this.z;
  2004. yield this.w;
  2005. }
  2006. }
  2007. /*
  2008. In options, we can specify:
  2009. * Texture parameters for an auto-generated target texture
  2010. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2011. */
  2012. class WebGLRenderTarget extends EventDispatcher {
  2013. constructor( width = 1, height = 1, options = {} ) {
  2014. super();
  2015. this.isWebGLRenderTarget = true;
  2016. this.width = width;
  2017. this.height = height;
  2018. this.depth = 1;
  2019. this.scissor = new Vector4( 0, 0, width, height );
  2020. this.scissorTest = false;
  2021. this.viewport = new Vector4( 0, 0, width, height );
  2022. const image = { width: width, height: height, depth: 1 };
  2023. this.texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  2024. this.texture.isRenderTargetTexture = true;
  2025. this.texture.flipY = false;
  2026. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2027. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  2028. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2029. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2030. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  2031. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2032. this.samples = options.samples !== undefined ? options.samples : 0;
  2033. }
  2034. setSize( width, height, depth = 1 ) {
  2035. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  2036. this.width = width;
  2037. this.height = height;
  2038. this.depth = depth;
  2039. this.texture.image.width = width;
  2040. this.texture.image.height = height;
  2041. this.texture.image.depth = depth;
  2042. this.dispose();
  2043. }
  2044. this.viewport.set( 0, 0, width, height );
  2045. this.scissor.set( 0, 0, width, height );
  2046. }
  2047. clone() {
  2048. return new this.constructor().copy( this );
  2049. }
  2050. copy( source ) {
  2051. this.width = source.width;
  2052. this.height = source.height;
  2053. this.depth = source.depth;
  2054. this.viewport.copy( source.viewport );
  2055. this.texture = source.texture.clone();
  2056. this.texture.isRenderTargetTexture = true;
  2057. // ensure image object is not shared, see #20328
  2058. const image = Object.assign( {}, source.texture.image );
  2059. this.texture.source = new Source( image );
  2060. this.depthBuffer = source.depthBuffer;
  2061. this.stencilBuffer = source.stencilBuffer;
  2062. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  2063. this.samples = source.samples;
  2064. return this;
  2065. }
  2066. dispose() {
  2067. this.dispatchEvent( { type: 'dispose' } );
  2068. }
  2069. }
  2070. class DataArrayTexture extends Texture {
  2071. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  2072. super( null );
  2073. this.isDataArrayTexture = true;
  2074. this.image = { data, width, height, depth };
  2075. this.magFilter = NearestFilter;
  2076. this.minFilter = NearestFilter;
  2077. this.wrapR = ClampToEdgeWrapping;
  2078. this.generateMipmaps = false;
  2079. this.flipY = false;
  2080. this.unpackAlignment = 1;
  2081. }
  2082. }
  2083. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  2084. constructor( width = 1, height = 1, depth = 1 ) {
  2085. super( width, height );
  2086. this.isWebGLArrayRenderTarget = true;
  2087. this.depth = depth;
  2088. this.texture = new DataArrayTexture( null, width, height, depth );
  2089. this.texture.isRenderTargetTexture = true;
  2090. }
  2091. }
  2092. class Data3DTexture extends Texture {
  2093. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  2094. // We're going to add .setXXX() methods for setting properties later.
  2095. // Users can still set in DataTexture3D directly.
  2096. //
  2097. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  2098. // texture.anisotropy = 16;
  2099. //
  2100. // See #14839
  2101. super( null );
  2102. this.isData3DTexture = true;
  2103. this.image = { data, width, height, depth };
  2104. this.magFilter = NearestFilter;
  2105. this.minFilter = NearestFilter;
  2106. this.wrapR = ClampToEdgeWrapping;
  2107. this.generateMipmaps = false;
  2108. this.flipY = false;
  2109. this.unpackAlignment = 1;
  2110. }
  2111. }
  2112. class WebGL3DRenderTarget extends WebGLRenderTarget {
  2113. constructor( width = 1, height = 1, depth = 1 ) {
  2114. super( width, height );
  2115. this.isWebGL3DRenderTarget = true;
  2116. this.depth = depth;
  2117. this.texture = new Data3DTexture( null, width, height, depth );
  2118. this.texture.isRenderTargetTexture = true;
  2119. }
  2120. }
  2121. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  2122. constructor( width = 1, height = 1, count = 1, options = {} ) {
  2123. super( width, height, options );
  2124. this.isWebGLMultipleRenderTargets = true;
  2125. const texture = this.texture;
  2126. this.texture = [];
  2127. for ( let i = 0; i < count; i ++ ) {
  2128. this.texture[ i ] = texture.clone();
  2129. this.texture[ i ].isRenderTargetTexture = true;
  2130. }
  2131. }
  2132. setSize( width, height, depth = 1 ) {
  2133. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  2134. this.width = width;
  2135. this.height = height;
  2136. this.depth = depth;
  2137. for ( let i = 0, il = this.texture.length; i < il; i ++ ) {
  2138. this.texture[ i ].image.width = width;
  2139. this.texture[ i ].image.height = height;
  2140. this.texture[ i ].image.depth = depth;
  2141. }
  2142. this.dispose();
  2143. }
  2144. this.viewport.set( 0, 0, width, height );
  2145. this.scissor.set( 0, 0, width, height );
  2146. return this;
  2147. }
  2148. copy( source ) {
  2149. this.dispose();
  2150. this.width = source.width;
  2151. this.height = source.height;
  2152. this.depth = source.depth;
  2153. this.viewport.set( 0, 0, this.width, this.height );
  2154. this.scissor.set( 0, 0, this.width, this.height );
  2155. this.depthBuffer = source.depthBuffer;
  2156. this.stencilBuffer = source.stencilBuffer;
  2157. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  2158. this.texture.length = 0;
  2159. for ( let i = 0, il = source.texture.length; i < il; i ++ ) {
  2160. this.texture[ i ] = source.texture[ i ].clone();
  2161. this.texture[ i ].isRenderTargetTexture = true;
  2162. }
  2163. return this;
  2164. }
  2165. }
  2166. class Quaternion {
  2167. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2168. this.isQuaternion = true;
  2169. this._x = x;
  2170. this._y = y;
  2171. this._z = z;
  2172. this._w = w;
  2173. }
  2174. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  2175. // fuzz-free, array-based Quaternion SLERP operation
  2176. let x0 = src0[ srcOffset0 + 0 ],
  2177. y0 = src0[ srcOffset0 + 1 ],
  2178. z0 = src0[ srcOffset0 + 2 ],
  2179. w0 = src0[ srcOffset0 + 3 ];
  2180. const x1 = src1[ srcOffset1 + 0 ],
  2181. y1 = src1[ srcOffset1 + 1 ],
  2182. z1 = src1[ srcOffset1 + 2 ],
  2183. w1 = src1[ srcOffset1 + 3 ];
  2184. if ( t === 0 ) {
  2185. dst[ dstOffset + 0 ] = x0;
  2186. dst[ dstOffset + 1 ] = y0;
  2187. dst[ dstOffset + 2 ] = z0;
  2188. dst[ dstOffset + 3 ] = w0;
  2189. return;
  2190. }
  2191. if ( t === 1 ) {
  2192. dst[ dstOffset + 0 ] = x1;
  2193. dst[ dstOffset + 1 ] = y1;
  2194. dst[ dstOffset + 2 ] = z1;
  2195. dst[ dstOffset + 3 ] = w1;
  2196. return;
  2197. }
  2198. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  2199. let s = 1 - t;
  2200. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2201. dir = ( cos >= 0 ? 1 : - 1 ),
  2202. sqrSin = 1 - cos * cos;
  2203. // Skip the Slerp for tiny steps to avoid numeric problems:
  2204. if ( sqrSin > Number.EPSILON ) {
  2205. const sin = Math.sqrt( sqrSin ),
  2206. len = Math.atan2( sin, cos * dir );
  2207. s = Math.sin( s * len ) / sin;
  2208. t = Math.sin( t * len ) / sin;
  2209. }
  2210. const tDir = t * dir;
  2211. x0 = x0 * s + x1 * tDir;
  2212. y0 = y0 * s + y1 * tDir;
  2213. z0 = z0 * s + z1 * tDir;
  2214. w0 = w0 * s + w1 * tDir;
  2215. // Normalize in case we just did a lerp:
  2216. if ( s === 1 - t ) {
  2217. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2218. x0 *= f;
  2219. y0 *= f;
  2220. z0 *= f;
  2221. w0 *= f;
  2222. }
  2223. }
  2224. dst[ dstOffset ] = x0;
  2225. dst[ dstOffset + 1 ] = y0;
  2226. dst[ dstOffset + 2 ] = z0;
  2227. dst[ dstOffset + 3 ] = w0;
  2228. }
  2229. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2230. const x0 = src0[ srcOffset0 ];
  2231. const y0 = src0[ srcOffset0 + 1 ];
  2232. const z0 = src0[ srcOffset0 + 2 ];
  2233. const w0 = src0[ srcOffset0 + 3 ];
  2234. const x1 = src1[ srcOffset1 ];
  2235. const y1 = src1[ srcOffset1 + 1 ];
  2236. const z1 = src1[ srcOffset1 + 2 ];
  2237. const w1 = src1[ srcOffset1 + 3 ];
  2238. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2239. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2240. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2241. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2242. return dst;
  2243. }
  2244. get x() {
  2245. return this._x;
  2246. }
  2247. set x( value ) {
  2248. this._x = value;
  2249. this._onChangeCallback();
  2250. }
  2251. get y() {
  2252. return this._y;
  2253. }
  2254. set y( value ) {
  2255. this._y = value;
  2256. this._onChangeCallback();
  2257. }
  2258. get z() {
  2259. return this._z;
  2260. }
  2261. set z( value ) {
  2262. this._z = value;
  2263. this._onChangeCallback();
  2264. }
  2265. get w() {
  2266. return this._w;
  2267. }
  2268. set w( value ) {
  2269. this._w = value;
  2270. this._onChangeCallback();
  2271. }
  2272. set( x, y, z, w ) {
  2273. this._x = x;
  2274. this._y = y;
  2275. this._z = z;
  2276. this._w = w;
  2277. this._onChangeCallback();
  2278. return this;
  2279. }
  2280. clone() {
  2281. return new this.constructor( this._x, this._y, this._z, this._w );
  2282. }
  2283. copy( quaternion ) {
  2284. this._x = quaternion.x;
  2285. this._y = quaternion.y;
  2286. this._z = quaternion.z;
  2287. this._w = quaternion.w;
  2288. this._onChangeCallback();
  2289. return this;
  2290. }
  2291. setFromEuler( euler, update ) {
  2292. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2293. // http://www.mathworks.com/matlabcentral/fileexchange/
  2294. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2295. // content/SpinCalc.m
  2296. const cos = Math.cos;
  2297. const sin = Math.sin;
  2298. const c1 = cos( x / 2 );
  2299. const c2 = cos( y / 2 );
  2300. const c3 = cos( z / 2 );
  2301. const s1 = sin( x / 2 );
  2302. const s2 = sin( y / 2 );
  2303. const s3 = sin( z / 2 );
  2304. switch ( order ) {
  2305. case 'XYZ':
  2306. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2307. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2308. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2309. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2310. break;
  2311. case 'YXZ':
  2312. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2313. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2314. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2315. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2316. break;
  2317. case 'ZXY':
  2318. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2319. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2320. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2321. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2322. break;
  2323. case 'ZYX':
  2324. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2325. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2326. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2327. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2328. break;
  2329. case 'YZX':
  2330. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2331. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2332. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2333. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2334. break;
  2335. case 'XZY':
  2336. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2337. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2338. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2339. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2340. break;
  2341. default:
  2342. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2343. }
  2344. if ( update !== false ) this._onChangeCallback();
  2345. return this;
  2346. }
  2347. setFromAxisAngle( axis, angle ) {
  2348. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2349. // assumes axis is normalized
  2350. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2351. this._x = axis.x * s;
  2352. this._y = axis.y * s;
  2353. this._z = axis.z * s;
  2354. this._w = Math.cos( halfAngle );
  2355. this._onChangeCallback();
  2356. return this;
  2357. }
  2358. setFromRotationMatrix( m ) {
  2359. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2360. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2361. const te = m.elements,
  2362. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2363. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2364. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2365. trace = m11 + m22 + m33;
  2366. if ( trace > 0 ) {
  2367. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2368. this._w = 0.25 / s;
  2369. this._x = ( m32 - m23 ) * s;
  2370. this._y = ( m13 - m31 ) * s;
  2371. this._z = ( m21 - m12 ) * s;
  2372. } else if ( m11 > m22 && m11 > m33 ) {
  2373. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2374. this._w = ( m32 - m23 ) / s;
  2375. this._x = 0.25 * s;
  2376. this._y = ( m12 + m21 ) / s;
  2377. this._z = ( m13 + m31 ) / s;
  2378. } else if ( m22 > m33 ) {
  2379. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2380. this._w = ( m13 - m31 ) / s;
  2381. this._x = ( m12 + m21 ) / s;
  2382. this._y = 0.25 * s;
  2383. this._z = ( m23 + m32 ) / s;
  2384. } else {
  2385. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2386. this._w = ( m21 - m12 ) / s;
  2387. this._x = ( m13 + m31 ) / s;
  2388. this._y = ( m23 + m32 ) / s;
  2389. this._z = 0.25 * s;
  2390. }
  2391. this._onChangeCallback();
  2392. return this;
  2393. }
  2394. setFromUnitVectors( vFrom, vTo ) {
  2395. // assumes direction vectors vFrom and vTo are normalized
  2396. let r = vFrom.dot( vTo ) + 1;
  2397. if ( r < Number.EPSILON ) {
  2398. // vFrom and vTo point in opposite directions
  2399. r = 0;
  2400. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2401. this._x = - vFrom.y;
  2402. this._y = vFrom.x;
  2403. this._z = 0;
  2404. this._w = r;
  2405. } else {
  2406. this._x = 0;
  2407. this._y = - vFrom.z;
  2408. this._z = vFrom.y;
  2409. this._w = r;
  2410. }
  2411. } else {
  2412. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2413. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2414. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2415. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2416. this._w = r;
  2417. }
  2418. return this.normalize();
  2419. }
  2420. angleTo( q ) {
  2421. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  2422. }
  2423. rotateTowards( q, step ) {
  2424. const angle = this.angleTo( q );
  2425. if ( angle === 0 ) return this;
  2426. const t = Math.min( 1, step / angle );
  2427. this.slerp( q, t );
  2428. return this;
  2429. }
  2430. identity() {
  2431. return this.set( 0, 0, 0, 1 );
  2432. }
  2433. invert() {
  2434. // quaternion is assumed to have unit length
  2435. return this.conjugate();
  2436. }
  2437. conjugate() {
  2438. this._x *= - 1;
  2439. this._y *= - 1;
  2440. this._z *= - 1;
  2441. this._onChangeCallback();
  2442. return this;
  2443. }
  2444. dot( v ) {
  2445. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2446. }
  2447. lengthSq() {
  2448. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2449. }
  2450. length() {
  2451. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2452. }
  2453. normalize() {
  2454. let l = this.length();
  2455. if ( l === 0 ) {
  2456. this._x = 0;
  2457. this._y = 0;
  2458. this._z = 0;
  2459. this._w = 1;
  2460. } else {
  2461. l = 1 / l;
  2462. this._x = this._x * l;
  2463. this._y = this._y * l;
  2464. this._z = this._z * l;
  2465. this._w = this._w * l;
  2466. }
  2467. this._onChangeCallback();
  2468. return this;
  2469. }
  2470. multiply( q ) {
  2471. return this.multiplyQuaternions( this, q );
  2472. }
  2473. premultiply( q ) {
  2474. return this.multiplyQuaternions( q, this );
  2475. }
  2476. multiplyQuaternions( a, b ) {
  2477. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2478. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2479. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2480. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2481. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2482. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2483. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2484. this._onChangeCallback();
  2485. return this;
  2486. }
  2487. slerp( qb, t ) {
  2488. if ( t === 0 ) return this;
  2489. if ( t === 1 ) return this.copy( qb );
  2490. const x = this._x, y = this._y, z = this._z, w = this._w;
  2491. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2492. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2493. if ( cosHalfTheta < 0 ) {
  2494. this._w = - qb._w;
  2495. this._x = - qb._x;
  2496. this._y = - qb._y;
  2497. this._z = - qb._z;
  2498. cosHalfTheta = - cosHalfTheta;
  2499. } else {
  2500. this.copy( qb );
  2501. }
  2502. if ( cosHalfTheta >= 1.0 ) {
  2503. this._w = w;
  2504. this._x = x;
  2505. this._y = y;
  2506. this._z = z;
  2507. return this;
  2508. }
  2509. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2510. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2511. const s = 1 - t;
  2512. this._w = s * w + t * this._w;
  2513. this._x = s * x + t * this._x;
  2514. this._y = s * y + t * this._y;
  2515. this._z = s * z + t * this._z;
  2516. this.normalize();
  2517. this._onChangeCallback();
  2518. return this;
  2519. }
  2520. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2521. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2522. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2523. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2524. this._w = ( w * ratioA + this._w * ratioB );
  2525. this._x = ( x * ratioA + this._x * ratioB );
  2526. this._y = ( y * ratioA + this._y * ratioB );
  2527. this._z = ( z * ratioA + this._z * ratioB );
  2528. this._onChangeCallback();
  2529. return this;
  2530. }
  2531. slerpQuaternions( qa, qb, t ) {
  2532. return this.copy( qa ).slerp( qb, t );
  2533. }
  2534. random() {
  2535. // Derived from http://planning.cs.uiuc.edu/node198.html
  2536. // Note, this source uses w, x, y, z ordering,
  2537. // so we swap the order below.
  2538. const u1 = Math.random();
  2539. const sqrt1u1 = Math.sqrt( 1 - u1 );
  2540. const sqrtu1 = Math.sqrt( u1 );
  2541. const u2 = 2 * Math.PI * Math.random();
  2542. const u3 = 2 * Math.PI * Math.random();
  2543. return this.set(
  2544. sqrt1u1 * Math.cos( u2 ),
  2545. sqrtu1 * Math.sin( u3 ),
  2546. sqrtu1 * Math.cos( u3 ),
  2547. sqrt1u1 * Math.sin( u2 ),
  2548. );
  2549. }
  2550. equals( quaternion ) {
  2551. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2552. }
  2553. fromArray( array, offset = 0 ) {
  2554. this._x = array[ offset ];
  2555. this._y = array[ offset + 1 ];
  2556. this._z = array[ offset + 2 ];
  2557. this._w = array[ offset + 3 ];
  2558. this._onChangeCallback();
  2559. return this;
  2560. }
  2561. toArray( array = [], offset = 0 ) {
  2562. array[ offset ] = this._x;
  2563. array[ offset + 1 ] = this._y;
  2564. array[ offset + 2 ] = this._z;
  2565. array[ offset + 3 ] = this._w;
  2566. return array;
  2567. }
  2568. fromBufferAttribute( attribute, index ) {
  2569. this._x = attribute.getX( index );
  2570. this._y = attribute.getY( index );
  2571. this._z = attribute.getZ( index );
  2572. this._w = attribute.getW( index );
  2573. return this;
  2574. }
  2575. _onChange( callback ) {
  2576. this._onChangeCallback = callback;
  2577. return this;
  2578. }
  2579. _onChangeCallback() {}
  2580. *[ Symbol.iterator ]() {
  2581. yield this._x;
  2582. yield this._y;
  2583. yield this._z;
  2584. yield this._w;
  2585. }
  2586. }
  2587. class Vector3 {
  2588. constructor( x = 0, y = 0, z = 0 ) {
  2589. Vector3.prototype.isVector3 = true;
  2590. this.x = x;
  2591. this.y = y;
  2592. this.z = z;
  2593. }
  2594. set( x, y, z ) {
  2595. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2596. this.x = x;
  2597. this.y = y;
  2598. this.z = z;
  2599. return this;
  2600. }
  2601. setScalar( scalar ) {
  2602. this.x = scalar;
  2603. this.y = scalar;
  2604. this.z = scalar;
  2605. return this;
  2606. }
  2607. setX( x ) {
  2608. this.x = x;
  2609. return this;
  2610. }
  2611. setY( y ) {
  2612. this.y = y;
  2613. return this;
  2614. }
  2615. setZ( z ) {
  2616. this.z = z;
  2617. return this;
  2618. }
  2619. setComponent( index, value ) {
  2620. switch ( index ) {
  2621. case 0: this.x = value; break;
  2622. case 1: this.y = value; break;
  2623. case 2: this.z = value; break;
  2624. default: throw new Error( 'index is out of range: ' + index );
  2625. }
  2626. return this;
  2627. }
  2628. getComponent( index ) {
  2629. switch ( index ) {
  2630. case 0: return this.x;
  2631. case 1: return this.y;
  2632. case 2: return this.z;
  2633. default: throw new Error( 'index is out of range: ' + index );
  2634. }
  2635. }
  2636. clone() {
  2637. return new this.constructor( this.x, this.y, this.z );
  2638. }
  2639. copy( v ) {
  2640. this.x = v.x;
  2641. this.y = v.y;
  2642. this.z = v.z;
  2643. return this;
  2644. }
  2645. add( v ) {
  2646. this.x += v.x;
  2647. this.y += v.y;
  2648. this.z += v.z;
  2649. return this;
  2650. }
  2651. addScalar( s ) {
  2652. this.x += s;
  2653. this.y += s;
  2654. this.z += s;
  2655. return this;
  2656. }
  2657. addVectors( a, b ) {
  2658. this.x = a.x + b.x;
  2659. this.y = a.y + b.y;
  2660. this.z = a.z + b.z;
  2661. return this;
  2662. }
  2663. addScaledVector( v, s ) {
  2664. this.x += v.x * s;
  2665. this.y += v.y * s;
  2666. this.z += v.z * s;
  2667. return this;
  2668. }
  2669. sub( v ) {
  2670. this.x -= v.x;
  2671. this.y -= v.y;
  2672. this.z -= v.z;
  2673. return this;
  2674. }
  2675. subScalar( s ) {
  2676. this.x -= s;
  2677. this.y -= s;
  2678. this.z -= s;
  2679. return this;
  2680. }
  2681. subVectors( a, b ) {
  2682. this.x = a.x - b.x;
  2683. this.y = a.y - b.y;
  2684. this.z = a.z - b.z;
  2685. return this;
  2686. }
  2687. multiply( v ) {
  2688. this.x *= v.x;
  2689. this.y *= v.y;
  2690. this.z *= v.z;
  2691. return this;
  2692. }
  2693. multiplyScalar( scalar ) {
  2694. this.x *= scalar;
  2695. this.y *= scalar;
  2696. this.z *= scalar;
  2697. return this;
  2698. }
  2699. multiplyVectors( a, b ) {
  2700. this.x = a.x * b.x;
  2701. this.y = a.y * b.y;
  2702. this.z = a.z * b.z;
  2703. return this;
  2704. }
  2705. applyEuler( euler ) {
  2706. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2707. }
  2708. applyAxisAngle( axis, angle ) {
  2709. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2710. }
  2711. applyMatrix3( m ) {
  2712. const x = this.x, y = this.y, z = this.z;
  2713. const e = m.elements;
  2714. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2715. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2716. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2717. return this;
  2718. }
  2719. applyNormalMatrix( m ) {
  2720. return this.applyMatrix3( m ).normalize();
  2721. }
  2722. applyMatrix4( m ) {
  2723. const x = this.x, y = this.y, z = this.z;
  2724. const e = m.elements;
  2725. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2726. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2727. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2728. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2729. return this;
  2730. }
  2731. applyQuaternion( q ) {
  2732. const x = this.x, y = this.y, z = this.z;
  2733. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2734. // calculate quat * vector
  2735. const ix = qw * x + qy * z - qz * y;
  2736. const iy = qw * y + qz * x - qx * z;
  2737. const iz = qw * z + qx * y - qy * x;
  2738. const iw = - qx * x - qy * y - qz * z;
  2739. // calculate result * inverse quat
  2740. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  2741. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  2742. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  2743. return this;
  2744. }
  2745. project( camera ) {
  2746. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2747. }
  2748. unproject( camera ) {
  2749. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2750. }
  2751. transformDirection( m ) {
  2752. // input: THREE.Matrix4 affine matrix
  2753. // vector interpreted as a direction
  2754. const x = this.x, y = this.y, z = this.z;
  2755. const e = m.elements;
  2756. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2757. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2758. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2759. return this.normalize();
  2760. }
  2761. divide( v ) {
  2762. this.x /= v.x;
  2763. this.y /= v.y;
  2764. this.z /= v.z;
  2765. return this;
  2766. }
  2767. divideScalar( scalar ) {
  2768. return this.multiplyScalar( 1 / scalar );
  2769. }
  2770. min( v ) {
  2771. this.x = Math.min( this.x, v.x );
  2772. this.y = Math.min( this.y, v.y );
  2773. this.z = Math.min( this.z, v.z );
  2774. return this;
  2775. }
  2776. max( v ) {
  2777. this.x = Math.max( this.x, v.x );
  2778. this.y = Math.max( this.y, v.y );
  2779. this.z = Math.max( this.z, v.z );
  2780. return this;
  2781. }
  2782. clamp( min, max ) {
  2783. // assumes min < max, componentwise
  2784. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2785. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2786. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2787. return this;
  2788. }
  2789. clampScalar( minVal, maxVal ) {
  2790. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2791. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2792. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2793. return this;
  2794. }
  2795. clampLength( min, max ) {
  2796. const length = this.length();
  2797. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2798. }
  2799. floor() {
  2800. this.x = Math.floor( this.x );
  2801. this.y = Math.floor( this.y );
  2802. this.z = Math.floor( this.z );
  2803. return this;
  2804. }
  2805. ceil() {
  2806. this.x = Math.ceil( this.x );
  2807. this.y = Math.ceil( this.y );
  2808. this.z = Math.ceil( this.z );
  2809. return this;
  2810. }
  2811. round() {
  2812. this.x = Math.round( this.x );
  2813. this.y = Math.round( this.y );
  2814. this.z = Math.round( this.z );
  2815. return this;
  2816. }
  2817. roundToZero() {
  2818. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2819. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2820. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2821. return this;
  2822. }
  2823. negate() {
  2824. this.x = - this.x;
  2825. this.y = - this.y;
  2826. this.z = - this.z;
  2827. return this;
  2828. }
  2829. dot( v ) {
  2830. return this.x * v.x + this.y * v.y + this.z * v.z;
  2831. }
  2832. // TODO lengthSquared?
  2833. lengthSq() {
  2834. return this.x * this.x + this.y * this.y + this.z * this.z;
  2835. }
  2836. length() {
  2837. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2838. }
  2839. manhattanLength() {
  2840. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2841. }
  2842. normalize() {
  2843. return this.divideScalar( this.length() || 1 );
  2844. }
  2845. setLength( length ) {
  2846. return this.normalize().multiplyScalar( length );
  2847. }
  2848. lerp( v, alpha ) {
  2849. this.x += ( v.x - this.x ) * alpha;
  2850. this.y += ( v.y - this.y ) * alpha;
  2851. this.z += ( v.z - this.z ) * alpha;
  2852. return this;
  2853. }
  2854. lerpVectors( v1, v2, alpha ) {
  2855. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2856. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2857. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2858. return this;
  2859. }
  2860. cross( v ) {
  2861. return this.crossVectors( this, v );
  2862. }
  2863. crossVectors( a, b ) {
  2864. const ax = a.x, ay = a.y, az = a.z;
  2865. const bx = b.x, by = b.y, bz = b.z;
  2866. this.x = ay * bz - az * by;
  2867. this.y = az * bx - ax * bz;
  2868. this.z = ax * by - ay * bx;
  2869. return this;
  2870. }
  2871. projectOnVector( v ) {
  2872. const denominator = v.lengthSq();
  2873. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2874. const scalar = v.dot( this ) / denominator;
  2875. return this.copy( v ).multiplyScalar( scalar );
  2876. }
  2877. projectOnPlane( planeNormal ) {
  2878. _vector$c.copy( this ).projectOnVector( planeNormal );
  2879. return this.sub( _vector$c );
  2880. }
  2881. reflect( normal ) {
  2882. // reflect incident vector off plane orthogonal to normal
  2883. // normal is assumed to have unit length
  2884. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2885. }
  2886. angleTo( v ) {
  2887. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2888. if ( denominator === 0 ) return Math.PI / 2;
  2889. const theta = this.dot( v ) / denominator;
  2890. // clamp, to handle numerical problems
  2891. return Math.acos( clamp( theta, - 1, 1 ) );
  2892. }
  2893. distanceTo( v ) {
  2894. return Math.sqrt( this.distanceToSquared( v ) );
  2895. }
  2896. distanceToSquared( v ) {
  2897. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2898. return dx * dx + dy * dy + dz * dz;
  2899. }
  2900. manhattanDistanceTo( v ) {
  2901. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2902. }
  2903. setFromSpherical( s ) {
  2904. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2905. }
  2906. setFromSphericalCoords( radius, phi, theta ) {
  2907. const sinPhiRadius = Math.sin( phi ) * radius;
  2908. this.x = sinPhiRadius * Math.sin( theta );
  2909. this.y = Math.cos( phi ) * radius;
  2910. this.z = sinPhiRadius * Math.cos( theta );
  2911. return this;
  2912. }
  2913. setFromCylindrical( c ) {
  2914. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2915. }
  2916. setFromCylindricalCoords( radius, theta, y ) {
  2917. this.x = radius * Math.sin( theta );
  2918. this.y = y;
  2919. this.z = radius * Math.cos( theta );
  2920. return this;
  2921. }
  2922. setFromMatrixPosition( m ) {
  2923. const e = m.elements;
  2924. this.x = e[ 12 ];
  2925. this.y = e[ 13 ];
  2926. this.z = e[ 14 ];
  2927. return this;
  2928. }
  2929. setFromMatrixScale( m ) {
  2930. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2931. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2932. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2933. this.x = sx;
  2934. this.y = sy;
  2935. this.z = sz;
  2936. return this;
  2937. }
  2938. setFromMatrixColumn( m, index ) {
  2939. return this.fromArray( m.elements, index * 4 );
  2940. }
  2941. setFromMatrix3Column( m, index ) {
  2942. return this.fromArray( m.elements, index * 3 );
  2943. }
  2944. setFromEuler( e ) {
  2945. this.x = e._x;
  2946. this.y = e._y;
  2947. this.z = e._z;
  2948. return this;
  2949. }
  2950. equals( v ) {
  2951. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2952. }
  2953. fromArray( array, offset = 0 ) {
  2954. this.x = array[ offset ];
  2955. this.y = array[ offset + 1 ];
  2956. this.z = array[ offset + 2 ];
  2957. return this;
  2958. }
  2959. toArray( array = [], offset = 0 ) {
  2960. array[ offset ] = this.x;
  2961. array[ offset + 1 ] = this.y;
  2962. array[ offset + 2 ] = this.z;
  2963. return array;
  2964. }
  2965. fromBufferAttribute( attribute, index ) {
  2966. this.x = attribute.getX( index );
  2967. this.y = attribute.getY( index );
  2968. this.z = attribute.getZ( index );
  2969. return this;
  2970. }
  2971. random() {
  2972. this.x = Math.random();
  2973. this.y = Math.random();
  2974. this.z = Math.random();
  2975. return this;
  2976. }
  2977. randomDirection() {
  2978. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  2979. const u = ( Math.random() - 0.5 ) * 2;
  2980. const t = Math.random() * Math.PI * 2;
  2981. const f = Math.sqrt( 1 - u ** 2 );
  2982. this.x = f * Math.cos( t );
  2983. this.y = f * Math.sin( t );
  2984. this.z = u;
  2985. return this;
  2986. }
  2987. *[ Symbol.iterator ]() {
  2988. yield this.x;
  2989. yield this.y;
  2990. yield this.z;
  2991. }
  2992. }
  2993. const _vector$c = /*@__PURE__*/ new Vector3();
  2994. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2995. class Box3 {
  2996. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2997. this.isBox3 = true;
  2998. this.min = min;
  2999. this.max = max;
  3000. }
  3001. set( min, max ) {
  3002. this.min.copy( min );
  3003. this.max.copy( max );
  3004. return this;
  3005. }
  3006. setFromArray( array ) {
  3007. let minX = + Infinity;
  3008. let minY = + Infinity;
  3009. let minZ = + Infinity;
  3010. let maxX = - Infinity;
  3011. let maxY = - Infinity;
  3012. let maxZ = - Infinity;
  3013. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  3014. const x = array[ i ];
  3015. const y = array[ i + 1 ];
  3016. const z = array[ i + 2 ];
  3017. if ( x < minX ) minX = x;
  3018. if ( y < minY ) minY = y;
  3019. if ( z < minZ ) minZ = z;
  3020. if ( x > maxX ) maxX = x;
  3021. if ( y > maxY ) maxY = y;
  3022. if ( z > maxZ ) maxZ = z;
  3023. }
  3024. this.min.set( minX, minY, minZ );
  3025. this.max.set( maxX, maxY, maxZ );
  3026. return this;
  3027. }
  3028. setFromBufferAttribute( attribute ) {
  3029. let minX = + Infinity;
  3030. let minY = + Infinity;
  3031. let minZ = + Infinity;
  3032. let maxX = - Infinity;
  3033. let maxY = - Infinity;
  3034. let maxZ = - Infinity;
  3035. for ( let i = 0, l = attribute.count; i < l; i ++ ) {
  3036. const x = attribute.getX( i );
  3037. const y = attribute.getY( i );
  3038. const z = attribute.getZ( i );
  3039. if ( x < minX ) minX = x;
  3040. if ( y < minY ) minY = y;
  3041. if ( z < minZ ) minZ = z;
  3042. if ( x > maxX ) maxX = x;
  3043. if ( y > maxY ) maxY = y;
  3044. if ( z > maxZ ) maxZ = z;
  3045. }
  3046. this.min.set( minX, minY, minZ );
  3047. this.max.set( maxX, maxY, maxZ );
  3048. return this;
  3049. }
  3050. setFromPoints( points ) {
  3051. this.makeEmpty();
  3052. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3053. this.expandByPoint( points[ i ] );
  3054. }
  3055. return this;
  3056. }
  3057. setFromCenterAndSize( center, size ) {
  3058. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  3059. this.min.copy( center ).sub( halfSize );
  3060. this.max.copy( center ).add( halfSize );
  3061. return this;
  3062. }
  3063. setFromObject( object, precise = false ) {
  3064. this.makeEmpty();
  3065. return this.expandByObject( object, precise );
  3066. }
  3067. clone() {
  3068. return new this.constructor().copy( this );
  3069. }
  3070. copy( box ) {
  3071. this.min.copy( box.min );
  3072. this.max.copy( box.max );
  3073. return this;
  3074. }
  3075. makeEmpty() {
  3076. this.min.x = this.min.y = this.min.z = + Infinity;
  3077. this.max.x = this.max.y = this.max.z = - Infinity;
  3078. return this;
  3079. }
  3080. isEmpty() {
  3081. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3082. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  3083. }
  3084. getCenter( target ) {
  3085. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  3086. }
  3087. getSize( target ) {
  3088. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  3089. }
  3090. expandByPoint( point ) {
  3091. this.min.min( point );
  3092. this.max.max( point );
  3093. return this;
  3094. }
  3095. expandByVector( vector ) {
  3096. this.min.sub( vector );
  3097. this.max.add( vector );
  3098. return this;
  3099. }
  3100. expandByScalar( scalar ) {
  3101. this.min.addScalar( - scalar );
  3102. this.max.addScalar( scalar );
  3103. return this;
  3104. }
  3105. expandByObject( object, precise = false ) {
  3106. // Computes the world-axis-aligned bounding box of an object (including its children),
  3107. // accounting for both the object's, and children's, world transforms
  3108. object.updateWorldMatrix( false, false );
  3109. const geometry = object.geometry;
  3110. if ( geometry !== undefined ) {
  3111. if ( precise && geometry.attributes != undefined && geometry.attributes.position !== undefined ) {
  3112. const position = geometry.attributes.position;
  3113. for ( let i = 0, l = position.count; i < l; i ++ ) {
  3114. _vector$b.fromBufferAttribute( position, i ).applyMatrix4( object.matrixWorld );
  3115. this.expandByPoint( _vector$b );
  3116. }
  3117. } else {
  3118. if ( geometry.boundingBox === null ) {
  3119. geometry.computeBoundingBox();
  3120. }
  3121. _box$3.copy( geometry.boundingBox );
  3122. _box$3.applyMatrix4( object.matrixWorld );
  3123. this.union( _box$3 );
  3124. }
  3125. }
  3126. const children = object.children;
  3127. for ( let i = 0, l = children.length; i < l; i ++ ) {
  3128. this.expandByObject( children[ i ], precise );
  3129. }
  3130. return this;
  3131. }
  3132. containsPoint( point ) {
  3133. return point.x < this.min.x || point.x > this.max.x ||
  3134. point.y < this.min.y || point.y > this.max.y ||
  3135. point.z < this.min.z || point.z > this.max.z ? false : true;
  3136. }
  3137. containsBox( box ) {
  3138. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  3139. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  3140. this.min.z <= box.min.z && box.max.z <= this.max.z;
  3141. }
  3142. getParameter( point, target ) {
  3143. // This can potentially have a divide by zero if the box
  3144. // has a size dimension of 0.
  3145. return target.set(
  3146. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3147. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  3148. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  3149. );
  3150. }
  3151. intersectsBox( box ) {
  3152. // using 6 splitting planes to rule out intersections.
  3153. return box.max.x < this.min.x || box.min.x > this.max.x ||
  3154. box.max.y < this.min.y || box.min.y > this.max.y ||
  3155. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  3156. }
  3157. intersectsSphere( sphere ) {
  3158. // Find the point on the AABB closest to the sphere center.
  3159. this.clampPoint( sphere.center, _vector$b );
  3160. // If that point is inside the sphere, the AABB and sphere intersect.
  3161. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  3162. }
  3163. intersectsPlane( plane ) {
  3164. // We compute the minimum and maximum dot product values. If those values
  3165. // are on the same side (back or front) of the plane, then there is no intersection.
  3166. let min, max;
  3167. if ( plane.normal.x > 0 ) {
  3168. min = plane.normal.x * this.min.x;
  3169. max = plane.normal.x * this.max.x;
  3170. } else {
  3171. min = plane.normal.x * this.max.x;
  3172. max = plane.normal.x * this.min.x;
  3173. }
  3174. if ( plane.normal.y > 0 ) {
  3175. min += plane.normal.y * this.min.y;
  3176. max += plane.normal.y * this.max.y;
  3177. } else {
  3178. min += plane.normal.y * this.max.y;
  3179. max += plane.normal.y * this.min.y;
  3180. }
  3181. if ( plane.normal.z > 0 ) {
  3182. min += plane.normal.z * this.min.z;
  3183. max += plane.normal.z * this.max.z;
  3184. } else {
  3185. min += plane.normal.z * this.max.z;
  3186. max += plane.normal.z * this.min.z;
  3187. }
  3188. return ( min <= - plane.constant && max >= - plane.constant );
  3189. }
  3190. intersectsTriangle( triangle ) {
  3191. if ( this.isEmpty() ) {
  3192. return false;
  3193. }
  3194. // compute box center and extents
  3195. this.getCenter( _center );
  3196. _extents.subVectors( this.max, _center );
  3197. // translate triangle to aabb origin
  3198. _v0$2.subVectors( triangle.a, _center );
  3199. _v1$7.subVectors( triangle.b, _center );
  3200. _v2$4.subVectors( triangle.c, _center );
  3201. // compute edge vectors for triangle
  3202. _f0.subVectors( _v1$7, _v0$2 );
  3203. _f1.subVectors( _v2$4, _v1$7 );
  3204. _f2.subVectors( _v0$2, _v2$4 );
  3205. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  3206. // 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
  3207. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3208. let axes = [
  3209. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  3210. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  3211. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  3212. ];
  3213. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  3214. return false;
  3215. }
  3216. // test 3 face normals from the aabb
  3217. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  3218. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  3219. return false;
  3220. }
  3221. // finally testing the face normal of the triangle
  3222. // use already existing triangle edge vectors here
  3223. _triangleNormal.crossVectors( _f0, _f1 );
  3224. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  3225. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  3226. }
  3227. clampPoint( point, target ) {
  3228. return target.copy( point ).clamp( this.min, this.max );
  3229. }
  3230. distanceToPoint( point ) {
  3231. const clampedPoint = _vector$b.copy( point ).clamp( this.min, this.max );
  3232. return clampedPoint.sub( point ).length();
  3233. }
  3234. getBoundingSphere( target ) {
  3235. this.getCenter( target.center );
  3236. target.radius = this.getSize( _vector$b ).length() * 0.5;
  3237. return target;
  3238. }
  3239. intersect( box ) {
  3240. this.min.max( box.min );
  3241. this.max.min( box.max );
  3242. // 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.
  3243. if ( this.isEmpty() ) this.makeEmpty();
  3244. return this;
  3245. }
  3246. union( box ) {
  3247. this.min.min( box.min );
  3248. this.max.max( box.max );
  3249. return this;
  3250. }
  3251. applyMatrix4( matrix ) {
  3252. // transform of empty box is an empty box.
  3253. if ( this.isEmpty() ) return this;
  3254. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3255. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3256. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3257. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3258. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3259. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3260. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3261. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3262. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3263. this.setFromPoints( _points );
  3264. return this;
  3265. }
  3266. translate( offset ) {
  3267. this.min.add( offset );
  3268. this.max.add( offset );
  3269. return this;
  3270. }
  3271. equals( box ) {
  3272. return box.min.equals( this.min ) && box.max.equals( this.max );
  3273. }
  3274. }
  3275. const _points = [
  3276. /*@__PURE__*/ new Vector3(),
  3277. /*@__PURE__*/ new Vector3(),
  3278. /*@__PURE__*/ new Vector3(),
  3279. /*@__PURE__*/ new Vector3(),
  3280. /*@__PURE__*/ new Vector3(),
  3281. /*@__PURE__*/ new Vector3(),
  3282. /*@__PURE__*/ new Vector3(),
  3283. /*@__PURE__*/ new Vector3()
  3284. ];
  3285. const _vector$b = /*@__PURE__*/ new Vector3();
  3286. const _box$3 = /*@__PURE__*/ new Box3();
  3287. // triangle centered vertices
  3288. const _v0$2 = /*@__PURE__*/ new Vector3();
  3289. const _v1$7 = /*@__PURE__*/ new Vector3();
  3290. const _v2$4 = /*@__PURE__*/ new Vector3();
  3291. // triangle edge vectors
  3292. const _f0 = /*@__PURE__*/ new Vector3();
  3293. const _f1 = /*@__PURE__*/ new Vector3();
  3294. const _f2 = /*@__PURE__*/ new Vector3();
  3295. const _center = /*@__PURE__*/ new Vector3();
  3296. const _extents = /*@__PURE__*/ new Vector3();
  3297. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3298. const _testAxis = /*@__PURE__*/ new Vector3();
  3299. function satForAxes( axes, v0, v1, v2, extents ) {
  3300. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3301. _testAxis.fromArray( axes, i );
  3302. // project the aabb onto the separating axis
  3303. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3304. // project all 3 vertices of the triangle onto the separating axis
  3305. const p0 = v0.dot( _testAxis );
  3306. const p1 = v1.dot( _testAxis );
  3307. const p2 = v2.dot( _testAxis );
  3308. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3309. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3310. // points of the projected triangle are outside the projected half-length of the aabb
  3311. // the axis is separating and we can exit
  3312. return false;
  3313. }
  3314. }
  3315. return true;
  3316. }
  3317. const _box$2 = /*@__PURE__*/ new Box3();
  3318. const _v1$6 = /*@__PURE__*/ new Vector3();
  3319. const _v2$3 = /*@__PURE__*/ new Vector3();
  3320. class Sphere {
  3321. constructor( center = new Vector3(), radius = - 1 ) {
  3322. this.center = center;
  3323. this.radius = radius;
  3324. }
  3325. set( center, radius ) {
  3326. this.center.copy( center );
  3327. this.radius = radius;
  3328. return this;
  3329. }
  3330. setFromPoints( points, optionalCenter ) {
  3331. const center = this.center;
  3332. if ( optionalCenter !== undefined ) {
  3333. center.copy( optionalCenter );
  3334. } else {
  3335. _box$2.setFromPoints( points ).getCenter( center );
  3336. }
  3337. let maxRadiusSq = 0;
  3338. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3339. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3340. }
  3341. this.radius = Math.sqrt( maxRadiusSq );
  3342. return this;
  3343. }
  3344. copy( sphere ) {
  3345. this.center.copy( sphere.center );
  3346. this.radius = sphere.radius;
  3347. return this;
  3348. }
  3349. isEmpty() {
  3350. return ( this.radius < 0 );
  3351. }
  3352. makeEmpty() {
  3353. this.center.set( 0, 0, 0 );
  3354. this.radius = - 1;
  3355. return this;
  3356. }
  3357. containsPoint( point ) {
  3358. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3359. }
  3360. distanceToPoint( point ) {
  3361. return ( point.distanceTo( this.center ) - this.radius );
  3362. }
  3363. intersectsSphere( sphere ) {
  3364. const radiusSum = this.radius + sphere.radius;
  3365. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3366. }
  3367. intersectsBox( box ) {
  3368. return box.intersectsSphere( this );
  3369. }
  3370. intersectsPlane( plane ) {
  3371. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3372. }
  3373. clampPoint( point, target ) {
  3374. const deltaLengthSq = this.center.distanceToSquared( point );
  3375. target.copy( point );
  3376. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3377. target.sub( this.center ).normalize();
  3378. target.multiplyScalar( this.radius ).add( this.center );
  3379. }
  3380. return target;
  3381. }
  3382. getBoundingBox( target ) {
  3383. if ( this.isEmpty() ) {
  3384. // Empty sphere produces empty bounding box
  3385. target.makeEmpty();
  3386. return target;
  3387. }
  3388. target.set( this.center, this.center );
  3389. target.expandByScalar( this.radius );
  3390. return target;
  3391. }
  3392. applyMatrix4( matrix ) {
  3393. this.center.applyMatrix4( matrix );
  3394. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3395. return this;
  3396. }
  3397. translate( offset ) {
  3398. this.center.add( offset );
  3399. return this;
  3400. }
  3401. expandByPoint( point ) {
  3402. if ( this.isEmpty() ) {
  3403. this.center.copy( point );
  3404. this.radius = 0;
  3405. return this;
  3406. }
  3407. _v1$6.subVectors( point, this.center );
  3408. const lengthSq = _v1$6.lengthSq();
  3409. if ( lengthSq > ( this.radius * this.radius ) ) {
  3410. // calculate the minimal sphere
  3411. const length = Math.sqrt( lengthSq );
  3412. const delta = ( length - this.radius ) * 0.5;
  3413. this.center.addScaledVector( _v1$6, delta / length );
  3414. this.radius += delta;
  3415. }
  3416. return this;
  3417. }
  3418. union( sphere ) {
  3419. if ( sphere.isEmpty() ) {
  3420. return this;
  3421. }
  3422. if ( this.isEmpty() ) {
  3423. this.copy( sphere );
  3424. return this;
  3425. }
  3426. if ( this.center.equals( sphere.center ) === true ) {
  3427. this.radius = Math.max( this.radius, sphere.radius );
  3428. } else {
  3429. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3430. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3431. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3432. }
  3433. return this;
  3434. }
  3435. equals( sphere ) {
  3436. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3437. }
  3438. clone() {
  3439. return new this.constructor().copy( this );
  3440. }
  3441. }
  3442. const _vector$a = /*@__PURE__*/ new Vector3();
  3443. const _segCenter = /*@__PURE__*/ new Vector3();
  3444. const _segDir = /*@__PURE__*/ new Vector3();
  3445. const _diff = /*@__PURE__*/ new Vector3();
  3446. const _edge1 = /*@__PURE__*/ new Vector3();
  3447. const _edge2 = /*@__PURE__*/ new Vector3();
  3448. const _normal$1 = /*@__PURE__*/ new Vector3();
  3449. class Ray {
  3450. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3451. this.origin = origin;
  3452. this.direction = direction;
  3453. }
  3454. set( origin, direction ) {
  3455. this.origin.copy( origin );
  3456. this.direction.copy( direction );
  3457. return this;
  3458. }
  3459. copy( ray ) {
  3460. this.origin.copy( ray.origin );
  3461. this.direction.copy( ray.direction );
  3462. return this;
  3463. }
  3464. at( t, target ) {
  3465. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3466. }
  3467. lookAt( v ) {
  3468. this.direction.copy( v ).sub( this.origin ).normalize();
  3469. return this;
  3470. }
  3471. recast( t ) {
  3472. this.origin.copy( this.at( t, _vector$a ) );
  3473. return this;
  3474. }
  3475. closestPointToPoint( point, target ) {
  3476. target.subVectors( point, this.origin );
  3477. const directionDistance = target.dot( this.direction );
  3478. if ( directionDistance < 0 ) {
  3479. return target.copy( this.origin );
  3480. }
  3481. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3482. }
  3483. distanceToPoint( point ) {
  3484. return Math.sqrt( this.distanceSqToPoint( point ) );
  3485. }
  3486. distanceSqToPoint( point ) {
  3487. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3488. // point behind the ray
  3489. if ( directionDistance < 0 ) {
  3490. return this.origin.distanceToSquared( point );
  3491. }
  3492. _vector$a.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3493. return _vector$a.distanceToSquared( point );
  3494. }
  3495. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3496. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3497. // It returns the min distance between the ray and the segment
  3498. // defined by v0 and v1
  3499. // It can also set two optional targets :
  3500. // - The closest point on the ray
  3501. // - The closest point on the segment
  3502. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3503. _segDir.copy( v1 ).sub( v0 ).normalize();
  3504. _diff.copy( this.origin ).sub( _segCenter );
  3505. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3506. const a01 = - this.direction.dot( _segDir );
  3507. const b0 = _diff.dot( this.direction );
  3508. const b1 = - _diff.dot( _segDir );
  3509. const c = _diff.lengthSq();
  3510. const det = Math.abs( 1 - a01 * a01 );
  3511. let s0, s1, sqrDist, extDet;
  3512. if ( det > 0 ) {
  3513. // The ray and segment are not parallel.
  3514. s0 = a01 * b1 - b0;
  3515. s1 = a01 * b0 - b1;
  3516. extDet = segExtent * det;
  3517. if ( s0 >= 0 ) {
  3518. if ( s1 >= - extDet ) {
  3519. if ( s1 <= extDet ) {
  3520. // region 0
  3521. // Minimum at interior points of ray and segment.
  3522. const invDet = 1 / det;
  3523. s0 *= invDet;
  3524. s1 *= invDet;
  3525. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3526. } else {
  3527. // region 1
  3528. s1 = segExtent;
  3529. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3530. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3531. }
  3532. } else {
  3533. // region 5
  3534. s1 = - segExtent;
  3535. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3536. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3537. }
  3538. } else {
  3539. if ( s1 <= - extDet ) {
  3540. // region 4
  3541. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3542. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3543. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3544. } else if ( s1 <= extDet ) {
  3545. // region 3
  3546. s0 = 0;
  3547. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3548. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3549. } else {
  3550. // region 2
  3551. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3552. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3553. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3554. }
  3555. }
  3556. } else {
  3557. // Ray and segment are parallel.
  3558. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3559. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3560. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3561. }
  3562. if ( optionalPointOnRay ) {
  3563. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  3564. }
  3565. if ( optionalPointOnSegment ) {
  3566. optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter );
  3567. }
  3568. return sqrDist;
  3569. }
  3570. intersectSphere( sphere, target ) {
  3571. _vector$a.subVectors( sphere.center, this.origin );
  3572. const tca = _vector$a.dot( this.direction );
  3573. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3574. const radius2 = sphere.radius * sphere.radius;
  3575. if ( d2 > radius2 ) return null;
  3576. const thc = Math.sqrt( radius2 - d2 );
  3577. // t0 = first intersect point - entrance on front of sphere
  3578. const t0 = tca - thc;
  3579. // t1 = second intersect point - exit point on back of sphere
  3580. const t1 = tca + thc;
  3581. // test to see if both t0 and t1 are behind the ray - if so, return null
  3582. if ( t0 < 0 && t1 < 0 ) return null;
  3583. // test to see if t0 is behind the ray:
  3584. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3585. // in order to always return an intersect point that is in front of the ray.
  3586. if ( t0 < 0 ) return this.at( t1, target );
  3587. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3588. return this.at( t0, target );
  3589. }
  3590. intersectsSphere( sphere ) {
  3591. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3592. }
  3593. distanceToPlane( plane ) {
  3594. const denominator = plane.normal.dot( this.direction );
  3595. if ( denominator === 0 ) {
  3596. // line is coplanar, return origin
  3597. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3598. return 0;
  3599. }
  3600. // Null is preferable to undefined since undefined means.... it is undefined
  3601. return null;
  3602. }
  3603. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3604. // Return if the ray never intersects the plane
  3605. return t >= 0 ? t : null;
  3606. }
  3607. intersectPlane( plane, target ) {
  3608. const t = this.distanceToPlane( plane );
  3609. if ( t === null ) {
  3610. return null;
  3611. }
  3612. return this.at( t, target );
  3613. }
  3614. intersectsPlane( plane ) {
  3615. // check if the ray lies on the plane first
  3616. const distToPoint = plane.distanceToPoint( this.origin );
  3617. if ( distToPoint === 0 ) {
  3618. return true;
  3619. }
  3620. const denominator = plane.normal.dot( this.direction );
  3621. if ( denominator * distToPoint < 0 ) {
  3622. return true;
  3623. }
  3624. // ray origin is behind the plane (and is pointing behind it)
  3625. return false;
  3626. }
  3627. intersectBox( box, target ) {
  3628. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3629. const invdirx = 1 / this.direction.x,
  3630. invdiry = 1 / this.direction.y,
  3631. invdirz = 1 / this.direction.z;
  3632. const origin = this.origin;
  3633. if ( invdirx >= 0 ) {
  3634. tmin = ( box.min.x - origin.x ) * invdirx;
  3635. tmax = ( box.max.x - origin.x ) * invdirx;
  3636. } else {
  3637. tmin = ( box.max.x - origin.x ) * invdirx;
  3638. tmax = ( box.min.x - origin.x ) * invdirx;
  3639. }
  3640. if ( invdiry >= 0 ) {
  3641. tymin = ( box.min.y - origin.y ) * invdiry;
  3642. tymax = ( box.max.y - origin.y ) * invdiry;
  3643. } else {
  3644. tymin = ( box.max.y - origin.y ) * invdiry;
  3645. tymax = ( box.min.y - origin.y ) * invdiry;
  3646. }
  3647. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3648. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3649. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3650. if ( invdirz >= 0 ) {
  3651. tzmin = ( box.min.z - origin.z ) * invdirz;
  3652. tzmax = ( box.max.z - origin.z ) * invdirz;
  3653. } else {
  3654. tzmin = ( box.max.z - origin.z ) * invdirz;
  3655. tzmax = ( box.min.z - origin.z ) * invdirz;
  3656. }
  3657. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3658. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3659. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3660. //return point closest to the ray (positive side)
  3661. if ( tmax < 0 ) return null;
  3662. return this.at( tmin >= 0 ? tmin : tmax, target );
  3663. }
  3664. intersectsBox( box ) {
  3665. return this.intersectBox( box, _vector$a ) !== null;
  3666. }
  3667. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3668. // Compute the offset origin, edges, and normal.
  3669. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3670. _edge1.subVectors( b, a );
  3671. _edge2.subVectors( c, a );
  3672. _normal$1.crossVectors( _edge1, _edge2 );
  3673. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3674. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3675. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3676. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3677. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3678. let DdN = this.direction.dot( _normal$1 );
  3679. let sign;
  3680. if ( DdN > 0 ) {
  3681. if ( backfaceCulling ) return null;
  3682. sign = 1;
  3683. } else if ( DdN < 0 ) {
  3684. sign = - 1;
  3685. DdN = - DdN;
  3686. } else {
  3687. return null;
  3688. }
  3689. _diff.subVectors( this.origin, a );
  3690. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3691. // b1 < 0, no intersection
  3692. if ( DdQxE2 < 0 ) {
  3693. return null;
  3694. }
  3695. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3696. // b2 < 0, no intersection
  3697. if ( DdE1xQ < 0 ) {
  3698. return null;
  3699. }
  3700. // b1+b2 > 1, no intersection
  3701. if ( DdQxE2 + DdE1xQ > DdN ) {
  3702. return null;
  3703. }
  3704. // Line intersects triangle, check if ray does.
  3705. const QdN = - sign * _diff.dot( _normal$1 );
  3706. // t < 0, no intersection
  3707. if ( QdN < 0 ) {
  3708. return null;
  3709. }
  3710. // Ray intersects triangle.
  3711. return this.at( QdN / DdN, target );
  3712. }
  3713. applyMatrix4( matrix4 ) {
  3714. this.origin.applyMatrix4( matrix4 );
  3715. this.direction.transformDirection( matrix4 );
  3716. return this;
  3717. }
  3718. equals( ray ) {
  3719. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3720. }
  3721. clone() {
  3722. return new this.constructor().copy( this );
  3723. }
  3724. }
  3725. class Matrix4 {
  3726. constructor() {
  3727. Matrix4.prototype.isMatrix4 = true;
  3728. this.elements = [
  3729. 1, 0, 0, 0,
  3730. 0, 1, 0, 0,
  3731. 0, 0, 1, 0,
  3732. 0, 0, 0, 1
  3733. ];
  3734. }
  3735. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3736. const te = this.elements;
  3737. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3738. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3739. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3740. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3741. return this;
  3742. }
  3743. identity() {
  3744. this.set(
  3745. 1, 0, 0, 0,
  3746. 0, 1, 0, 0,
  3747. 0, 0, 1, 0,
  3748. 0, 0, 0, 1
  3749. );
  3750. return this;
  3751. }
  3752. clone() {
  3753. return new Matrix4().fromArray( this.elements );
  3754. }
  3755. copy( m ) {
  3756. const te = this.elements;
  3757. const me = m.elements;
  3758. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3759. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3760. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3761. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3762. return this;
  3763. }
  3764. copyPosition( m ) {
  3765. const te = this.elements, me = m.elements;
  3766. te[ 12 ] = me[ 12 ];
  3767. te[ 13 ] = me[ 13 ];
  3768. te[ 14 ] = me[ 14 ];
  3769. return this;
  3770. }
  3771. setFromMatrix3( m ) {
  3772. const me = m.elements;
  3773. this.set(
  3774. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3775. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3776. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3777. 0, 0, 0, 1
  3778. );
  3779. return this;
  3780. }
  3781. extractBasis( xAxis, yAxis, zAxis ) {
  3782. xAxis.setFromMatrixColumn( this, 0 );
  3783. yAxis.setFromMatrixColumn( this, 1 );
  3784. zAxis.setFromMatrixColumn( this, 2 );
  3785. return this;
  3786. }
  3787. makeBasis( xAxis, yAxis, zAxis ) {
  3788. this.set(
  3789. xAxis.x, yAxis.x, zAxis.x, 0,
  3790. xAxis.y, yAxis.y, zAxis.y, 0,
  3791. xAxis.z, yAxis.z, zAxis.z, 0,
  3792. 0, 0, 0, 1
  3793. );
  3794. return this;
  3795. }
  3796. extractRotation( m ) {
  3797. // this method does not support reflection matrices
  3798. const te = this.elements;
  3799. const me = m.elements;
  3800. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3801. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3802. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3803. te[ 0 ] = me[ 0 ] * scaleX;
  3804. te[ 1 ] = me[ 1 ] * scaleX;
  3805. te[ 2 ] = me[ 2 ] * scaleX;
  3806. te[ 3 ] = 0;
  3807. te[ 4 ] = me[ 4 ] * scaleY;
  3808. te[ 5 ] = me[ 5 ] * scaleY;
  3809. te[ 6 ] = me[ 6 ] * scaleY;
  3810. te[ 7 ] = 0;
  3811. te[ 8 ] = me[ 8 ] * scaleZ;
  3812. te[ 9 ] = me[ 9 ] * scaleZ;
  3813. te[ 10 ] = me[ 10 ] * scaleZ;
  3814. te[ 11 ] = 0;
  3815. te[ 12 ] = 0;
  3816. te[ 13 ] = 0;
  3817. te[ 14 ] = 0;
  3818. te[ 15 ] = 1;
  3819. return this;
  3820. }
  3821. makeRotationFromEuler( euler ) {
  3822. const te = this.elements;
  3823. const x = euler.x, y = euler.y, z = euler.z;
  3824. const a = Math.cos( x ), b = Math.sin( x );
  3825. const c = Math.cos( y ), d = Math.sin( y );
  3826. const e = Math.cos( z ), f = Math.sin( z );
  3827. if ( euler.order === 'XYZ' ) {
  3828. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3829. te[ 0 ] = c * e;
  3830. te[ 4 ] = - c * f;
  3831. te[ 8 ] = d;
  3832. te[ 1 ] = af + be * d;
  3833. te[ 5 ] = ae - bf * d;
  3834. te[ 9 ] = - b * c;
  3835. te[ 2 ] = bf - ae * d;
  3836. te[ 6 ] = be + af * d;
  3837. te[ 10 ] = a * c;
  3838. } else if ( euler.order === 'YXZ' ) {
  3839. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3840. te[ 0 ] = ce + df * b;
  3841. te[ 4 ] = de * b - cf;
  3842. te[ 8 ] = a * d;
  3843. te[ 1 ] = a * f;
  3844. te[ 5 ] = a * e;
  3845. te[ 9 ] = - b;
  3846. te[ 2 ] = cf * b - de;
  3847. te[ 6 ] = df + ce * b;
  3848. te[ 10 ] = a * c;
  3849. } else if ( euler.order === 'ZXY' ) {
  3850. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3851. te[ 0 ] = ce - df * b;
  3852. te[ 4 ] = - a * f;
  3853. te[ 8 ] = de + cf * b;
  3854. te[ 1 ] = cf + de * b;
  3855. te[ 5 ] = a * e;
  3856. te[ 9 ] = df - ce * b;
  3857. te[ 2 ] = - a * d;
  3858. te[ 6 ] = b;
  3859. te[ 10 ] = a * c;
  3860. } else if ( euler.order === 'ZYX' ) {
  3861. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3862. te[ 0 ] = c * e;
  3863. te[ 4 ] = be * d - af;
  3864. te[ 8 ] = ae * d + bf;
  3865. te[ 1 ] = c * f;
  3866. te[ 5 ] = bf * d + ae;
  3867. te[ 9 ] = af * d - be;
  3868. te[ 2 ] = - d;
  3869. te[ 6 ] = b * c;
  3870. te[ 10 ] = a * c;
  3871. } else if ( euler.order === 'YZX' ) {
  3872. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3873. te[ 0 ] = c * e;
  3874. te[ 4 ] = bd - ac * f;
  3875. te[ 8 ] = bc * f + ad;
  3876. te[ 1 ] = f;
  3877. te[ 5 ] = a * e;
  3878. te[ 9 ] = - b * e;
  3879. te[ 2 ] = - d * e;
  3880. te[ 6 ] = ad * f + bc;
  3881. te[ 10 ] = ac - bd * f;
  3882. } else if ( euler.order === 'XZY' ) {
  3883. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3884. te[ 0 ] = c * e;
  3885. te[ 4 ] = - f;
  3886. te[ 8 ] = d * e;
  3887. te[ 1 ] = ac * f + bd;
  3888. te[ 5 ] = a * e;
  3889. te[ 9 ] = ad * f - bc;
  3890. te[ 2 ] = bc * f - ad;
  3891. te[ 6 ] = b * e;
  3892. te[ 10 ] = bd * f + ac;
  3893. }
  3894. // bottom row
  3895. te[ 3 ] = 0;
  3896. te[ 7 ] = 0;
  3897. te[ 11 ] = 0;
  3898. // last column
  3899. te[ 12 ] = 0;
  3900. te[ 13 ] = 0;
  3901. te[ 14 ] = 0;
  3902. te[ 15 ] = 1;
  3903. return this;
  3904. }
  3905. makeRotationFromQuaternion( q ) {
  3906. return this.compose( _zero, q, _one );
  3907. }
  3908. lookAt( eye, target, up ) {
  3909. const te = this.elements;
  3910. _z.subVectors( eye, target );
  3911. if ( _z.lengthSq() === 0 ) {
  3912. // eye and target are in the same position
  3913. _z.z = 1;
  3914. }
  3915. _z.normalize();
  3916. _x.crossVectors( up, _z );
  3917. if ( _x.lengthSq() === 0 ) {
  3918. // up and z are parallel
  3919. if ( Math.abs( up.z ) === 1 ) {
  3920. _z.x += 0.0001;
  3921. } else {
  3922. _z.z += 0.0001;
  3923. }
  3924. _z.normalize();
  3925. _x.crossVectors( up, _z );
  3926. }
  3927. _x.normalize();
  3928. _y.crossVectors( _z, _x );
  3929. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3930. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3931. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3932. return this;
  3933. }
  3934. multiply( m ) {
  3935. return this.multiplyMatrices( this, m );
  3936. }
  3937. premultiply( m ) {
  3938. return this.multiplyMatrices( m, this );
  3939. }
  3940. multiplyMatrices( a, b ) {
  3941. const ae = a.elements;
  3942. const be = b.elements;
  3943. const te = this.elements;
  3944. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3945. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3946. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3947. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3948. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3949. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3950. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3951. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3952. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3953. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3954. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3955. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3956. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3957. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3958. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3959. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3960. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3961. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3962. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3963. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3964. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3965. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3966. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3967. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3968. return this;
  3969. }
  3970. multiplyScalar( s ) {
  3971. const te = this.elements;
  3972. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3973. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3974. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3975. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3976. return this;
  3977. }
  3978. determinant() {
  3979. const te = this.elements;
  3980. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3981. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3982. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3983. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3984. //TODO: make this more efficient
  3985. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3986. return (
  3987. n41 * (
  3988. + n14 * n23 * n32
  3989. - n13 * n24 * n32
  3990. - n14 * n22 * n33
  3991. + n12 * n24 * n33
  3992. + n13 * n22 * n34
  3993. - n12 * n23 * n34
  3994. ) +
  3995. n42 * (
  3996. + n11 * n23 * n34
  3997. - n11 * n24 * n33
  3998. + n14 * n21 * n33
  3999. - n13 * n21 * n34
  4000. + n13 * n24 * n31
  4001. - n14 * n23 * n31
  4002. ) +
  4003. n43 * (
  4004. + n11 * n24 * n32
  4005. - n11 * n22 * n34
  4006. - n14 * n21 * n32
  4007. + n12 * n21 * n34
  4008. + n14 * n22 * n31
  4009. - n12 * n24 * n31
  4010. ) +
  4011. n44 * (
  4012. - n13 * n22 * n31
  4013. - n11 * n23 * n32
  4014. + n11 * n22 * n33
  4015. + n13 * n21 * n32
  4016. - n12 * n21 * n33
  4017. + n12 * n23 * n31
  4018. )
  4019. );
  4020. }
  4021. transpose() {
  4022. const te = this.elements;
  4023. let tmp;
  4024. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  4025. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  4026. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  4027. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  4028. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  4029. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  4030. return this;
  4031. }
  4032. setPosition( x, y, z ) {
  4033. const te = this.elements;
  4034. if ( x.isVector3 ) {
  4035. te[ 12 ] = x.x;
  4036. te[ 13 ] = x.y;
  4037. te[ 14 ] = x.z;
  4038. } else {
  4039. te[ 12 ] = x;
  4040. te[ 13 ] = y;
  4041. te[ 14 ] = z;
  4042. }
  4043. return this;
  4044. }
  4045. invert() {
  4046. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4047. const te = this.elements,
  4048. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  4049. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  4050. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  4051. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  4052. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4053. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4054. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4055. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4056. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4057. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4058. const detInv = 1 / det;
  4059. te[ 0 ] = t11 * detInv;
  4060. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  4061. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  4062. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  4063. te[ 4 ] = t12 * detInv;
  4064. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  4065. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  4066. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  4067. te[ 8 ] = t13 * detInv;
  4068. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  4069. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  4070. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  4071. te[ 12 ] = t14 * detInv;
  4072. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  4073. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  4074. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  4075. return this;
  4076. }
  4077. scale( v ) {
  4078. const te = this.elements;
  4079. const x = v.x, y = v.y, z = v.z;
  4080. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  4081. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  4082. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  4083. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  4084. return this;
  4085. }
  4086. getMaxScaleOnAxis() {
  4087. const te = this.elements;
  4088. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  4089. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  4090. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  4091. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  4092. }
  4093. makeTranslation( x, y, z ) {
  4094. this.set(
  4095. 1, 0, 0, x,
  4096. 0, 1, 0, y,
  4097. 0, 0, 1, z,
  4098. 0, 0, 0, 1
  4099. );
  4100. return this;
  4101. }
  4102. makeRotationX( theta ) {
  4103. const c = Math.cos( theta ), s = Math.sin( theta );
  4104. this.set(
  4105. 1, 0, 0, 0,
  4106. 0, c, - s, 0,
  4107. 0, s, c, 0,
  4108. 0, 0, 0, 1
  4109. );
  4110. return this;
  4111. }
  4112. makeRotationY( theta ) {
  4113. const c = Math.cos( theta ), s = Math.sin( theta );
  4114. this.set(
  4115. c, 0, s, 0,
  4116. 0, 1, 0, 0,
  4117. - s, 0, c, 0,
  4118. 0, 0, 0, 1
  4119. );
  4120. return this;
  4121. }
  4122. makeRotationZ( theta ) {
  4123. const c = Math.cos( theta ), s = Math.sin( theta );
  4124. this.set(
  4125. c, - s, 0, 0,
  4126. s, c, 0, 0,
  4127. 0, 0, 1, 0,
  4128. 0, 0, 0, 1
  4129. );
  4130. return this;
  4131. }
  4132. makeRotationAxis( axis, angle ) {
  4133. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4134. const c = Math.cos( angle );
  4135. const s = Math.sin( angle );
  4136. const t = 1 - c;
  4137. const x = axis.x, y = axis.y, z = axis.z;
  4138. const tx = t * x, ty = t * y;
  4139. this.set(
  4140. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  4141. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  4142. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  4143. 0, 0, 0, 1
  4144. );
  4145. return this;
  4146. }
  4147. makeScale( x, y, z ) {
  4148. this.set(
  4149. x, 0, 0, 0,
  4150. 0, y, 0, 0,
  4151. 0, 0, z, 0,
  4152. 0, 0, 0, 1
  4153. );
  4154. return this;
  4155. }
  4156. makeShear( xy, xz, yx, yz, zx, zy ) {
  4157. this.set(
  4158. 1, yx, zx, 0,
  4159. xy, 1, zy, 0,
  4160. xz, yz, 1, 0,
  4161. 0, 0, 0, 1
  4162. );
  4163. return this;
  4164. }
  4165. compose( position, quaternion, scale ) {
  4166. const te = this.elements;
  4167. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  4168. const x2 = x + x, y2 = y + y, z2 = z + z;
  4169. const xx = x * x2, xy = x * y2, xz = x * z2;
  4170. const yy = y * y2, yz = y * z2, zz = z * z2;
  4171. const wx = w * x2, wy = w * y2, wz = w * z2;
  4172. const sx = scale.x, sy = scale.y, sz = scale.z;
  4173. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  4174. te[ 1 ] = ( xy + wz ) * sx;
  4175. te[ 2 ] = ( xz - wy ) * sx;
  4176. te[ 3 ] = 0;
  4177. te[ 4 ] = ( xy - wz ) * sy;
  4178. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  4179. te[ 6 ] = ( yz + wx ) * sy;
  4180. te[ 7 ] = 0;
  4181. te[ 8 ] = ( xz + wy ) * sz;
  4182. te[ 9 ] = ( yz - wx ) * sz;
  4183. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  4184. te[ 11 ] = 0;
  4185. te[ 12 ] = position.x;
  4186. te[ 13 ] = position.y;
  4187. te[ 14 ] = position.z;
  4188. te[ 15 ] = 1;
  4189. return this;
  4190. }
  4191. decompose( position, quaternion, scale ) {
  4192. const te = this.elements;
  4193. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  4194. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  4195. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  4196. // if determine is negative, we need to invert one scale
  4197. const det = this.determinant();
  4198. if ( det < 0 ) sx = - sx;
  4199. position.x = te[ 12 ];
  4200. position.y = te[ 13 ];
  4201. position.z = te[ 14 ];
  4202. // scale the rotation part
  4203. _m1$2.copy( this );
  4204. const invSX = 1 / sx;
  4205. const invSY = 1 / sy;
  4206. const invSZ = 1 / sz;
  4207. _m1$2.elements[ 0 ] *= invSX;
  4208. _m1$2.elements[ 1 ] *= invSX;
  4209. _m1$2.elements[ 2 ] *= invSX;
  4210. _m1$2.elements[ 4 ] *= invSY;
  4211. _m1$2.elements[ 5 ] *= invSY;
  4212. _m1$2.elements[ 6 ] *= invSY;
  4213. _m1$2.elements[ 8 ] *= invSZ;
  4214. _m1$2.elements[ 9 ] *= invSZ;
  4215. _m1$2.elements[ 10 ] *= invSZ;
  4216. quaternion.setFromRotationMatrix( _m1$2 );
  4217. scale.x = sx;
  4218. scale.y = sy;
  4219. scale.z = sz;
  4220. return this;
  4221. }
  4222. makePerspective( left, right, top, bottom, near, far ) {
  4223. const te = this.elements;
  4224. const x = 2 * near / ( right - left );
  4225. const y = 2 * near / ( top - bottom );
  4226. const a = ( right + left ) / ( right - left );
  4227. const b = ( top + bottom ) / ( top - bottom );
  4228. const c = - ( far + near ) / ( far - near );
  4229. const d = - 2 * far * near / ( far - near );
  4230. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4231. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4232. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4233. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4234. return this;
  4235. }
  4236. makeOrthographic( left, right, top, bottom, near, far ) {
  4237. const te = this.elements;
  4238. const w = 1.0 / ( right - left );
  4239. const h = 1.0 / ( top - bottom );
  4240. const p = 1.0 / ( far - near );
  4241. const x = ( right + left ) * w;
  4242. const y = ( top + bottom ) * h;
  4243. const z = ( far + near ) * p;
  4244. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4245. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4246. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  4247. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4248. return this;
  4249. }
  4250. equals( matrix ) {
  4251. const te = this.elements;
  4252. const me = matrix.elements;
  4253. for ( let i = 0; i < 16; i ++ ) {
  4254. if ( te[ i ] !== me[ i ] ) return false;
  4255. }
  4256. return true;
  4257. }
  4258. fromArray( array, offset = 0 ) {
  4259. for ( let i = 0; i < 16; i ++ ) {
  4260. this.elements[ i ] = array[ i + offset ];
  4261. }
  4262. return this;
  4263. }
  4264. toArray( array = [], offset = 0 ) {
  4265. const te = this.elements;
  4266. array[ offset ] = te[ 0 ];
  4267. array[ offset + 1 ] = te[ 1 ];
  4268. array[ offset + 2 ] = te[ 2 ];
  4269. array[ offset + 3 ] = te[ 3 ];
  4270. array[ offset + 4 ] = te[ 4 ];
  4271. array[ offset + 5 ] = te[ 5 ];
  4272. array[ offset + 6 ] = te[ 6 ];
  4273. array[ offset + 7 ] = te[ 7 ];
  4274. array[ offset + 8 ] = te[ 8 ];
  4275. array[ offset + 9 ] = te[ 9 ];
  4276. array[ offset + 10 ] = te[ 10 ];
  4277. array[ offset + 11 ] = te[ 11 ];
  4278. array[ offset + 12 ] = te[ 12 ];
  4279. array[ offset + 13 ] = te[ 13 ];
  4280. array[ offset + 14 ] = te[ 14 ];
  4281. array[ offset + 15 ] = te[ 15 ];
  4282. return array;
  4283. }
  4284. }
  4285. const _v1$5 = /*@__PURE__*/ new Vector3();
  4286. const _m1$2 = /*@__PURE__*/ new Matrix4();
  4287. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4288. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4289. const _x = /*@__PURE__*/ new Vector3();
  4290. const _y = /*@__PURE__*/ new Vector3();
  4291. const _z = /*@__PURE__*/ new Vector3();
  4292. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  4293. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4294. class Euler {
  4295. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  4296. this.isEuler = true;
  4297. this._x = x;
  4298. this._y = y;
  4299. this._z = z;
  4300. this._order = order;
  4301. }
  4302. get x() {
  4303. return this._x;
  4304. }
  4305. set x( value ) {
  4306. this._x = value;
  4307. this._onChangeCallback();
  4308. }
  4309. get y() {
  4310. return this._y;
  4311. }
  4312. set y( value ) {
  4313. this._y = value;
  4314. this._onChangeCallback();
  4315. }
  4316. get z() {
  4317. return this._z;
  4318. }
  4319. set z( value ) {
  4320. this._z = value;
  4321. this._onChangeCallback();
  4322. }
  4323. get order() {
  4324. return this._order;
  4325. }
  4326. set order( value ) {
  4327. this._order = value;
  4328. this._onChangeCallback();
  4329. }
  4330. set( x, y, z, order = this._order ) {
  4331. this._x = x;
  4332. this._y = y;
  4333. this._z = z;
  4334. this._order = order;
  4335. this._onChangeCallback();
  4336. return this;
  4337. }
  4338. clone() {
  4339. return new this.constructor( this._x, this._y, this._z, this._order );
  4340. }
  4341. copy( euler ) {
  4342. this._x = euler._x;
  4343. this._y = euler._y;
  4344. this._z = euler._z;
  4345. this._order = euler._order;
  4346. this._onChangeCallback();
  4347. return this;
  4348. }
  4349. setFromRotationMatrix( m, order = this._order, update = true ) {
  4350. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4351. const te = m.elements;
  4352. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4353. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4354. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4355. switch ( order ) {
  4356. case 'XYZ':
  4357. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4358. if ( Math.abs( m13 ) < 0.9999999 ) {
  4359. this._x = Math.atan2( - m23, m33 );
  4360. this._z = Math.atan2( - m12, m11 );
  4361. } else {
  4362. this._x = Math.atan2( m32, m22 );
  4363. this._z = 0;
  4364. }
  4365. break;
  4366. case 'YXZ':
  4367. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4368. if ( Math.abs( m23 ) < 0.9999999 ) {
  4369. this._y = Math.atan2( m13, m33 );
  4370. this._z = Math.atan2( m21, m22 );
  4371. } else {
  4372. this._y = Math.atan2( - m31, m11 );
  4373. this._z = 0;
  4374. }
  4375. break;
  4376. case 'ZXY':
  4377. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4378. if ( Math.abs( m32 ) < 0.9999999 ) {
  4379. this._y = Math.atan2( - m31, m33 );
  4380. this._z = Math.atan2( - m12, m22 );
  4381. } else {
  4382. this._y = 0;
  4383. this._z = Math.atan2( m21, m11 );
  4384. }
  4385. break;
  4386. case 'ZYX':
  4387. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4388. if ( Math.abs( m31 ) < 0.9999999 ) {
  4389. this._x = Math.atan2( m32, m33 );
  4390. this._z = Math.atan2( m21, m11 );
  4391. } else {
  4392. this._x = 0;
  4393. this._z = Math.atan2( - m12, m22 );
  4394. }
  4395. break;
  4396. case 'YZX':
  4397. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4398. if ( Math.abs( m21 ) < 0.9999999 ) {
  4399. this._x = Math.atan2( - m23, m22 );
  4400. this._y = Math.atan2( - m31, m11 );
  4401. } else {
  4402. this._x = 0;
  4403. this._y = Math.atan2( m13, m33 );
  4404. }
  4405. break;
  4406. case 'XZY':
  4407. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  4408. if ( Math.abs( m12 ) < 0.9999999 ) {
  4409. this._x = Math.atan2( m32, m22 );
  4410. this._y = Math.atan2( m13, m11 );
  4411. } else {
  4412. this._x = Math.atan2( - m23, m33 );
  4413. this._y = 0;
  4414. }
  4415. break;
  4416. default:
  4417. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4418. }
  4419. this._order = order;
  4420. if ( update === true ) this._onChangeCallback();
  4421. return this;
  4422. }
  4423. setFromQuaternion( q, order, update ) {
  4424. _matrix$1.makeRotationFromQuaternion( q );
  4425. return this.setFromRotationMatrix( _matrix$1, order, update );
  4426. }
  4427. setFromVector3( v, order = this._order ) {
  4428. return this.set( v.x, v.y, v.z, order );
  4429. }
  4430. reorder( newOrder ) {
  4431. // WARNING: this discards revolution information -bhouston
  4432. _quaternion$3.setFromEuler( this );
  4433. return this.setFromQuaternion( _quaternion$3, newOrder );
  4434. }
  4435. equals( euler ) {
  4436. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4437. }
  4438. fromArray( array ) {
  4439. this._x = array[ 0 ];
  4440. this._y = array[ 1 ];
  4441. this._z = array[ 2 ];
  4442. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4443. this._onChangeCallback();
  4444. return this;
  4445. }
  4446. toArray( array = [], offset = 0 ) {
  4447. array[ offset ] = this._x;
  4448. array[ offset + 1 ] = this._y;
  4449. array[ offset + 2 ] = this._z;
  4450. array[ offset + 3 ] = this._order;
  4451. return array;
  4452. }
  4453. _onChange( callback ) {
  4454. this._onChangeCallback = callback;
  4455. return this;
  4456. }
  4457. _onChangeCallback() {}
  4458. *[ Symbol.iterator ]() {
  4459. yield this._x;
  4460. yield this._y;
  4461. yield this._z;
  4462. yield this._order;
  4463. }
  4464. }
  4465. Euler.DEFAULT_ORDER = 'XYZ';
  4466. class Layers {
  4467. constructor() {
  4468. this.mask = 1 | 0;
  4469. }
  4470. set( channel ) {
  4471. this.mask = ( 1 << channel | 0 ) >>> 0;
  4472. }
  4473. enable( channel ) {
  4474. this.mask |= 1 << channel | 0;
  4475. }
  4476. enableAll() {
  4477. this.mask = 0xffffffff | 0;
  4478. }
  4479. toggle( channel ) {
  4480. this.mask ^= 1 << channel | 0;
  4481. }
  4482. disable( channel ) {
  4483. this.mask &= ~ ( 1 << channel | 0 );
  4484. }
  4485. disableAll() {
  4486. this.mask = 0;
  4487. }
  4488. test( layers ) {
  4489. return ( this.mask & layers.mask ) !== 0;
  4490. }
  4491. isEnabled( channel ) {
  4492. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4493. }
  4494. }
  4495. let _object3DId = 0;
  4496. const _v1$4 = /*@__PURE__*/ new Vector3();
  4497. const _q1 = /*@__PURE__*/ new Quaternion();
  4498. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4499. const _target = /*@__PURE__*/ new Vector3();
  4500. const _position$3 = /*@__PURE__*/ new Vector3();
  4501. const _scale$2 = /*@__PURE__*/ new Vector3();
  4502. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4503. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4504. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4505. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4506. const _addedEvent = { type: 'added' };
  4507. const _removedEvent = { type: 'removed' };
  4508. class Object3D extends EventDispatcher {
  4509. constructor() {
  4510. super();
  4511. this.isObject3D = true;
  4512. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4513. this.uuid = generateUUID();
  4514. this.name = '';
  4515. this.type = 'Object3D';
  4516. this.parent = null;
  4517. this.children = [];
  4518. this.up = Object3D.DEFAULT_UP.clone();
  4519. const position = new Vector3();
  4520. const rotation = new Euler();
  4521. const quaternion = new Quaternion();
  4522. const scale = new Vector3( 1, 1, 1 );
  4523. function onRotationChange() {
  4524. quaternion.setFromEuler( rotation, false );
  4525. }
  4526. function onQuaternionChange() {
  4527. rotation.setFromQuaternion( quaternion, undefined, false );
  4528. }
  4529. rotation._onChange( onRotationChange );
  4530. quaternion._onChange( onQuaternionChange );
  4531. Object.defineProperties( this, {
  4532. position: {
  4533. configurable: true,
  4534. enumerable: true,
  4535. value: position
  4536. },
  4537. rotation: {
  4538. configurable: true,
  4539. enumerable: true,
  4540. value: rotation
  4541. },
  4542. quaternion: {
  4543. configurable: true,
  4544. enumerable: true,
  4545. value: quaternion
  4546. },
  4547. scale: {
  4548. configurable: true,
  4549. enumerable: true,
  4550. value: scale
  4551. },
  4552. modelViewMatrix: {
  4553. value: new Matrix4()
  4554. },
  4555. normalMatrix: {
  4556. value: new Matrix3()
  4557. }
  4558. } );
  4559. this.matrix = new Matrix4();
  4560. this.matrixWorld = new Matrix4();
  4561. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4562. this.matrixWorldNeedsUpdate = false;
  4563. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4564. this.layers = new Layers();
  4565. this.visible = true;
  4566. this.castShadow = false;
  4567. this.receiveShadow = false;
  4568. this.frustumCulled = true;
  4569. this.renderOrder = 0;
  4570. this.animations = [];
  4571. this.userData = {};
  4572. }
  4573. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4574. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4575. applyMatrix4( matrix ) {
  4576. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4577. this.matrix.premultiply( matrix );
  4578. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4579. }
  4580. applyQuaternion( q ) {
  4581. this.quaternion.premultiply( q );
  4582. return this;
  4583. }
  4584. setRotationFromAxisAngle( axis, angle ) {
  4585. // assumes axis is normalized
  4586. this.quaternion.setFromAxisAngle( axis, angle );
  4587. }
  4588. setRotationFromEuler( euler ) {
  4589. this.quaternion.setFromEuler( euler, true );
  4590. }
  4591. setRotationFromMatrix( m ) {
  4592. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4593. this.quaternion.setFromRotationMatrix( m );
  4594. }
  4595. setRotationFromQuaternion( q ) {
  4596. // assumes q is normalized
  4597. this.quaternion.copy( q );
  4598. }
  4599. rotateOnAxis( axis, angle ) {
  4600. // rotate object on axis in object space
  4601. // axis is assumed to be normalized
  4602. _q1.setFromAxisAngle( axis, angle );
  4603. this.quaternion.multiply( _q1 );
  4604. return this;
  4605. }
  4606. rotateOnWorldAxis( axis, angle ) {
  4607. // rotate object on axis in world space
  4608. // axis is assumed to be normalized
  4609. // method assumes no rotated parent
  4610. _q1.setFromAxisAngle( axis, angle );
  4611. this.quaternion.premultiply( _q1 );
  4612. return this;
  4613. }
  4614. rotateX( angle ) {
  4615. return this.rotateOnAxis( _xAxis, angle );
  4616. }
  4617. rotateY( angle ) {
  4618. return this.rotateOnAxis( _yAxis, angle );
  4619. }
  4620. rotateZ( angle ) {
  4621. return this.rotateOnAxis( _zAxis, angle );
  4622. }
  4623. translateOnAxis( axis, distance ) {
  4624. // translate object by distance along axis in object space
  4625. // axis is assumed to be normalized
  4626. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4627. this.position.add( _v1$4.multiplyScalar( distance ) );
  4628. return this;
  4629. }
  4630. translateX( distance ) {
  4631. return this.translateOnAxis( _xAxis, distance );
  4632. }
  4633. translateY( distance ) {
  4634. return this.translateOnAxis( _yAxis, distance );
  4635. }
  4636. translateZ( distance ) {
  4637. return this.translateOnAxis( _zAxis, distance );
  4638. }
  4639. localToWorld( vector ) {
  4640. this.updateWorldMatrix( true, false );
  4641. return vector.applyMatrix4( this.matrixWorld );
  4642. }
  4643. worldToLocal( vector ) {
  4644. this.updateWorldMatrix( true, false );
  4645. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4646. }
  4647. lookAt( x, y, z ) {
  4648. // This method does not support objects having non-uniformly-scaled parent(s)
  4649. if ( x.isVector3 ) {
  4650. _target.copy( x );
  4651. } else {
  4652. _target.set( x, y, z );
  4653. }
  4654. const parent = this.parent;
  4655. this.updateWorldMatrix( true, false );
  4656. _position$3.setFromMatrixPosition( this.matrixWorld );
  4657. if ( this.isCamera || this.isLight ) {
  4658. _m1$1.lookAt( _position$3, _target, this.up );
  4659. } else {
  4660. _m1$1.lookAt( _target, _position$3, this.up );
  4661. }
  4662. this.quaternion.setFromRotationMatrix( _m1$1 );
  4663. if ( parent ) {
  4664. _m1$1.extractRotation( parent.matrixWorld );
  4665. _q1.setFromRotationMatrix( _m1$1 );
  4666. this.quaternion.premultiply( _q1.invert() );
  4667. }
  4668. }
  4669. add( object ) {
  4670. if ( arguments.length > 1 ) {
  4671. for ( let i = 0; i < arguments.length; i ++ ) {
  4672. this.add( arguments[ i ] );
  4673. }
  4674. return this;
  4675. }
  4676. if ( object === this ) {
  4677. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4678. return this;
  4679. }
  4680. if ( object && object.isObject3D ) {
  4681. if ( object.parent !== null ) {
  4682. object.parent.remove( object );
  4683. }
  4684. object.parent = this;
  4685. this.children.push( object );
  4686. object.dispatchEvent( _addedEvent );
  4687. } else {
  4688. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4689. }
  4690. return this;
  4691. }
  4692. remove( object ) {
  4693. if ( arguments.length > 1 ) {
  4694. for ( let i = 0; i < arguments.length; i ++ ) {
  4695. this.remove( arguments[ i ] );
  4696. }
  4697. return this;
  4698. }
  4699. const index = this.children.indexOf( object );
  4700. if ( index !== - 1 ) {
  4701. object.parent = null;
  4702. this.children.splice( index, 1 );
  4703. object.dispatchEvent( _removedEvent );
  4704. }
  4705. return this;
  4706. }
  4707. removeFromParent() {
  4708. const parent = this.parent;
  4709. if ( parent !== null ) {
  4710. parent.remove( this );
  4711. }
  4712. return this;
  4713. }
  4714. clear() {
  4715. for ( let i = 0; i < this.children.length; i ++ ) {
  4716. const object = this.children[ i ];
  4717. object.parent = null;
  4718. object.dispatchEvent( _removedEvent );
  4719. }
  4720. this.children.length = 0;
  4721. return this;
  4722. }
  4723. attach( object ) {
  4724. // adds object as a child of this, while maintaining the object's world transform
  4725. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4726. this.updateWorldMatrix( true, false );
  4727. _m1$1.copy( this.matrixWorld ).invert();
  4728. if ( object.parent !== null ) {
  4729. object.parent.updateWorldMatrix( true, false );
  4730. _m1$1.multiply( object.parent.matrixWorld );
  4731. }
  4732. object.applyMatrix4( _m1$1 );
  4733. this.add( object );
  4734. object.updateWorldMatrix( false, true );
  4735. return this;
  4736. }
  4737. getObjectById( id ) {
  4738. return this.getObjectByProperty( 'id', id );
  4739. }
  4740. getObjectByName( name ) {
  4741. return this.getObjectByProperty( 'name', name );
  4742. }
  4743. getObjectByProperty( name, value ) {
  4744. if ( this[ name ] === value ) return this;
  4745. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4746. const child = this.children[ i ];
  4747. const object = child.getObjectByProperty( name, value );
  4748. if ( object !== undefined ) {
  4749. return object;
  4750. }
  4751. }
  4752. return undefined;
  4753. }
  4754. getObjectsByProperty( name, value ) {
  4755. let result = [];
  4756. if ( this[ name ] === value ) result.push( this );
  4757. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4758. const childResult = this.children[ i ].getObjectsByProperty( name, value );
  4759. if ( childResult.length > 0 ) {
  4760. result = result.concat( childResult );
  4761. }
  4762. }
  4763. return result;
  4764. }
  4765. getWorldPosition( target ) {
  4766. this.updateWorldMatrix( true, false );
  4767. return target.setFromMatrixPosition( this.matrixWorld );
  4768. }
  4769. getWorldQuaternion( target ) {
  4770. this.updateWorldMatrix( true, false );
  4771. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4772. return target;
  4773. }
  4774. getWorldScale( target ) {
  4775. this.updateWorldMatrix( true, false );
  4776. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4777. return target;
  4778. }
  4779. getWorldDirection( target ) {
  4780. this.updateWorldMatrix( true, false );
  4781. const e = this.matrixWorld.elements;
  4782. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4783. }
  4784. raycast( /* raycaster, intersects */ ) {}
  4785. traverse( callback ) {
  4786. callback( this );
  4787. const children = this.children;
  4788. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4789. children[ i ].traverse( callback );
  4790. }
  4791. }
  4792. traverseVisible( callback ) {
  4793. if ( this.visible === false ) return;
  4794. callback( this );
  4795. const children = this.children;
  4796. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4797. children[ i ].traverseVisible( callback );
  4798. }
  4799. }
  4800. traverseAncestors( callback ) {
  4801. const parent = this.parent;
  4802. if ( parent !== null ) {
  4803. callback( parent );
  4804. parent.traverseAncestors( callback );
  4805. }
  4806. }
  4807. updateMatrix() {
  4808. this.matrix.compose( this.position, this.quaternion, this.scale );
  4809. this.matrixWorldNeedsUpdate = true;
  4810. }
  4811. updateMatrixWorld( force ) {
  4812. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4813. if ( this.matrixWorldNeedsUpdate || force ) {
  4814. if ( this.parent === null ) {
  4815. this.matrixWorld.copy( this.matrix );
  4816. } else {
  4817. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4818. }
  4819. this.matrixWorldNeedsUpdate = false;
  4820. force = true;
  4821. }
  4822. // update children
  4823. const children = this.children;
  4824. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4825. const child = children[ i ];
  4826. if ( child.matrixWorldAutoUpdate === true || force === true ) {
  4827. child.updateMatrixWorld( force );
  4828. }
  4829. }
  4830. }
  4831. updateWorldMatrix( updateParents, updateChildren ) {
  4832. const parent = this.parent;
  4833. if ( updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true ) {
  4834. parent.updateWorldMatrix( true, false );
  4835. }
  4836. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4837. if ( this.parent === null ) {
  4838. this.matrixWorld.copy( this.matrix );
  4839. } else {
  4840. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4841. }
  4842. // update children
  4843. if ( updateChildren === true ) {
  4844. const children = this.children;
  4845. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4846. const child = children[ i ];
  4847. if ( child.matrixWorldAutoUpdate === true ) {
  4848. child.updateWorldMatrix( false, true );
  4849. }
  4850. }
  4851. }
  4852. }
  4853. toJSON( meta ) {
  4854. // meta is a string when called from JSON.stringify
  4855. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4856. const output = {};
  4857. // meta is a hash used to collect geometries, materials.
  4858. // not providing it implies that this is the root object
  4859. // being serialized.
  4860. if ( isRootObject ) {
  4861. // initialize meta obj
  4862. meta = {
  4863. geometries: {},
  4864. materials: {},
  4865. textures: {},
  4866. images: {},
  4867. shapes: {},
  4868. skeletons: {},
  4869. animations: {},
  4870. nodes: {}
  4871. };
  4872. output.metadata = {
  4873. version: 4.5,
  4874. type: 'Object',
  4875. generator: 'Object3D.toJSON'
  4876. };
  4877. }
  4878. // standard Object3D serialization
  4879. const object = {};
  4880. object.uuid = this.uuid;
  4881. object.type = this.type;
  4882. if ( this.name !== '' ) object.name = this.name;
  4883. if ( this.castShadow === true ) object.castShadow = true;
  4884. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4885. if ( this.visible === false ) object.visible = false;
  4886. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4887. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4888. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4889. object.layers = this.layers.mask;
  4890. object.matrix = this.matrix.toArray();
  4891. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4892. // object specific properties
  4893. if ( this.isInstancedMesh ) {
  4894. object.type = 'InstancedMesh';
  4895. object.count = this.count;
  4896. object.instanceMatrix = this.instanceMatrix.toJSON();
  4897. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4898. }
  4899. //
  4900. function serialize( library, element ) {
  4901. if ( library[ element.uuid ] === undefined ) {
  4902. library[ element.uuid ] = element.toJSON( meta );
  4903. }
  4904. return element.uuid;
  4905. }
  4906. if ( this.isScene ) {
  4907. if ( this.background ) {
  4908. if ( this.background.isColor ) {
  4909. object.background = this.background.toJSON();
  4910. } else if ( this.background.isTexture ) {
  4911. object.background = this.background.toJSON( meta ).uuid;
  4912. }
  4913. }
  4914. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4915. object.environment = this.environment.toJSON( meta ).uuid;
  4916. }
  4917. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4918. object.geometry = serialize( meta.geometries, this.geometry );
  4919. const parameters = this.geometry.parameters;
  4920. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4921. const shapes = parameters.shapes;
  4922. if ( Array.isArray( shapes ) ) {
  4923. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4924. const shape = shapes[ i ];
  4925. serialize( meta.shapes, shape );
  4926. }
  4927. } else {
  4928. serialize( meta.shapes, shapes );
  4929. }
  4930. }
  4931. }
  4932. if ( this.isSkinnedMesh ) {
  4933. object.bindMode = this.bindMode;
  4934. object.bindMatrix = this.bindMatrix.toArray();
  4935. if ( this.skeleton !== undefined ) {
  4936. serialize( meta.skeletons, this.skeleton );
  4937. object.skeleton = this.skeleton.uuid;
  4938. }
  4939. }
  4940. if ( this.material !== undefined ) {
  4941. if ( Array.isArray( this.material ) ) {
  4942. const uuids = [];
  4943. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4944. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4945. }
  4946. object.material = uuids;
  4947. } else {
  4948. object.material = serialize( meta.materials, this.material );
  4949. }
  4950. }
  4951. //
  4952. if ( this.children.length > 0 ) {
  4953. object.children = [];
  4954. for ( let i = 0; i < this.children.length; i ++ ) {
  4955. object.children.push( this.children[ i ].toJSON( meta ).object );
  4956. }
  4957. }
  4958. //
  4959. if ( this.animations.length > 0 ) {
  4960. object.animations = [];
  4961. for ( let i = 0; i < this.animations.length; i ++ ) {
  4962. const animation = this.animations[ i ];
  4963. object.animations.push( serialize( meta.animations, animation ) );
  4964. }
  4965. }
  4966. if ( isRootObject ) {
  4967. const geometries = extractFromCache( meta.geometries );
  4968. const materials = extractFromCache( meta.materials );
  4969. const textures = extractFromCache( meta.textures );
  4970. const images = extractFromCache( meta.images );
  4971. const shapes = extractFromCache( meta.shapes );
  4972. const skeletons = extractFromCache( meta.skeletons );
  4973. const animations = extractFromCache( meta.animations );
  4974. const nodes = extractFromCache( meta.nodes );
  4975. if ( geometries.length > 0 ) output.geometries = geometries;
  4976. if ( materials.length > 0 ) output.materials = materials;
  4977. if ( textures.length > 0 ) output.textures = textures;
  4978. if ( images.length > 0 ) output.images = images;
  4979. if ( shapes.length > 0 ) output.shapes = shapes;
  4980. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4981. if ( animations.length > 0 ) output.animations = animations;
  4982. if ( nodes.length > 0 ) output.nodes = nodes;
  4983. }
  4984. output.object = object;
  4985. return output;
  4986. // extract data from the cache hash
  4987. // remove metadata on each item
  4988. // and return as array
  4989. function extractFromCache( cache ) {
  4990. const values = [];
  4991. for ( const key in cache ) {
  4992. const data = cache[ key ];
  4993. delete data.metadata;
  4994. values.push( data );
  4995. }
  4996. return values;
  4997. }
  4998. }
  4999. clone( recursive ) {
  5000. return new this.constructor().copy( this, recursive );
  5001. }
  5002. copy( source, recursive = true ) {
  5003. this.name = source.name;
  5004. this.up.copy( source.up );
  5005. this.position.copy( source.position );
  5006. this.rotation.order = source.rotation.order;
  5007. this.quaternion.copy( source.quaternion );
  5008. this.scale.copy( source.scale );
  5009. this.matrix.copy( source.matrix );
  5010. this.matrixWorld.copy( source.matrixWorld );
  5011. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5012. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5013. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  5014. this.layers.mask = source.layers.mask;
  5015. this.visible = source.visible;
  5016. this.castShadow = source.castShadow;
  5017. this.receiveShadow = source.receiveShadow;
  5018. this.frustumCulled = source.frustumCulled;
  5019. this.renderOrder = source.renderOrder;
  5020. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5021. if ( recursive === true ) {
  5022. for ( let i = 0; i < source.children.length; i ++ ) {
  5023. const child = source.children[ i ];
  5024. this.add( child.clone() );
  5025. }
  5026. }
  5027. return this;
  5028. }
  5029. }
  5030. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  5031. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  5032. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  5033. const _v0$1 = /*@__PURE__*/ new Vector3();
  5034. const _v1$3 = /*@__PURE__*/ new Vector3();
  5035. const _v2$2 = /*@__PURE__*/ new Vector3();
  5036. const _v3$1 = /*@__PURE__*/ new Vector3();
  5037. const _vab = /*@__PURE__*/ new Vector3();
  5038. const _vac = /*@__PURE__*/ new Vector3();
  5039. const _vbc = /*@__PURE__*/ new Vector3();
  5040. const _vap = /*@__PURE__*/ new Vector3();
  5041. const _vbp = /*@__PURE__*/ new Vector3();
  5042. const _vcp = /*@__PURE__*/ new Vector3();
  5043. class Triangle {
  5044. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  5045. this.a = a;
  5046. this.b = b;
  5047. this.c = c;
  5048. }
  5049. static getNormal( a, b, c, target ) {
  5050. target.subVectors( c, b );
  5051. _v0$1.subVectors( a, b );
  5052. target.cross( _v0$1 );
  5053. const targetLengthSq = target.lengthSq();
  5054. if ( targetLengthSq > 0 ) {
  5055. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  5056. }
  5057. return target.set( 0, 0, 0 );
  5058. }
  5059. // static/instance method to calculate barycentric coordinates
  5060. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  5061. static getBarycoord( point, a, b, c, target ) {
  5062. _v0$1.subVectors( c, a );
  5063. _v1$3.subVectors( b, a );
  5064. _v2$2.subVectors( point, a );
  5065. const dot00 = _v0$1.dot( _v0$1 );
  5066. const dot01 = _v0$1.dot( _v1$3 );
  5067. const dot02 = _v0$1.dot( _v2$2 );
  5068. const dot11 = _v1$3.dot( _v1$3 );
  5069. const dot12 = _v1$3.dot( _v2$2 );
  5070. const denom = ( dot00 * dot11 - dot01 * dot01 );
  5071. // collinear or singular triangle
  5072. if ( denom === 0 ) {
  5073. // arbitrary location outside of triangle?
  5074. // not sure if this is the best idea, maybe should be returning undefined
  5075. return target.set( - 2, - 1, - 1 );
  5076. }
  5077. const invDenom = 1 / denom;
  5078. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  5079. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  5080. // barycentric coordinates must always sum to 1
  5081. return target.set( 1 - u - v, v, u );
  5082. }
  5083. static containsPoint( point, a, b, c ) {
  5084. this.getBarycoord( point, a, b, c, _v3$1 );
  5085. return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 );
  5086. }
  5087. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  5088. this.getBarycoord( point, p1, p2, p3, _v3$1 );
  5089. target.set( 0, 0 );
  5090. target.addScaledVector( uv1, _v3$1.x );
  5091. target.addScaledVector( uv2, _v3$1.y );
  5092. target.addScaledVector( uv3, _v3$1.z );
  5093. return target;
  5094. }
  5095. static isFrontFacing( a, b, c, direction ) {
  5096. _v0$1.subVectors( c, b );
  5097. _v1$3.subVectors( a, b );
  5098. // strictly front facing
  5099. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  5100. }
  5101. set( a, b, c ) {
  5102. this.a.copy( a );
  5103. this.b.copy( b );
  5104. this.c.copy( c );
  5105. return this;
  5106. }
  5107. setFromPointsAndIndices( points, i0, i1, i2 ) {
  5108. this.a.copy( points[ i0 ] );
  5109. this.b.copy( points[ i1 ] );
  5110. this.c.copy( points[ i2 ] );
  5111. return this;
  5112. }
  5113. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  5114. this.a.fromBufferAttribute( attribute, i0 );
  5115. this.b.fromBufferAttribute( attribute, i1 );
  5116. this.c.fromBufferAttribute( attribute, i2 );
  5117. return this;
  5118. }
  5119. clone() {
  5120. return new this.constructor().copy( this );
  5121. }
  5122. copy( triangle ) {
  5123. this.a.copy( triangle.a );
  5124. this.b.copy( triangle.b );
  5125. this.c.copy( triangle.c );
  5126. return this;
  5127. }
  5128. getArea() {
  5129. _v0$1.subVectors( this.c, this.b );
  5130. _v1$3.subVectors( this.a, this.b );
  5131. return _v0$1.cross( _v1$3 ).length() * 0.5;
  5132. }
  5133. getMidpoint( target ) {
  5134. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  5135. }
  5136. getNormal( target ) {
  5137. return Triangle.getNormal( this.a, this.b, this.c, target );
  5138. }
  5139. getPlane( target ) {
  5140. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  5141. }
  5142. getBarycoord( point, target ) {
  5143. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  5144. }
  5145. getUV( point, uv1, uv2, uv3, target ) {
  5146. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  5147. }
  5148. containsPoint( point ) {
  5149. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5150. }
  5151. isFrontFacing( direction ) {
  5152. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5153. }
  5154. intersectsBox( box ) {
  5155. return box.intersectsTriangle( this );
  5156. }
  5157. closestPointToPoint( p, target ) {
  5158. const a = this.a, b = this.b, c = this.c;
  5159. let v, w;
  5160. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5161. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5162. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5163. // basically, we're distinguishing which of the voronoi regions of the triangle
  5164. // the point lies in with the minimum amount of redundant computation.
  5165. _vab.subVectors( b, a );
  5166. _vac.subVectors( c, a );
  5167. _vap.subVectors( p, a );
  5168. const d1 = _vab.dot( _vap );
  5169. const d2 = _vac.dot( _vap );
  5170. if ( d1 <= 0 && d2 <= 0 ) {
  5171. // vertex region of A; barycentric coords (1, 0, 0)
  5172. return target.copy( a );
  5173. }
  5174. _vbp.subVectors( p, b );
  5175. const d3 = _vab.dot( _vbp );
  5176. const d4 = _vac.dot( _vbp );
  5177. if ( d3 >= 0 && d4 <= d3 ) {
  5178. // vertex region of B; barycentric coords (0, 1, 0)
  5179. return target.copy( b );
  5180. }
  5181. const vc = d1 * d4 - d3 * d2;
  5182. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5183. v = d1 / ( d1 - d3 );
  5184. // edge region of AB; barycentric coords (1-v, v, 0)
  5185. return target.copy( a ).addScaledVector( _vab, v );
  5186. }
  5187. _vcp.subVectors( p, c );
  5188. const d5 = _vab.dot( _vcp );
  5189. const d6 = _vac.dot( _vcp );
  5190. if ( d6 >= 0 && d5 <= d6 ) {
  5191. // vertex region of C; barycentric coords (0, 0, 1)
  5192. return target.copy( c );
  5193. }
  5194. const vb = d5 * d2 - d1 * d6;
  5195. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5196. w = d2 / ( d2 - d6 );
  5197. // edge region of AC; barycentric coords (1-w, 0, w)
  5198. return target.copy( a ).addScaledVector( _vac, w );
  5199. }
  5200. const va = d3 * d6 - d5 * d4;
  5201. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5202. _vbc.subVectors( c, b );
  5203. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5204. // edge region of BC; barycentric coords (0, 1-w, w)
  5205. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5206. }
  5207. // face region
  5208. const denom = 1 / ( va + vb + vc );
  5209. // u = va * denom
  5210. v = vb * denom;
  5211. w = vc * denom;
  5212. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5213. }
  5214. equals( triangle ) {
  5215. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5216. }
  5217. }
  5218. let materialId = 0;
  5219. class Material extends EventDispatcher {
  5220. constructor() {
  5221. super();
  5222. this.isMaterial = true;
  5223. Object.defineProperty( this, 'id', { value: materialId ++ } );
  5224. this.uuid = generateUUID();
  5225. this.name = '';
  5226. this.type = 'Material';
  5227. this.blending = NormalBlending;
  5228. this.side = FrontSide;
  5229. this.vertexColors = false;
  5230. this.opacity = 1;
  5231. this.transparent = false;
  5232. this.blendSrc = SrcAlphaFactor;
  5233. this.blendDst = OneMinusSrcAlphaFactor;
  5234. this.blendEquation = AddEquation;
  5235. this.blendSrcAlpha = null;
  5236. this.blendDstAlpha = null;
  5237. this.blendEquationAlpha = null;
  5238. this.depthFunc = LessEqualDepth;
  5239. this.depthTest = true;
  5240. this.depthWrite = true;
  5241. this.stencilWriteMask = 0xff;
  5242. this.stencilFunc = AlwaysStencilFunc;
  5243. this.stencilRef = 0;
  5244. this.stencilFuncMask = 0xff;
  5245. this.stencilFail = KeepStencilOp;
  5246. this.stencilZFail = KeepStencilOp;
  5247. this.stencilZPass = KeepStencilOp;
  5248. this.stencilWrite = false;
  5249. this.clippingPlanes = null;
  5250. this.clipIntersection = false;
  5251. this.clipShadows = false;
  5252. this.shadowSide = null;
  5253. this.colorWrite = true;
  5254. this.precision = null; // override the renderer's default precision for this material
  5255. this.polygonOffset = false;
  5256. this.polygonOffsetFactor = 0;
  5257. this.polygonOffsetUnits = 0;
  5258. this.dithering = false;
  5259. this.alphaToCoverage = false;
  5260. this.premultipliedAlpha = false;
  5261. this.forceSinglePass = false;
  5262. this.visible = true;
  5263. this.toneMapped = true;
  5264. this.userData = {};
  5265. this.version = 0;
  5266. this._alphaTest = 0;
  5267. }
  5268. get alphaTest() {
  5269. return this._alphaTest;
  5270. }
  5271. set alphaTest( value ) {
  5272. if ( this._alphaTest > 0 !== value > 0 ) {
  5273. this.version ++;
  5274. }
  5275. this._alphaTest = value;
  5276. }
  5277. onBuild( /* shaderobject, renderer */ ) {}
  5278. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  5279. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5280. customProgramCacheKey() {
  5281. return this.onBeforeCompile.toString();
  5282. }
  5283. setValues( values ) {
  5284. if ( values === undefined ) return;
  5285. for ( const key in values ) {
  5286. const newValue = values[ key ];
  5287. if ( newValue === undefined ) {
  5288. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  5289. continue;
  5290. }
  5291. const currentValue = this[ key ];
  5292. if ( currentValue === undefined ) {
  5293. console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' );
  5294. continue;
  5295. }
  5296. if ( currentValue && currentValue.isColor ) {
  5297. currentValue.set( newValue );
  5298. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5299. currentValue.copy( newValue );
  5300. } else {
  5301. this[ key ] = newValue;
  5302. }
  5303. }
  5304. }
  5305. toJSON( meta ) {
  5306. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5307. if ( isRootObject ) {
  5308. meta = {
  5309. textures: {},
  5310. images: {}
  5311. };
  5312. }
  5313. const data = {
  5314. metadata: {
  5315. version: 4.5,
  5316. type: 'Material',
  5317. generator: 'Material.toJSON'
  5318. }
  5319. };
  5320. // standard Material serialization
  5321. data.uuid = this.uuid;
  5322. data.type = this.type;
  5323. if ( this.name !== '' ) data.name = this.name;
  5324. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5325. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5326. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5327. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5328. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5329. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5330. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5331. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5332. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5333. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5334. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5335. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5336. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5337. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5338. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5339. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5340. }
  5341. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5342. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5343. }
  5344. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5345. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5346. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5347. }
  5348. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5349. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5350. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5351. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5352. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5353. }
  5354. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5355. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5356. }
  5357. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5358. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5359. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5360. if ( this.lightMap && this.lightMap.isTexture ) {
  5361. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5362. data.lightMapIntensity = this.lightMapIntensity;
  5363. }
  5364. if ( this.aoMap && this.aoMap.isTexture ) {
  5365. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5366. data.aoMapIntensity = this.aoMapIntensity;
  5367. }
  5368. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5369. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5370. data.bumpScale = this.bumpScale;
  5371. }
  5372. if ( this.normalMap && this.normalMap.isTexture ) {
  5373. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5374. data.normalMapType = this.normalMapType;
  5375. data.normalScale = this.normalScale.toArray();
  5376. }
  5377. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5378. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5379. data.displacementScale = this.displacementScale;
  5380. data.displacementBias = this.displacementBias;
  5381. }
  5382. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5383. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5384. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5385. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5386. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5387. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5388. if ( this.envMap && this.envMap.isTexture ) {
  5389. data.envMap = this.envMap.toJSON( meta ).uuid;
  5390. if ( this.combine !== undefined ) data.combine = this.combine;
  5391. }
  5392. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5393. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5394. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5395. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5396. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5397. }
  5398. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5399. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5400. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5401. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5402. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5403. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5404. if ( this.size !== undefined ) data.size = this.size;
  5405. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5406. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5407. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5408. if ( this.side !== FrontSide ) data.side = this.side;
  5409. if ( this.vertexColors ) data.vertexColors = true;
  5410. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5411. if ( this.transparent === true ) data.transparent = this.transparent;
  5412. data.depthFunc = this.depthFunc;
  5413. data.depthTest = this.depthTest;
  5414. data.depthWrite = this.depthWrite;
  5415. data.colorWrite = this.colorWrite;
  5416. data.stencilWrite = this.stencilWrite;
  5417. data.stencilWriteMask = this.stencilWriteMask;
  5418. data.stencilFunc = this.stencilFunc;
  5419. data.stencilRef = this.stencilRef;
  5420. data.stencilFuncMask = this.stencilFuncMask;
  5421. data.stencilFail = this.stencilFail;
  5422. data.stencilZFail = this.stencilZFail;
  5423. data.stencilZPass = this.stencilZPass;
  5424. // rotation (SpriteMaterial)
  5425. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5426. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5427. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5428. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5429. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5430. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5431. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5432. if ( this.scale !== undefined ) data.scale = this.scale;
  5433. if ( this.dithering === true ) data.dithering = true;
  5434. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5435. if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage;
  5436. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  5437. if ( this.forceSinglePass === true ) data.forceSinglePass = this.forceSinglePass;
  5438. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  5439. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5440. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5441. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5442. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  5443. if ( this.visible === false ) data.visible = false;
  5444. if ( this.toneMapped === false ) data.toneMapped = false;
  5445. if ( this.fog === false ) data.fog = false;
  5446. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5447. // TODO: Copied from Object3D.toJSON
  5448. function extractFromCache( cache ) {
  5449. const values = [];
  5450. for ( const key in cache ) {
  5451. const data = cache[ key ];
  5452. delete data.metadata;
  5453. values.push( data );
  5454. }
  5455. return values;
  5456. }
  5457. if ( isRootObject ) {
  5458. const textures = extractFromCache( meta.textures );
  5459. const images = extractFromCache( meta.images );
  5460. if ( textures.length > 0 ) data.textures = textures;
  5461. if ( images.length > 0 ) data.images = images;
  5462. }
  5463. return data;
  5464. }
  5465. clone() {
  5466. return new this.constructor().copy( this );
  5467. }
  5468. copy( source ) {
  5469. this.name = source.name;
  5470. this.blending = source.blending;
  5471. this.side = source.side;
  5472. this.vertexColors = source.vertexColors;
  5473. this.opacity = source.opacity;
  5474. this.transparent = source.transparent;
  5475. this.blendSrc = source.blendSrc;
  5476. this.blendDst = source.blendDst;
  5477. this.blendEquation = source.blendEquation;
  5478. this.blendSrcAlpha = source.blendSrcAlpha;
  5479. this.blendDstAlpha = source.blendDstAlpha;
  5480. this.blendEquationAlpha = source.blendEquationAlpha;
  5481. this.depthFunc = source.depthFunc;
  5482. this.depthTest = source.depthTest;
  5483. this.depthWrite = source.depthWrite;
  5484. this.stencilWriteMask = source.stencilWriteMask;
  5485. this.stencilFunc = source.stencilFunc;
  5486. this.stencilRef = source.stencilRef;
  5487. this.stencilFuncMask = source.stencilFuncMask;
  5488. this.stencilFail = source.stencilFail;
  5489. this.stencilZFail = source.stencilZFail;
  5490. this.stencilZPass = source.stencilZPass;
  5491. this.stencilWrite = source.stencilWrite;
  5492. const srcPlanes = source.clippingPlanes;
  5493. let dstPlanes = null;
  5494. if ( srcPlanes !== null ) {
  5495. const n = srcPlanes.length;
  5496. dstPlanes = new Array( n );
  5497. for ( let i = 0; i !== n; ++ i ) {
  5498. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5499. }
  5500. }
  5501. this.clippingPlanes = dstPlanes;
  5502. this.clipIntersection = source.clipIntersection;
  5503. this.clipShadows = source.clipShadows;
  5504. this.shadowSide = source.shadowSide;
  5505. this.colorWrite = source.colorWrite;
  5506. this.precision = source.precision;
  5507. this.polygonOffset = source.polygonOffset;
  5508. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5509. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5510. this.dithering = source.dithering;
  5511. this.alphaTest = source.alphaTest;
  5512. this.alphaToCoverage = source.alphaToCoverage;
  5513. this.premultipliedAlpha = source.premultipliedAlpha;
  5514. this.forceSinglePass = source.forceSinglePass;
  5515. this.visible = source.visible;
  5516. this.toneMapped = source.toneMapped;
  5517. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5518. return this;
  5519. }
  5520. dispose() {
  5521. this.dispatchEvent( { type: 'dispose' } );
  5522. }
  5523. set needsUpdate( value ) {
  5524. if ( value === true ) this.version ++;
  5525. }
  5526. }
  5527. class MeshBasicMaterial extends Material {
  5528. constructor( parameters ) {
  5529. super();
  5530. this.isMeshBasicMaterial = true;
  5531. this.type = 'MeshBasicMaterial';
  5532. this.color = new Color( 0xffffff ); // emissive
  5533. this.map = null;
  5534. this.lightMap = null;
  5535. this.lightMapIntensity = 1.0;
  5536. this.aoMap = null;
  5537. this.aoMapIntensity = 1.0;
  5538. this.specularMap = null;
  5539. this.alphaMap = null;
  5540. this.envMap = null;
  5541. this.combine = MultiplyOperation;
  5542. this.reflectivity = 1;
  5543. this.refractionRatio = 0.98;
  5544. this.wireframe = false;
  5545. this.wireframeLinewidth = 1;
  5546. this.wireframeLinecap = 'round';
  5547. this.wireframeLinejoin = 'round';
  5548. this.fog = true;
  5549. this.setValues( parameters );
  5550. }
  5551. copy( source ) {
  5552. super.copy( source );
  5553. this.color.copy( source.color );
  5554. this.map = source.map;
  5555. this.lightMap = source.lightMap;
  5556. this.lightMapIntensity = source.lightMapIntensity;
  5557. this.aoMap = source.aoMap;
  5558. this.aoMapIntensity = source.aoMapIntensity;
  5559. this.specularMap = source.specularMap;
  5560. this.alphaMap = source.alphaMap;
  5561. this.envMap = source.envMap;
  5562. this.combine = source.combine;
  5563. this.reflectivity = source.reflectivity;
  5564. this.refractionRatio = source.refractionRatio;
  5565. this.wireframe = source.wireframe;
  5566. this.wireframeLinewidth = source.wireframeLinewidth;
  5567. this.wireframeLinecap = source.wireframeLinecap;
  5568. this.wireframeLinejoin = source.wireframeLinejoin;
  5569. this.fog = source.fog;
  5570. return this;
  5571. }
  5572. }
  5573. const _vector$9 = /*@__PURE__*/ new Vector3();
  5574. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5575. class BufferAttribute {
  5576. constructor( array, itemSize, normalized = false ) {
  5577. if ( Array.isArray( array ) ) {
  5578. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5579. }
  5580. this.isBufferAttribute = true;
  5581. this.name = '';
  5582. this.array = array;
  5583. this.itemSize = itemSize;
  5584. this.count = array !== undefined ? array.length / itemSize : 0;
  5585. this.normalized = normalized;
  5586. this.usage = StaticDrawUsage;
  5587. this.updateRange = { offset: 0, count: - 1 };
  5588. this.version = 0;
  5589. }
  5590. onUploadCallback() {}
  5591. set needsUpdate( value ) {
  5592. if ( value === true ) this.version ++;
  5593. }
  5594. setUsage( value ) {
  5595. this.usage = value;
  5596. return this;
  5597. }
  5598. copy( source ) {
  5599. this.name = source.name;
  5600. this.array = new source.array.constructor( source.array );
  5601. this.itemSize = source.itemSize;
  5602. this.count = source.count;
  5603. this.normalized = source.normalized;
  5604. this.usage = source.usage;
  5605. return this;
  5606. }
  5607. copyAt( index1, attribute, index2 ) {
  5608. index1 *= this.itemSize;
  5609. index2 *= attribute.itemSize;
  5610. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5611. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5612. }
  5613. return this;
  5614. }
  5615. copyArray( array ) {
  5616. this.array.set( array );
  5617. return this;
  5618. }
  5619. applyMatrix3( m ) {
  5620. if ( this.itemSize === 2 ) {
  5621. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5622. _vector2$1.fromBufferAttribute( this, i );
  5623. _vector2$1.applyMatrix3( m );
  5624. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5625. }
  5626. } else if ( this.itemSize === 3 ) {
  5627. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5628. _vector$9.fromBufferAttribute( this, i );
  5629. _vector$9.applyMatrix3( m );
  5630. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5631. }
  5632. }
  5633. return this;
  5634. }
  5635. applyMatrix4( m ) {
  5636. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5637. _vector$9.fromBufferAttribute( this, i );
  5638. _vector$9.applyMatrix4( m );
  5639. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5640. }
  5641. return this;
  5642. }
  5643. applyNormalMatrix( m ) {
  5644. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5645. _vector$9.fromBufferAttribute( this, i );
  5646. _vector$9.applyNormalMatrix( m );
  5647. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5648. }
  5649. return this;
  5650. }
  5651. transformDirection( m ) {
  5652. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5653. _vector$9.fromBufferAttribute( this, i );
  5654. _vector$9.transformDirection( m );
  5655. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5656. }
  5657. return this;
  5658. }
  5659. set( value, offset = 0 ) {
  5660. // Matching BufferAttribute constructor, do not normalize the array.
  5661. this.array.set( value, offset );
  5662. return this;
  5663. }
  5664. getX( index ) {
  5665. let x = this.array[ index * this.itemSize ];
  5666. if ( this.normalized ) x = denormalize( x, this.array );
  5667. return x;
  5668. }
  5669. setX( index, x ) {
  5670. if ( this.normalized ) x = normalize( x, this.array );
  5671. this.array[ index * this.itemSize ] = x;
  5672. return this;
  5673. }
  5674. getY( index ) {
  5675. let y = this.array[ index * this.itemSize + 1 ];
  5676. if ( this.normalized ) y = denormalize( y, this.array );
  5677. return y;
  5678. }
  5679. setY( index, y ) {
  5680. if ( this.normalized ) y = normalize( y, this.array );
  5681. this.array[ index * this.itemSize + 1 ] = y;
  5682. return this;
  5683. }
  5684. getZ( index ) {
  5685. let z = this.array[ index * this.itemSize + 2 ];
  5686. if ( this.normalized ) z = denormalize( z, this.array );
  5687. return z;
  5688. }
  5689. setZ( index, z ) {
  5690. if ( this.normalized ) z = normalize( z, this.array );
  5691. this.array[ index * this.itemSize + 2 ] = z;
  5692. return this;
  5693. }
  5694. getW( index ) {
  5695. let w = this.array[ index * this.itemSize + 3 ];
  5696. if ( this.normalized ) w = denormalize( w, this.array );
  5697. return w;
  5698. }
  5699. setW( index, w ) {
  5700. if ( this.normalized ) w = normalize( w, this.array );
  5701. this.array[ index * this.itemSize + 3 ] = w;
  5702. return this;
  5703. }
  5704. setXY( index, x, y ) {
  5705. index *= this.itemSize;
  5706. if ( this.normalized ) {
  5707. x = normalize( x, this.array );
  5708. y = normalize( y, this.array );
  5709. }
  5710. this.array[ index + 0 ] = x;
  5711. this.array[ index + 1 ] = y;
  5712. return this;
  5713. }
  5714. setXYZ( index, x, y, z ) {
  5715. index *= this.itemSize;
  5716. if ( this.normalized ) {
  5717. x = normalize( x, this.array );
  5718. y = normalize( y, this.array );
  5719. z = normalize( z, this.array );
  5720. }
  5721. this.array[ index + 0 ] = x;
  5722. this.array[ index + 1 ] = y;
  5723. this.array[ index + 2 ] = z;
  5724. return this;
  5725. }
  5726. setXYZW( index, x, y, z, w ) {
  5727. index *= this.itemSize;
  5728. if ( this.normalized ) {
  5729. x = normalize( x, this.array );
  5730. y = normalize( y, this.array );
  5731. z = normalize( z, this.array );
  5732. w = normalize( w, this.array );
  5733. }
  5734. this.array[ index + 0 ] = x;
  5735. this.array[ index + 1 ] = y;
  5736. this.array[ index + 2 ] = z;
  5737. this.array[ index + 3 ] = w;
  5738. return this;
  5739. }
  5740. onUpload( callback ) {
  5741. this.onUploadCallback = callback;
  5742. return this;
  5743. }
  5744. clone() {
  5745. return new this.constructor( this.array, this.itemSize ).copy( this );
  5746. }
  5747. toJSON() {
  5748. const data = {
  5749. itemSize: this.itemSize,
  5750. type: this.array.constructor.name,
  5751. array: Array.from( this.array ),
  5752. normalized: this.normalized
  5753. };
  5754. if ( this.name !== '' ) data.name = this.name;
  5755. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  5756. if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange;
  5757. return data;
  5758. }
  5759. // @deprecated
  5760. copyColorsArray() {
  5761. console.error( 'THREE.BufferAttribute: copyColorsArray() was removed in r144.' );
  5762. }
  5763. copyVector2sArray() {
  5764. console.error( 'THREE.BufferAttribute: copyVector2sArray() was removed in r144.' );
  5765. }
  5766. copyVector3sArray() {
  5767. console.error( 'THREE.BufferAttribute: copyVector3sArray() was removed in r144.' );
  5768. }
  5769. copyVector4sArray() {
  5770. console.error( 'THREE.BufferAttribute: copyVector4sArray() was removed in r144.' );
  5771. }
  5772. }
  5773. //
  5774. class Int8BufferAttribute extends BufferAttribute {
  5775. constructor( array, itemSize, normalized ) {
  5776. super( new Int8Array( array ), itemSize, normalized );
  5777. }
  5778. }
  5779. class Uint8BufferAttribute extends BufferAttribute {
  5780. constructor( array, itemSize, normalized ) {
  5781. super( new Uint8Array( array ), itemSize, normalized );
  5782. }
  5783. }
  5784. class Uint8ClampedBufferAttribute extends BufferAttribute {
  5785. constructor( array, itemSize, normalized ) {
  5786. super( new Uint8ClampedArray( array ), itemSize, normalized );
  5787. }
  5788. }
  5789. class Int16BufferAttribute extends BufferAttribute {
  5790. constructor( array, itemSize, normalized ) {
  5791. super( new Int16Array( array ), itemSize, normalized );
  5792. }
  5793. }
  5794. class Uint16BufferAttribute extends BufferAttribute {
  5795. constructor( array, itemSize, normalized ) {
  5796. super( new Uint16Array( array ), itemSize, normalized );
  5797. }
  5798. }
  5799. class Int32BufferAttribute extends BufferAttribute {
  5800. constructor( array, itemSize, normalized ) {
  5801. super( new Int32Array( array ), itemSize, normalized );
  5802. }
  5803. }
  5804. class Uint32BufferAttribute extends BufferAttribute {
  5805. constructor( array, itemSize, normalized ) {
  5806. super( new Uint32Array( array ), itemSize, normalized );
  5807. }
  5808. }
  5809. class Float16BufferAttribute extends BufferAttribute {
  5810. constructor( array, itemSize, normalized ) {
  5811. super( new Uint16Array( array ), itemSize, normalized );
  5812. this.isFloat16BufferAttribute = true;
  5813. }
  5814. }
  5815. class Float32BufferAttribute extends BufferAttribute {
  5816. constructor( array, itemSize, normalized ) {
  5817. super( new Float32Array( array ), itemSize, normalized );
  5818. }
  5819. }
  5820. class Float64BufferAttribute extends BufferAttribute {
  5821. constructor( array, itemSize, normalized ) {
  5822. super( new Float64Array( array ), itemSize, normalized );
  5823. }
  5824. }
  5825. let _id$1 = 0;
  5826. const _m1 = /*@__PURE__*/ new Matrix4();
  5827. const _obj = /*@__PURE__*/ new Object3D();
  5828. const _offset = /*@__PURE__*/ new Vector3();
  5829. const _box$1 = /*@__PURE__*/ new Box3();
  5830. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  5831. const _vector$8 = /*@__PURE__*/ new Vector3();
  5832. class BufferGeometry extends EventDispatcher {
  5833. constructor() {
  5834. super();
  5835. this.isBufferGeometry = true;
  5836. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  5837. this.uuid = generateUUID();
  5838. this.name = '';
  5839. this.type = 'BufferGeometry';
  5840. this.index = null;
  5841. this.attributes = {};
  5842. this.morphAttributes = {};
  5843. this.morphTargetsRelative = false;
  5844. this.groups = [];
  5845. this.boundingBox = null;
  5846. this.boundingSphere = null;
  5847. this.drawRange = { start: 0, count: Infinity };
  5848. this.userData = {};
  5849. }
  5850. getIndex() {
  5851. return this.index;
  5852. }
  5853. setIndex( index ) {
  5854. if ( Array.isArray( index ) ) {
  5855. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  5856. } else {
  5857. this.index = index;
  5858. }
  5859. return this;
  5860. }
  5861. getAttribute( name ) {
  5862. return this.attributes[ name ];
  5863. }
  5864. setAttribute( name, attribute ) {
  5865. this.attributes[ name ] = attribute;
  5866. return this;
  5867. }
  5868. deleteAttribute( name ) {
  5869. delete this.attributes[ name ];
  5870. return this;
  5871. }
  5872. hasAttribute( name ) {
  5873. return this.attributes[ name ] !== undefined;
  5874. }
  5875. addGroup( start, count, materialIndex = 0 ) {
  5876. this.groups.push( {
  5877. start: start,
  5878. count: count,
  5879. materialIndex: materialIndex
  5880. } );
  5881. }
  5882. clearGroups() {
  5883. this.groups = [];
  5884. }
  5885. setDrawRange( start, count ) {
  5886. this.drawRange.start = start;
  5887. this.drawRange.count = count;
  5888. }
  5889. applyMatrix4( matrix ) {
  5890. const position = this.attributes.position;
  5891. if ( position !== undefined ) {
  5892. position.applyMatrix4( matrix );
  5893. position.needsUpdate = true;
  5894. }
  5895. const normal = this.attributes.normal;
  5896. if ( normal !== undefined ) {
  5897. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  5898. normal.applyNormalMatrix( normalMatrix );
  5899. normal.needsUpdate = true;
  5900. }
  5901. const tangent = this.attributes.tangent;
  5902. if ( tangent !== undefined ) {
  5903. tangent.transformDirection( matrix );
  5904. tangent.needsUpdate = true;
  5905. }
  5906. if ( this.boundingBox !== null ) {
  5907. this.computeBoundingBox();
  5908. }
  5909. if ( this.boundingSphere !== null ) {
  5910. this.computeBoundingSphere();
  5911. }
  5912. return this;
  5913. }
  5914. applyQuaternion( q ) {
  5915. _m1.makeRotationFromQuaternion( q );
  5916. this.applyMatrix4( _m1 );
  5917. return this;
  5918. }
  5919. rotateX( angle ) {
  5920. // rotate geometry around world x-axis
  5921. _m1.makeRotationX( angle );
  5922. this.applyMatrix4( _m1 );
  5923. return this;
  5924. }
  5925. rotateY( angle ) {
  5926. // rotate geometry around world y-axis
  5927. _m1.makeRotationY( angle );
  5928. this.applyMatrix4( _m1 );
  5929. return this;
  5930. }
  5931. rotateZ( angle ) {
  5932. // rotate geometry around world z-axis
  5933. _m1.makeRotationZ( angle );
  5934. this.applyMatrix4( _m1 );
  5935. return this;
  5936. }
  5937. translate( x, y, z ) {
  5938. // translate geometry
  5939. _m1.makeTranslation( x, y, z );
  5940. this.applyMatrix4( _m1 );
  5941. return this;
  5942. }
  5943. scale( x, y, z ) {
  5944. // scale geometry
  5945. _m1.makeScale( x, y, z );
  5946. this.applyMatrix4( _m1 );
  5947. return this;
  5948. }
  5949. lookAt( vector ) {
  5950. _obj.lookAt( vector );
  5951. _obj.updateMatrix();
  5952. this.applyMatrix4( _obj.matrix );
  5953. return this;
  5954. }
  5955. center() {
  5956. this.computeBoundingBox();
  5957. this.boundingBox.getCenter( _offset ).negate();
  5958. this.translate( _offset.x, _offset.y, _offset.z );
  5959. return this;
  5960. }
  5961. setFromPoints( points ) {
  5962. const position = [];
  5963. for ( let i = 0, l = points.length; i < l; i ++ ) {
  5964. const point = points[ i ];
  5965. position.push( point.x, point.y, point.z || 0 );
  5966. }
  5967. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  5968. return this;
  5969. }
  5970. computeBoundingBox() {
  5971. if ( this.boundingBox === null ) {
  5972. this.boundingBox = new Box3();
  5973. }
  5974. const position = this.attributes.position;
  5975. const morphAttributesPosition = this.morphAttributes.position;
  5976. if ( position && position.isGLBufferAttribute ) {
  5977. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  5978. this.boundingBox.set(
  5979. new Vector3( - Infinity, - Infinity, - Infinity ),
  5980. new Vector3( + Infinity, + Infinity, + Infinity )
  5981. );
  5982. return;
  5983. }
  5984. if ( position !== undefined ) {
  5985. this.boundingBox.setFromBufferAttribute( position );
  5986. // process morph attributes if present
  5987. if ( morphAttributesPosition ) {
  5988. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  5989. const morphAttribute = morphAttributesPosition[ i ];
  5990. _box$1.setFromBufferAttribute( morphAttribute );
  5991. if ( this.morphTargetsRelative ) {
  5992. _vector$8.addVectors( this.boundingBox.min, _box$1.min );
  5993. this.boundingBox.expandByPoint( _vector$8 );
  5994. _vector$8.addVectors( this.boundingBox.max, _box$1.max );
  5995. this.boundingBox.expandByPoint( _vector$8 );
  5996. } else {
  5997. this.boundingBox.expandByPoint( _box$1.min );
  5998. this.boundingBox.expandByPoint( _box$1.max );
  5999. }
  6000. }
  6001. }
  6002. } else {
  6003. this.boundingBox.makeEmpty();
  6004. }
  6005. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6006. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6007. }
  6008. }
  6009. computeBoundingSphere() {
  6010. if ( this.boundingSphere === null ) {
  6011. this.boundingSphere = new Sphere();
  6012. }
  6013. const position = this.attributes.position;
  6014. const morphAttributesPosition = this.morphAttributes.position;
  6015. if ( position && position.isGLBufferAttribute ) {
  6016. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  6017. this.boundingSphere.set( new Vector3(), Infinity );
  6018. return;
  6019. }
  6020. if ( position ) {
  6021. // first, find the center of the bounding sphere
  6022. const center = this.boundingSphere.center;
  6023. _box$1.setFromBufferAttribute( position );
  6024. // process morph attributes if present
  6025. if ( morphAttributesPosition ) {
  6026. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6027. const morphAttribute = morphAttributesPosition[ i ];
  6028. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6029. if ( this.morphTargetsRelative ) {
  6030. _vector$8.addVectors( _box$1.min, _boxMorphTargets.min );
  6031. _box$1.expandByPoint( _vector$8 );
  6032. _vector$8.addVectors( _box$1.max, _boxMorphTargets.max );
  6033. _box$1.expandByPoint( _vector$8 );
  6034. } else {
  6035. _box$1.expandByPoint( _boxMorphTargets.min );
  6036. _box$1.expandByPoint( _boxMorphTargets.max );
  6037. }
  6038. }
  6039. }
  6040. _box$1.getCenter( center );
  6041. // second, try to find a boundingSphere with a radius smaller than the
  6042. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6043. let maxRadiusSq = 0;
  6044. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6045. _vector$8.fromBufferAttribute( position, i );
  6046. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6047. }
  6048. // process morph attributes if present
  6049. if ( morphAttributesPosition ) {
  6050. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6051. const morphAttribute = morphAttributesPosition[ i ];
  6052. const morphTargetsRelative = this.morphTargetsRelative;
  6053. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6054. _vector$8.fromBufferAttribute( morphAttribute, j );
  6055. if ( morphTargetsRelative ) {
  6056. _offset.fromBufferAttribute( position, j );
  6057. _vector$8.add( _offset );
  6058. }
  6059. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6060. }
  6061. }
  6062. }
  6063. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6064. if ( isNaN( this.boundingSphere.radius ) ) {
  6065. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6066. }
  6067. }
  6068. }
  6069. computeTangents() {
  6070. const index = this.index;
  6071. const attributes = this.attributes;
  6072. // based on http://www.terathon.com/code/tangent.html
  6073. // (per vertex tangents)
  6074. if ( index === null ||
  6075. attributes.position === undefined ||
  6076. attributes.normal === undefined ||
  6077. attributes.uv === undefined ) {
  6078. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6079. return;
  6080. }
  6081. const indices = index.array;
  6082. const positions = attributes.position.array;
  6083. const normals = attributes.normal.array;
  6084. const uvs = attributes.uv.array;
  6085. const nVertices = positions.length / 3;
  6086. if ( this.hasAttribute( 'tangent' ) === false ) {
  6087. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  6088. }
  6089. const tangents = this.getAttribute( 'tangent' ).array;
  6090. const tan1 = [], tan2 = [];
  6091. for ( let i = 0; i < nVertices; i ++ ) {
  6092. tan1[ i ] = new Vector3();
  6093. tan2[ i ] = new Vector3();
  6094. }
  6095. const vA = new Vector3(),
  6096. vB = new Vector3(),
  6097. vC = new Vector3(),
  6098. uvA = new Vector2(),
  6099. uvB = new Vector2(),
  6100. uvC = new Vector2(),
  6101. sdir = new Vector3(),
  6102. tdir = new Vector3();
  6103. function handleTriangle( a, b, c ) {
  6104. vA.fromArray( positions, a * 3 );
  6105. vB.fromArray( positions, b * 3 );
  6106. vC.fromArray( positions, c * 3 );
  6107. uvA.fromArray( uvs, a * 2 );
  6108. uvB.fromArray( uvs, b * 2 );
  6109. uvC.fromArray( uvs, c * 2 );
  6110. vB.sub( vA );
  6111. vC.sub( vA );
  6112. uvB.sub( uvA );
  6113. uvC.sub( uvA );
  6114. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6115. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6116. if ( ! isFinite( r ) ) return;
  6117. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6118. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6119. tan1[ a ].add( sdir );
  6120. tan1[ b ].add( sdir );
  6121. tan1[ c ].add( sdir );
  6122. tan2[ a ].add( tdir );
  6123. tan2[ b ].add( tdir );
  6124. tan2[ c ].add( tdir );
  6125. }
  6126. let groups = this.groups;
  6127. if ( groups.length === 0 ) {
  6128. groups = [ {
  6129. start: 0,
  6130. count: indices.length
  6131. } ];
  6132. }
  6133. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6134. const group = groups[ i ];
  6135. const start = group.start;
  6136. const count = group.count;
  6137. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6138. handleTriangle(
  6139. indices[ j + 0 ],
  6140. indices[ j + 1 ],
  6141. indices[ j + 2 ]
  6142. );
  6143. }
  6144. }
  6145. const tmp = new Vector3(), tmp2 = new Vector3();
  6146. const n = new Vector3(), n2 = new Vector3();
  6147. function handleVertex( v ) {
  6148. n.fromArray( normals, v * 3 );
  6149. n2.copy( n );
  6150. const t = tan1[ v ];
  6151. // Gram-Schmidt orthogonalize
  6152. tmp.copy( t );
  6153. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6154. // Calculate handedness
  6155. tmp2.crossVectors( n2, t );
  6156. const test = tmp2.dot( tan2[ v ] );
  6157. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6158. tangents[ v * 4 ] = tmp.x;
  6159. tangents[ v * 4 + 1 ] = tmp.y;
  6160. tangents[ v * 4 + 2 ] = tmp.z;
  6161. tangents[ v * 4 + 3 ] = w;
  6162. }
  6163. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6164. const group = groups[ i ];
  6165. const start = group.start;
  6166. const count = group.count;
  6167. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6168. handleVertex( indices[ j + 0 ] );
  6169. handleVertex( indices[ j + 1 ] );
  6170. handleVertex( indices[ j + 2 ] );
  6171. }
  6172. }
  6173. }
  6174. computeVertexNormals() {
  6175. const index = this.index;
  6176. const positionAttribute = this.getAttribute( 'position' );
  6177. if ( positionAttribute !== undefined ) {
  6178. let normalAttribute = this.getAttribute( 'normal' );
  6179. if ( normalAttribute === undefined ) {
  6180. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6181. this.setAttribute( 'normal', normalAttribute );
  6182. } else {
  6183. // reset existing normals to zero
  6184. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6185. normalAttribute.setXYZ( i, 0, 0, 0 );
  6186. }
  6187. }
  6188. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6189. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6190. const cb = new Vector3(), ab = new Vector3();
  6191. // indexed elements
  6192. if ( index ) {
  6193. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6194. const vA = index.getX( i + 0 );
  6195. const vB = index.getX( i + 1 );
  6196. const vC = index.getX( i + 2 );
  6197. pA.fromBufferAttribute( positionAttribute, vA );
  6198. pB.fromBufferAttribute( positionAttribute, vB );
  6199. pC.fromBufferAttribute( positionAttribute, vC );
  6200. cb.subVectors( pC, pB );
  6201. ab.subVectors( pA, pB );
  6202. cb.cross( ab );
  6203. nA.fromBufferAttribute( normalAttribute, vA );
  6204. nB.fromBufferAttribute( normalAttribute, vB );
  6205. nC.fromBufferAttribute( normalAttribute, vC );
  6206. nA.add( cb );
  6207. nB.add( cb );
  6208. nC.add( cb );
  6209. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6210. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6211. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6212. }
  6213. } else {
  6214. // non-indexed elements (unconnected triangle soup)
  6215. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6216. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6217. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6218. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6219. cb.subVectors( pC, pB );
  6220. ab.subVectors( pA, pB );
  6221. cb.cross( ab );
  6222. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6223. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6224. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6225. }
  6226. }
  6227. this.normalizeNormals();
  6228. normalAttribute.needsUpdate = true;
  6229. }
  6230. }
  6231. // @deprecated since r144
  6232. merge() {
  6233. console.error( 'THREE.BufferGeometry.merge() has been removed. Use THREE.BufferGeometryUtils.mergeBufferGeometries() instead.' );
  6234. return this;
  6235. }
  6236. normalizeNormals() {
  6237. const normals = this.attributes.normal;
  6238. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6239. _vector$8.fromBufferAttribute( normals, i );
  6240. _vector$8.normalize();
  6241. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6242. }
  6243. }
  6244. toNonIndexed() {
  6245. function convertBufferAttribute( attribute, indices ) {
  6246. const array = attribute.array;
  6247. const itemSize = attribute.itemSize;
  6248. const normalized = attribute.normalized;
  6249. const array2 = new array.constructor( indices.length * itemSize );
  6250. let index = 0, index2 = 0;
  6251. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6252. if ( attribute.isInterleavedBufferAttribute ) {
  6253. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6254. } else {
  6255. index = indices[ i ] * itemSize;
  6256. }
  6257. for ( let j = 0; j < itemSize; j ++ ) {
  6258. array2[ index2 ++ ] = array[ index ++ ];
  6259. }
  6260. }
  6261. return new BufferAttribute( array2, itemSize, normalized );
  6262. }
  6263. //
  6264. if ( this.index === null ) {
  6265. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6266. return this;
  6267. }
  6268. const geometry2 = new BufferGeometry();
  6269. const indices = this.index.array;
  6270. const attributes = this.attributes;
  6271. // attributes
  6272. for ( const name in attributes ) {
  6273. const attribute = attributes[ name ];
  6274. const newAttribute = convertBufferAttribute( attribute, indices );
  6275. geometry2.setAttribute( name, newAttribute );
  6276. }
  6277. // morph attributes
  6278. const morphAttributes = this.morphAttributes;
  6279. for ( const name in morphAttributes ) {
  6280. const morphArray = [];
  6281. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6282. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6283. const attribute = morphAttribute[ i ];
  6284. const newAttribute = convertBufferAttribute( attribute, indices );
  6285. morphArray.push( newAttribute );
  6286. }
  6287. geometry2.morphAttributes[ name ] = morphArray;
  6288. }
  6289. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6290. // groups
  6291. const groups = this.groups;
  6292. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6293. const group = groups[ i ];
  6294. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6295. }
  6296. return geometry2;
  6297. }
  6298. toJSON() {
  6299. const data = {
  6300. metadata: {
  6301. version: 4.5,
  6302. type: 'BufferGeometry',
  6303. generator: 'BufferGeometry.toJSON'
  6304. }
  6305. };
  6306. // standard BufferGeometry serialization
  6307. data.uuid = this.uuid;
  6308. data.type = this.type;
  6309. if ( this.name !== '' ) data.name = this.name;
  6310. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6311. if ( this.parameters !== undefined ) {
  6312. const parameters = this.parameters;
  6313. for ( const key in parameters ) {
  6314. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6315. }
  6316. return data;
  6317. }
  6318. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6319. data.data = { attributes: {} };
  6320. const index = this.index;
  6321. if ( index !== null ) {
  6322. data.data.index = {
  6323. type: index.array.constructor.name,
  6324. array: Array.prototype.slice.call( index.array )
  6325. };
  6326. }
  6327. const attributes = this.attributes;
  6328. for ( const key in attributes ) {
  6329. const attribute = attributes[ key ];
  6330. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6331. }
  6332. const morphAttributes = {};
  6333. let hasMorphAttributes = false;
  6334. for ( const key in this.morphAttributes ) {
  6335. const attributeArray = this.morphAttributes[ key ];
  6336. const array = [];
  6337. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6338. const attribute = attributeArray[ i ];
  6339. array.push( attribute.toJSON( data.data ) );
  6340. }
  6341. if ( array.length > 0 ) {
  6342. morphAttributes[ key ] = array;
  6343. hasMorphAttributes = true;
  6344. }
  6345. }
  6346. if ( hasMorphAttributes ) {
  6347. data.data.morphAttributes = morphAttributes;
  6348. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6349. }
  6350. const groups = this.groups;
  6351. if ( groups.length > 0 ) {
  6352. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6353. }
  6354. const boundingSphere = this.boundingSphere;
  6355. if ( boundingSphere !== null ) {
  6356. data.data.boundingSphere = {
  6357. center: boundingSphere.center.toArray(),
  6358. radius: boundingSphere.radius
  6359. };
  6360. }
  6361. return data;
  6362. }
  6363. clone() {
  6364. return new this.constructor().copy( this );
  6365. }
  6366. copy( source ) {
  6367. // reset
  6368. this.index = null;
  6369. this.attributes = {};
  6370. this.morphAttributes = {};
  6371. this.groups = [];
  6372. this.boundingBox = null;
  6373. this.boundingSphere = null;
  6374. // used for storing cloned, shared data
  6375. const data = {};
  6376. // name
  6377. this.name = source.name;
  6378. // index
  6379. const index = source.index;
  6380. if ( index !== null ) {
  6381. this.setIndex( index.clone( data ) );
  6382. }
  6383. // attributes
  6384. const attributes = source.attributes;
  6385. for ( const name in attributes ) {
  6386. const attribute = attributes[ name ];
  6387. this.setAttribute( name, attribute.clone( data ) );
  6388. }
  6389. // morph attributes
  6390. const morphAttributes = source.morphAttributes;
  6391. for ( const name in morphAttributes ) {
  6392. const array = [];
  6393. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6394. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6395. array.push( morphAttribute[ i ].clone( data ) );
  6396. }
  6397. this.morphAttributes[ name ] = array;
  6398. }
  6399. this.morphTargetsRelative = source.morphTargetsRelative;
  6400. // groups
  6401. const groups = source.groups;
  6402. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6403. const group = groups[ i ];
  6404. this.addGroup( group.start, group.count, group.materialIndex );
  6405. }
  6406. // bounding box
  6407. const boundingBox = source.boundingBox;
  6408. if ( boundingBox !== null ) {
  6409. this.boundingBox = boundingBox.clone();
  6410. }
  6411. // bounding sphere
  6412. const boundingSphere = source.boundingSphere;
  6413. if ( boundingSphere !== null ) {
  6414. this.boundingSphere = boundingSphere.clone();
  6415. }
  6416. // draw range
  6417. this.drawRange.start = source.drawRange.start;
  6418. this.drawRange.count = source.drawRange.count;
  6419. // user data
  6420. this.userData = source.userData;
  6421. // geometry generator parameters
  6422. if ( source.parameters !== undefined ) this.parameters = Object.assign( {}, source.parameters );
  6423. return this;
  6424. }
  6425. dispose() {
  6426. this.dispatchEvent( { type: 'dispose' } );
  6427. }
  6428. }
  6429. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  6430. const _ray$2 = /*@__PURE__*/ new Ray();
  6431. const _sphere$3 = /*@__PURE__*/ new Sphere();
  6432. const _vA$1 = /*@__PURE__*/ new Vector3();
  6433. const _vB$1 = /*@__PURE__*/ new Vector3();
  6434. const _vC$1 = /*@__PURE__*/ new Vector3();
  6435. const _tempA = /*@__PURE__*/ new Vector3();
  6436. const _morphA = /*@__PURE__*/ new Vector3();
  6437. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6438. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6439. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6440. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6441. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6442. class Mesh extends Object3D {
  6443. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6444. super();
  6445. this.isMesh = true;
  6446. this.type = 'Mesh';
  6447. this.geometry = geometry;
  6448. this.material = material;
  6449. this.updateMorphTargets();
  6450. }
  6451. copy( source, recursive ) {
  6452. super.copy( source, recursive );
  6453. if ( source.morphTargetInfluences !== undefined ) {
  6454. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6455. }
  6456. if ( source.morphTargetDictionary !== undefined ) {
  6457. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6458. }
  6459. this.material = source.material;
  6460. this.geometry = source.geometry;
  6461. return this;
  6462. }
  6463. updateMorphTargets() {
  6464. const geometry = this.geometry;
  6465. const morphAttributes = geometry.morphAttributes;
  6466. const keys = Object.keys( morphAttributes );
  6467. if ( keys.length > 0 ) {
  6468. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6469. if ( morphAttribute !== undefined ) {
  6470. this.morphTargetInfluences = [];
  6471. this.morphTargetDictionary = {};
  6472. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6473. const name = morphAttribute[ m ].name || String( m );
  6474. this.morphTargetInfluences.push( 0 );
  6475. this.morphTargetDictionary[ name ] = m;
  6476. }
  6477. }
  6478. }
  6479. }
  6480. getVertexPosition( index, target ) {
  6481. const geometry = this.geometry;
  6482. const position = geometry.attributes.position;
  6483. const morphPosition = geometry.morphAttributes.position;
  6484. const morphTargetsRelative = geometry.morphTargetsRelative;
  6485. target.fromBufferAttribute( position, index );
  6486. const morphInfluences = this.morphTargetInfluences;
  6487. if ( morphPosition && morphInfluences ) {
  6488. _morphA.set( 0, 0, 0 );
  6489. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6490. const influence = morphInfluences[ i ];
  6491. const morphAttribute = morphPosition[ i ];
  6492. if ( influence === 0 ) continue;
  6493. _tempA.fromBufferAttribute( morphAttribute, index );
  6494. if ( morphTargetsRelative ) {
  6495. _morphA.addScaledVector( _tempA, influence );
  6496. } else {
  6497. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6498. }
  6499. }
  6500. target.add( _morphA );
  6501. }
  6502. if ( this.isSkinnedMesh ) {
  6503. this.boneTransform( index, target );
  6504. }
  6505. return target;
  6506. }
  6507. raycast( raycaster, intersects ) {
  6508. const geometry = this.geometry;
  6509. const material = this.material;
  6510. const matrixWorld = this.matrixWorld;
  6511. if ( material === undefined ) return;
  6512. // Checking boundingSphere distance to ray
  6513. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6514. _sphere$3.copy( geometry.boundingSphere );
  6515. _sphere$3.applyMatrix4( matrixWorld );
  6516. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  6517. //
  6518. _inverseMatrix$2.copy( matrixWorld ).invert();
  6519. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  6520. // Check boundingBox before continuing
  6521. if ( geometry.boundingBox !== null ) {
  6522. if ( _ray$2.intersectsBox( geometry.boundingBox ) === false ) return;
  6523. }
  6524. let intersection;
  6525. const index = geometry.index;
  6526. const position = geometry.attributes.position;
  6527. const uv = geometry.attributes.uv;
  6528. const uv2 = geometry.attributes.uv2;
  6529. const groups = geometry.groups;
  6530. const drawRange = geometry.drawRange;
  6531. if ( index !== null ) {
  6532. // indexed buffer geometry
  6533. if ( Array.isArray( material ) ) {
  6534. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6535. const group = groups[ i ];
  6536. const groupMaterial = material[ group.materialIndex ];
  6537. const start = Math.max( group.start, drawRange.start );
  6538. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6539. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6540. const a = index.getX( j );
  6541. const b = index.getX( j + 1 );
  6542. const c = index.getX( j + 2 );
  6543. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, uv, uv2, a, b, c );
  6544. if ( intersection ) {
  6545. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6546. intersection.face.materialIndex = group.materialIndex;
  6547. intersects.push( intersection );
  6548. }
  6549. }
  6550. }
  6551. } else {
  6552. const start = Math.max( 0, drawRange.start );
  6553. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6554. for ( let i = start, il = end; i < il; i += 3 ) {
  6555. const a = index.getX( i );
  6556. const b = index.getX( i + 1 );
  6557. const c = index.getX( i + 2 );
  6558. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, uv, uv2, a, b, c );
  6559. if ( intersection ) {
  6560. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6561. intersects.push( intersection );
  6562. }
  6563. }
  6564. }
  6565. } else if ( position !== undefined ) {
  6566. // non-indexed buffer geometry
  6567. if ( Array.isArray( material ) ) {
  6568. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6569. const group = groups[ i ];
  6570. const groupMaterial = material[ group.materialIndex ];
  6571. const start = Math.max( group.start, drawRange.start );
  6572. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6573. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6574. const a = j;
  6575. const b = j + 1;
  6576. const c = j + 2;
  6577. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, uv, uv2, a, b, c );
  6578. if ( intersection ) {
  6579. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6580. intersection.face.materialIndex = group.materialIndex;
  6581. intersects.push( intersection );
  6582. }
  6583. }
  6584. }
  6585. } else {
  6586. const start = Math.max( 0, drawRange.start );
  6587. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6588. for ( let i = start, il = end; i < il; i += 3 ) {
  6589. const a = i;
  6590. const b = i + 1;
  6591. const c = i + 2;
  6592. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, uv, uv2, a, b, c );
  6593. if ( intersection ) {
  6594. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  6595. intersects.push( intersection );
  6596. }
  6597. }
  6598. }
  6599. }
  6600. }
  6601. }
  6602. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  6603. let intersect;
  6604. if ( material.side === BackSide ) {
  6605. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  6606. } else {
  6607. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  6608. }
  6609. if ( intersect === null ) return null;
  6610. _intersectionPointWorld.copy( point );
  6611. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  6612. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  6613. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  6614. return {
  6615. distance: distance,
  6616. point: _intersectionPointWorld.clone(),
  6617. object: object
  6618. };
  6619. }
  6620. function checkBufferGeometryIntersection( object, material, raycaster, ray, uv, uv2, a, b, c ) {
  6621. object.getVertexPosition( a, _vA$1 );
  6622. object.getVertexPosition( b, _vB$1 );
  6623. object.getVertexPosition( c, _vC$1 );
  6624. const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  6625. if ( intersection ) {
  6626. if ( uv ) {
  6627. _uvA$1.fromBufferAttribute( uv, a );
  6628. _uvB$1.fromBufferAttribute( uv, b );
  6629. _uvC$1.fromBufferAttribute( uv, c );
  6630. intersection.uv = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6631. }
  6632. if ( uv2 ) {
  6633. _uvA$1.fromBufferAttribute( uv2, a );
  6634. _uvB$1.fromBufferAttribute( uv2, b );
  6635. _uvC$1.fromBufferAttribute( uv2, c );
  6636. intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6637. }
  6638. const face = {
  6639. a: a,
  6640. b: b,
  6641. c: c,
  6642. normal: new Vector3(),
  6643. materialIndex: 0
  6644. };
  6645. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  6646. intersection.face = face;
  6647. }
  6648. return intersection;
  6649. }
  6650. class BoxGeometry extends BufferGeometry {
  6651. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  6652. super();
  6653. this.type = 'BoxGeometry';
  6654. this.parameters = {
  6655. width: width,
  6656. height: height,
  6657. depth: depth,
  6658. widthSegments: widthSegments,
  6659. heightSegments: heightSegments,
  6660. depthSegments: depthSegments
  6661. };
  6662. const scope = this;
  6663. // segments
  6664. widthSegments = Math.floor( widthSegments );
  6665. heightSegments = Math.floor( heightSegments );
  6666. depthSegments = Math.floor( depthSegments );
  6667. // buffers
  6668. const indices = [];
  6669. const vertices = [];
  6670. const normals = [];
  6671. const uvs = [];
  6672. // helper variables
  6673. let numberOfVertices = 0;
  6674. let groupStart = 0;
  6675. // build each side of the box geometry
  6676. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  6677. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  6678. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  6679. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  6680. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  6681. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  6682. // build geometry
  6683. this.setIndex( indices );
  6684. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  6685. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  6686. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  6687. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  6688. const segmentWidth = width / gridX;
  6689. const segmentHeight = height / gridY;
  6690. const widthHalf = width / 2;
  6691. const heightHalf = height / 2;
  6692. const depthHalf = depth / 2;
  6693. const gridX1 = gridX + 1;
  6694. const gridY1 = gridY + 1;
  6695. let vertexCounter = 0;
  6696. let groupCount = 0;
  6697. const vector = new Vector3();
  6698. // generate vertices, normals and uvs
  6699. for ( let iy = 0; iy < gridY1; iy ++ ) {
  6700. const y = iy * segmentHeight - heightHalf;
  6701. for ( let ix = 0; ix < gridX1; ix ++ ) {
  6702. const x = ix * segmentWidth - widthHalf;
  6703. // set values to correct vector component
  6704. vector[ u ] = x * udir;
  6705. vector[ v ] = y * vdir;
  6706. vector[ w ] = depthHalf;
  6707. // now apply vector to vertex buffer
  6708. vertices.push( vector.x, vector.y, vector.z );
  6709. // set values to correct vector component
  6710. vector[ u ] = 0;
  6711. vector[ v ] = 0;
  6712. vector[ w ] = depth > 0 ? 1 : - 1;
  6713. // now apply vector to normal buffer
  6714. normals.push( vector.x, vector.y, vector.z );
  6715. // uvs
  6716. uvs.push( ix / gridX );
  6717. uvs.push( 1 - ( iy / gridY ) );
  6718. // counters
  6719. vertexCounter += 1;
  6720. }
  6721. }
  6722. // indices
  6723. // 1. you need three indices to draw a single face
  6724. // 2. a single segment consists of two faces
  6725. // 3. so we need to generate six (2*3) indices per segment
  6726. for ( let iy = 0; iy < gridY; iy ++ ) {
  6727. for ( let ix = 0; ix < gridX; ix ++ ) {
  6728. const a = numberOfVertices + ix + gridX1 * iy;
  6729. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  6730. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  6731. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  6732. // faces
  6733. indices.push( a, b, d );
  6734. indices.push( b, c, d );
  6735. // increase counter
  6736. groupCount += 6;
  6737. }
  6738. }
  6739. // add a group to the geometry. this will ensure multi material support
  6740. scope.addGroup( groupStart, groupCount, materialIndex );
  6741. // calculate new start value for groups
  6742. groupStart += groupCount;
  6743. // update total number of vertices
  6744. numberOfVertices += vertexCounter;
  6745. }
  6746. }
  6747. static fromJSON( data ) {
  6748. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  6749. }
  6750. }
  6751. /**
  6752. * Uniform Utilities
  6753. */
  6754. function cloneUniforms( src ) {
  6755. const dst = {};
  6756. for ( const u in src ) {
  6757. dst[ u ] = {};
  6758. for ( const p in src[ u ] ) {
  6759. const property = src[ u ][ p ];
  6760. if ( property && ( property.isColor ||
  6761. property.isMatrix3 || property.isMatrix4 ||
  6762. property.isVector2 || property.isVector3 || property.isVector4 ||
  6763. property.isTexture || property.isQuaternion ) ) {
  6764. dst[ u ][ p ] = property.clone();
  6765. } else if ( Array.isArray( property ) ) {
  6766. dst[ u ][ p ] = property.slice();
  6767. } else {
  6768. dst[ u ][ p ] = property;
  6769. }
  6770. }
  6771. }
  6772. return dst;
  6773. }
  6774. function mergeUniforms( uniforms ) {
  6775. const merged = {};
  6776. for ( let u = 0; u < uniforms.length; u ++ ) {
  6777. const tmp = cloneUniforms( uniforms[ u ] );
  6778. for ( const p in tmp ) {
  6779. merged[ p ] = tmp[ p ];
  6780. }
  6781. }
  6782. return merged;
  6783. }
  6784. function cloneUniformsGroups( src ) {
  6785. const dst = [];
  6786. for ( let u = 0; u < src.length; u ++ ) {
  6787. dst.push( src[ u ].clone() );
  6788. }
  6789. return dst;
  6790. }
  6791. function getUnlitUniformColorSpace( renderer ) {
  6792. if ( renderer.getRenderTarget() === null ) {
  6793. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  6794. return renderer.outputEncoding === sRGBEncoding ? SRGBColorSpace : LinearSRGBColorSpace;
  6795. }
  6796. return LinearSRGBColorSpace;
  6797. }
  6798. // Legacy
  6799. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  6800. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  6801. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  6802. class ShaderMaterial extends Material {
  6803. constructor( parameters ) {
  6804. super();
  6805. this.isShaderMaterial = true;
  6806. this.type = 'ShaderMaterial';
  6807. this.defines = {};
  6808. this.uniforms = {};
  6809. this.uniformsGroups = [];
  6810. this.vertexShader = default_vertex;
  6811. this.fragmentShader = default_fragment;
  6812. this.linewidth = 1;
  6813. this.wireframe = false;
  6814. this.wireframeLinewidth = 1;
  6815. this.fog = false; // set to use scene fog
  6816. this.lights = false; // set to use scene lights
  6817. this.clipping = false; // set to use user-defined clipping planes
  6818. this.extensions = {
  6819. derivatives: false, // set to use derivatives
  6820. fragDepth: false, // set to use fragment depth values
  6821. drawBuffers: false, // set to use draw buffers
  6822. shaderTextureLOD: false // set to use shader texture LOD
  6823. };
  6824. // When rendered geometry doesn't include these attributes but the material does,
  6825. // use these default values in WebGL. This avoids errors when buffer data is missing.
  6826. this.defaultAttributeValues = {
  6827. 'color': [ 1, 1, 1 ],
  6828. 'uv': [ 0, 0 ],
  6829. 'uv2': [ 0, 0 ]
  6830. };
  6831. this.index0AttributeName = undefined;
  6832. this.uniformsNeedUpdate = false;
  6833. this.glslVersion = null;
  6834. if ( parameters !== undefined ) {
  6835. this.setValues( parameters );
  6836. }
  6837. }
  6838. copy( source ) {
  6839. super.copy( source );
  6840. this.fragmentShader = source.fragmentShader;
  6841. this.vertexShader = source.vertexShader;
  6842. this.uniforms = cloneUniforms( source.uniforms );
  6843. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  6844. this.defines = Object.assign( {}, source.defines );
  6845. this.wireframe = source.wireframe;
  6846. this.wireframeLinewidth = source.wireframeLinewidth;
  6847. this.fog = source.fog;
  6848. this.lights = source.lights;
  6849. this.clipping = source.clipping;
  6850. this.extensions = Object.assign( {}, source.extensions );
  6851. this.glslVersion = source.glslVersion;
  6852. return this;
  6853. }
  6854. toJSON( meta ) {
  6855. const data = super.toJSON( meta );
  6856. data.glslVersion = this.glslVersion;
  6857. data.uniforms = {};
  6858. for ( const name in this.uniforms ) {
  6859. const uniform = this.uniforms[ name ];
  6860. const value = uniform.value;
  6861. if ( value && value.isTexture ) {
  6862. data.uniforms[ name ] = {
  6863. type: 't',
  6864. value: value.toJSON( meta ).uuid
  6865. };
  6866. } else if ( value && value.isColor ) {
  6867. data.uniforms[ name ] = {
  6868. type: 'c',
  6869. value: value.getHex()
  6870. };
  6871. } else if ( value && value.isVector2 ) {
  6872. data.uniforms[ name ] = {
  6873. type: 'v2',
  6874. value: value.toArray()
  6875. };
  6876. } else if ( value && value.isVector3 ) {
  6877. data.uniforms[ name ] = {
  6878. type: 'v3',
  6879. value: value.toArray()
  6880. };
  6881. } else if ( value && value.isVector4 ) {
  6882. data.uniforms[ name ] = {
  6883. type: 'v4',
  6884. value: value.toArray()
  6885. };
  6886. } else if ( value && value.isMatrix3 ) {
  6887. data.uniforms[ name ] = {
  6888. type: 'm3',
  6889. value: value.toArray()
  6890. };
  6891. } else if ( value && value.isMatrix4 ) {
  6892. data.uniforms[ name ] = {
  6893. type: 'm4',
  6894. value: value.toArray()
  6895. };
  6896. } else {
  6897. data.uniforms[ name ] = {
  6898. value: value
  6899. };
  6900. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  6901. }
  6902. }
  6903. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  6904. data.vertexShader = this.vertexShader;
  6905. data.fragmentShader = this.fragmentShader;
  6906. const extensions = {};
  6907. for ( const key in this.extensions ) {
  6908. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  6909. }
  6910. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  6911. return data;
  6912. }
  6913. }
  6914. class Camera extends Object3D {
  6915. constructor() {
  6916. super();
  6917. this.isCamera = true;
  6918. this.type = 'Camera';
  6919. this.matrixWorldInverse = new Matrix4();
  6920. this.projectionMatrix = new Matrix4();
  6921. this.projectionMatrixInverse = new Matrix4();
  6922. }
  6923. copy( source, recursive ) {
  6924. super.copy( source, recursive );
  6925. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  6926. this.projectionMatrix.copy( source.projectionMatrix );
  6927. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  6928. return this;
  6929. }
  6930. getWorldDirection( target ) {
  6931. this.updateWorldMatrix( true, false );
  6932. const e = this.matrixWorld.elements;
  6933. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  6934. }
  6935. updateMatrixWorld( force ) {
  6936. super.updateMatrixWorld( force );
  6937. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  6938. }
  6939. updateWorldMatrix( updateParents, updateChildren ) {
  6940. super.updateWorldMatrix( updateParents, updateChildren );
  6941. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  6942. }
  6943. clone() {
  6944. return new this.constructor().copy( this );
  6945. }
  6946. }
  6947. class PerspectiveCamera extends Camera {
  6948. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  6949. super();
  6950. this.isPerspectiveCamera = true;
  6951. this.type = 'PerspectiveCamera';
  6952. this.fov = fov;
  6953. this.zoom = 1;
  6954. this.near = near;
  6955. this.far = far;
  6956. this.focus = 10;
  6957. this.aspect = aspect;
  6958. this.view = null;
  6959. this.filmGauge = 35; // width of the film (default in millimeters)
  6960. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  6961. this.updateProjectionMatrix();
  6962. }
  6963. copy( source, recursive ) {
  6964. super.copy( source, recursive );
  6965. this.fov = source.fov;
  6966. this.zoom = source.zoom;
  6967. this.near = source.near;
  6968. this.far = source.far;
  6969. this.focus = source.focus;
  6970. this.aspect = source.aspect;
  6971. this.view = source.view === null ? null : Object.assign( {}, source.view );
  6972. this.filmGauge = source.filmGauge;
  6973. this.filmOffset = source.filmOffset;
  6974. return this;
  6975. }
  6976. /**
  6977. * Sets the FOV by focal length in respect to the current .filmGauge.
  6978. *
  6979. * The default film gauge is 35, so that the focal length can be specified for
  6980. * a 35mm (full frame) camera.
  6981. *
  6982. * Values for focal length and film gauge must have the same unit.
  6983. */
  6984. setFocalLength( focalLength ) {
  6985. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  6986. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  6987. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  6988. this.updateProjectionMatrix();
  6989. }
  6990. /**
  6991. * Calculates the focal length from the current .fov and .filmGauge.
  6992. */
  6993. getFocalLength() {
  6994. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  6995. return 0.5 * this.getFilmHeight() / vExtentSlope;
  6996. }
  6997. getEffectiveFOV() {
  6998. return RAD2DEG * 2 * Math.atan(
  6999. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7000. }
  7001. getFilmWidth() {
  7002. // film not completely covered in portrait format (aspect < 1)
  7003. return this.filmGauge * Math.min( this.aspect, 1 );
  7004. }
  7005. getFilmHeight() {
  7006. // film not completely covered in landscape format (aspect > 1)
  7007. return this.filmGauge / Math.max( this.aspect, 1 );
  7008. }
  7009. /**
  7010. * Sets an offset in a larger frustum. This is useful for multi-window or
  7011. * multi-monitor/multi-machine setups.
  7012. *
  7013. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7014. * the monitors are in grid like this
  7015. *
  7016. * +---+---+---+
  7017. * | A | B | C |
  7018. * +---+---+---+
  7019. * | D | E | F |
  7020. * +---+---+---+
  7021. *
  7022. * then for each monitor you would call it like this
  7023. *
  7024. * const w = 1920;
  7025. * const h = 1080;
  7026. * const fullWidth = w * 3;
  7027. * const fullHeight = h * 2;
  7028. *
  7029. * --A--
  7030. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7031. * --B--
  7032. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7033. * --C--
  7034. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7035. * --D--
  7036. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7037. * --E--
  7038. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7039. * --F--
  7040. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7041. *
  7042. * Note there is no reason monitors have to be the same size or in a grid.
  7043. */
  7044. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7045. this.aspect = fullWidth / fullHeight;
  7046. if ( this.view === null ) {
  7047. this.view = {
  7048. enabled: true,
  7049. fullWidth: 1,
  7050. fullHeight: 1,
  7051. offsetX: 0,
  7052. offsetY: 0,
  7053. width: 1,
  7054. height: 1
  7055. };
  7056. }
  7057. this.view.enabled = true;
  7058. this.view.fullWidth = fullWidth;
  7059. this.view.fullHeight = fullHeight;
  7060. this.view.offsetX = x;
  7061. this.view.offsetY = y;
  7062. this.view.width = width;
  7063. this.view.height = height;
  7064. this.updateProjectionMatrix();
  7065. }
  7066. clearViewOffset() {
  7067. if ( this.view !== null ) {
  7068. this.view.enabled = false;
  7069. }
  7070. this.updateProjectionMatrix();
  7071. }
  7072. updateProjectionMatrix() {
  7073. const near = this.near;
  7074. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7075. let height = 2 * top;
  7076. let width = this.aspect * height;
  7077. let left = - 0.5 * width;
  7078. const view = this.view;
  7079. if ( this.view !== null && this.view.enabled ) {
  7080. const fullWidth = view.fullWidth,
  7081. fullHeight = view.fullHeight;
  7082. left += view.offsetX * width / fullWidth;
  7083. top -= view.offsetY * height / fullHeight;
  7084. width *= view.width / fullWidth;
  7085. height *= view.height / fullHeight;
  7086. }
  7087. const skew = this.filmOffset;
  7088. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7089. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  7090. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7091. }
  7092. toJSON( meta ) {
  7093. const data = super.toJSON( meta );
  7094. data.object.fov = this.fov;
  7095. data.object.zoom = this.zoom;
  7096. data.object.near = this.near;
  7097. data.object.far = this.far;
  7098. data.object.focus = this.focus;
  7099. data.object.aspect = this.aspect;
  7100. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7101. data.object.filmGauge = this.filmGauge;
  7102. data.object.filmOffset = this.filmOffset;
  7103. return data;
  7104. }
  7105. }
  7106. const fov = - 90; // negative fov is not an error
  7107. const aspect = 1;
  7108. class CubeCamera extends Object3D {
  7109. constructor( near, far, renderTarget ) {
  7110. super();
  7111. this.type = 'CubeCamera';
  7112. this.renderTarget = renderTarget;
  7113. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7114. cameraPX.layers = this.layers;
  7115. cameraPX.up.set( 0, 1, 0 );
  7116. cameraPX.lookAt( 1, 0, 0 );
  7117. this.add( cameraPX );
  7118. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7119. cameraNX.layers = this.layers;
  7120. cameraNX.up.set( 0, 1, 0 );
  7121. cameraNX.lookAt( - 1, 0, 0 );
  7122. this.add( cameraNX );
  7123. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7124. cameraPY.layers = this.layers;
  7125. cameraPY.up.set( 0, 0, - 1 );
  7126. cameraPY.lookAt( 0, 1, 0 );
  7127. this.add( cameraPY );
  7128. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7129. cameraNY.layers = this.layers;
  7130. cameraNY.up.set( 0, 0, 1 );
  7131. cameraNY.lookAt( 0, - 1, 0 );
  7132. this.add( cameraNY );
  7133. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7134. cameraPZ.layers = this.layers;
  7135. cameraPZ.up.set( 0, 1, 0 );
  7136. cameraPZ.lookAt( 0, 0, 1 );
  7137. this.add( cameraPZ );
  7138. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7139. cameraNZ.layers = this.layers;
  7140. cameraNZ.up.set( 0, 1, 0 );
  7141. cameraNZ.lookAt( 0, 0, - 1 );
  7142. this.add( cameraNZ );
  7143. }
  7144. update( renderer, scene ) {
  7145. if ( this.parent === null ) this.updateMatrixWorld();
  7146. const renderTarget = this.renderTarget;
  7147. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7148. const currentRenderTarget = renderer.getRenderTarget();
  7149. const currentToneMapping = renderer.toneMapping;
  7150. const currentXrEnabled = renderer.xr.enabled;
  7151. renderer.toneMapping = NoToneMapping;
  7152. renderer.xr.enabled = false;
  7153. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7154. renderTarget.texture.generateMipmaps = false;
  7155. renderer.setRenderTarget( renderTarget, 0 );
  7156. renderer.render( scene, cameraPX );
  7157. renderer.setRenderTarget( renderTarget, 1 );
  7158. renderer.render( scene, cameraNX );
  7159. renderer.setRenderTarget( renderTarget, 2 );
  7160. renderer.render( scene, cameraPY );
  7161. renderer.setRenderTarget( renderTarget, 3 );
  7162. renderer.render( scene, cameraNY );
  7163. renderer.setRenderTarget( renderTarget, 4 );
  7164. renderer.render( scene, cameraPZ );
  7165. renderTarget.texture.generateMipmaps = generateMipmaps;
  7166. renderer.setRenderTarget( renderTarget, 5 );
  7167. renderer.render( scene, cameraNZ );
  7168. renderer.setRenderTarget( currentRenderTarget );
  7169. renderer.toneMapping = currentToneMapping;
  7170. renderer.xr.enabled = currentXrEnabled;
  7171. renderTarget.texture.needsPMREMUpdate = true;
  7172. }
  7173. }
  7174. class CubeTexture extends Texture {
  7175. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  7176. images = images !== undefined ? images : [];
  7177. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7178. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7179. this.isCubeTexture = true;
  7180. this.flipY = false;
  7181. }
  7182. get images() {
  7183. return this.image;
  7184. }
  7185. set images( value ) {
  7186. this.image = value;
  7187. }
  7188. }
  7189. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7190. constructor( size = 1, options = {} ) {
  7191. super( size, size, options );
  7192. this.isWebGLCubeRenderTarget = true;
  7193. const image = { width: size, height: size, depth: 1 };
  7194. const images = [ image, image, image, image, image, image ];
  7195. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  7196. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7197. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7198. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7199. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7200. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7201. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7202. this.texture.isRenderTargetTexture = true;
  7203. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7204. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7205. }
  7206. fromEquirectangularTexture( renderer, texture ) {
  7207. this.texture.type = texture.type;
  7208. this.texture.encoding = texture.encoding;
  7209. this.texture.generateMipmaps = texture.generateMipmaps;
  7210. this.texture.minFilter = texture.minFilter;
  7211. this.texture.magFilter = texture.magFilter;
  7212. const shader = {
  7213. uniforms: {
  7214. tEquirect: { value: null },
  7215. },
  7216. vertexShader: /* glsl */`
  7217. varying vec3 vWorldDirection;
  7218. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7219. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7220. }
  7221. void main() {
  7222. vWorldDirection = transformDirection( position, modelMatrix );
  7223. #include <begin_vertex>
  7224. #include <project_vertex>
  7225. }
  7226. `,
  7227. fragmentShader: /* glsl */`
  7228. uniform sampler2D tEquirect;
  7229. varying vec3 vWorldDirection;
  7230. #include <common>
  7231. void main() {
  7232. vec3 direction = normalize( vWorldDirection );
  7233. vec2 sampleUV = equirectUv( direction );
  7234. gl_FragColor = texture2D( tEquirect, sampleUV );
  7235. }
  7236. `
  7237. };
  7238. const geometry = new BoxGeometry( 5, 5, 5 );
  7239. const material = new ShaderMaterial( {
  7240. name: 'CubemapFromEquirect',
  7241. uniforms: cloneUniforms( shader.uniforms ),
  7242. vertexShader: shader.vertexShader,
  7243. fragmentShader: shader.fragmentShader,
  7244. side: BackSide,
  7245. blending: NoBlending
  7246. } );
  7247. material.uniforms.tEquirect.value = texture;
  7248. const mesh = new Mesh( geometry, material );
  7249. const currentMinFilter = texture.minFilter;
  7250. // Avoid blurred poles
  7251. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7252. const camera = new CubeCamera( 1, 10, this );
  7253. camera.update( renderer, mesh );
  7254. texture.minFilter = currentMinFilter;
  7255. mesh.geometry.dispose();
  7256. mesh.material.dispose();
  7257. return this;
  7258. }
  7259. clear( renderer, color, depth, stencil ) {
  7260. const currentRenderTarget = renderer.getRenderTarget();
  7261. for ( let i = 0; i < 6; i ++ ) {
  7262. renderer.setRenderTarget( this, i );
  7263. renderer.clear( color, depth, stencil );
  7264. }
  7265. renderer.setRenderTarget( currentRenderTarget );
  7266. }
  7267. }
  7268. const _vector1 = /*@__PURE__*/ new Vector3();
  7269. const _vector2 = /*@__PURE__*/ new Vector3();
  7270. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  7271. class Plane {
  7272. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  7273. this.isPlane = true;
  7274. // normal is assumed to be normalized
  7275. this.normal = normal;
  7276. this.constant = constant;
  7277. }
  7278. set( normal, constant ) {
  7279. this.normal.copy( normal );
  7280. this.constant = constant;
  7281. return this;
  7282. }
  7283. setComponents( x, y, z, w ) {
  7284. this.normal.set( x, y, z );
  7285. this.constant = w;
  7286. return this;
  7287. }
  7288. setFromNormalAndCoplanarPoint( normal, point ) {
  7289. this.normal.copy( normal );
  7290. this.constant = - point.dot( this.normal );
  7291. return this;
  7292. }
  7293. setFromCoplanarPoints( a, b, c ) {
  7294. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  7295. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7296. this.setFromNormalAndCoplanarPoint( normal, a );
  7297. return this;
  7298. }
  7299. copy( plane ) {
  7300. this.normal.copy( plane.normal );
  7301. this.constant = plane.constant;
  7302. return this;
  7303. }
  7304. normalize() {
  7305. // Note: will lead to a divide by zero if the plane is invalid.
  7306. const inverseNormalLength = 1.0 / this.normal.length();
  7307. this.normal.multiplyScalar( inverseNormalLength );
  7308. this.constant *= inverseNormalLength;
  7309. return this;
  7310. }
  7311. negate() {
  7312. this.constant *= - 1;
  7313. this.normal.negate();
  7314. return this;
  7315. }
  7316. distanceToPoint( point ) {
  7317. return this.normal.dot( point ) + this.constant;
  7318. }
  7319. distanceToSphere( sphere ) {
  7320. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7321. }
  7322. projectPoint( point, target ) {
  7323. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  7324. }
  7325. intersectLine( line, target ) {
  7326. const direction = line.delta( _vector1 );
  7327. const denominator = this.normal.dot( direction );
  7328. if ( denominator === 0 ) {
  7329. // line is coplanar, return origin
  7330. if ( this.distanceToPoint( line.start ) === 0 ) {
  7331. return target.copy( line.start );
  7332. }
  7333. // Unsure if this is the correct method to handle this case.
  7334. return null;
  7335. }
  7336. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7337. if ( t < 0 || t > 1 ) {
  7338. return null;
  7339. }
  7340. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  7341. }
  7342. intersectsLine( line ) {
  7343. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7344. const startSign = this.distanceToPoint( line.start );
  7345. const endSign = this.distanceToPoint( line.end );
  7346. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7347. }
  7348. intersectsBox( box ) {
  7349. return box.intersectsPlane( this );
  7350. }
  7351. intersectsSphere( sphere ) {
  7352. return sphere.intersectsPlane( this );
  7353. }
  7354. coplanarPoint( target ) {
  7355. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7356. }
  7357. applyMatrix4( matrix, optionalNormalMatrix ) {
  7358. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  7359. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  7360. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7361. this.constant = - referencePoint.dot( normal );
  7362. return this;
  7363. }
  7364. translate( offset ) {
  7365. this.constant -= offset.dot( this.normal );
  7366. return this;
  7367. }
  7368. equals( plane ) {
  7369. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7370. }
  7371. clone() {
  7372. return new this.constructor().copy( this );
  7373. }
  7374. }
  7375. const _sphere$2 = /*@__PURE__*/ new Sphere();
  7376. const _vector$7 = /*@__PURE__*/ new Vector3();
  7377. class Frustum {
  7378. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7379. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7380. }
  7381. set( p0, p1, p2, p3, p4, p5 ) {
  7382. const planes = this.planes;
  7383. planes[ 0 ].copy( p0 );
  7384. planes[ 1 ].copy( p1 );
  7385. planes[ 2 ].copy( p2 );
  7386. planes[ 3 ].copy( p3 );
  7387. planes[ 4 ].copy( p4 );
  7388. planes[ 5 ].copy( p5 );
  7389. return this;
  7390. }
  7391. copy( frustum ) {
  7392. const planes = this.planes;
  7393. for ( let i = 0; i < 6; i ++ ) {
  7394. planes[ i ].copy( frustum.planes[ i ] );
  7395. }
  7396. return this;
  7397. }
  7398. setFromProjectionMatrix( m ) {
  7399. const planes = this.planes;
  7400. const me = m.elements;
  7401. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7402. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7403. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7404. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7405. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7406. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7407. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7408. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7409. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7410. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7411. return this;
  7412. }
  7413. intersectsObject( object ) {
  7414. const geometry = object.geometry;
  7415. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7416. _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7417. return this.intersectsSphere( _sphere$2 );
  7418. }
  7419. intersectsSprite( sprite ) {
  7420. _sphere$2.center.set( 0, 0, 0 );
  7421. _sphere$2.radius = 0.7071067811865476;
  7422. _sphere$2.applyMatrix4( sprite.matrixWorld );
  7423. return this.intersectsSphere( _sphere$2 );
  7424. }
  7425. intersectsSphere( sphere ) {
  7426. const planes = this.planes;
  7427. const center = sphere.center;
  7428. const negRadius = - sphere.radius;
  7429. for ( let i = 0; i < 6; i ++ ) {
  7430. const distance = planes[ i ].distanceToPoint( center );
  7431. if ( distance < negRadius ) {
  7432. return false;
  7433. }
  7434. }
  7435. return true;
  7436. }
  7437. intersectsBox( box ) {
  7438. const planes = this.planes;
  7439. for ( let i = 0; i < 6; i ++ ) {
  7440. const plane = planes[ i ];
  7441. // corner at max distance
  7442. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7443. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7444. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7445. if ( plane.distanceToPoint( _vector$7 ) < 0 ) {
  7446. return false;
  7447. }
  7448. }
  7449. return true;
  7450. }
  7451. containsPoint( point ) {
  7452. const planes = this.planes;
  7453. for ( let i = 0; i < 6; i ++ ) {
  7454. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7455. return false;
  7456. }
  7457. }
  7458. return true;
  7459. }
  7460. clone() {
  7461. return new this.constructor().copy( this );
  7462. }
  7463. }
  7464. function WebGLAnimation() {
  7465. let context = null;
  7466. let isAnimating = false;
  7467. let animationLoop = null;
  7468. let requestId = null;
  7469. function onAnimationFrame( time, frame ) {
  7470. animationLoop( time, frame );
  7471. requestId = context.requestAnimationFrame( onAnimationFrame );
  7472. }
  7473. return {
  7474. start: function () {
  7475. if ( isAnimating === true ) return;
  7476. if ( animationLoop === null ) return;
  7477. requestId = context.requestAnimationFrame( onAnimationFrame );
  7478. isAnimating = true;
  7479. },
  7480. stop: function () {
  7481. context.cancelAnimationFrame( requestId );
  7482. isAnimating = false;
  7483. },
  7484. setAnimationLoop: function ( callback ) {
  7485. animationLoop = callback;
  7486. },
  7487. setContext: function ( value ) {
  7488. context = value;
  7489. }
  7490. };
  7491. }
  7492. function WebGLAttributes( gl, capabilities ) {
  7493. const isWebGL2 = capabilities.isWebGL2;
  7494. const buffers = new WeakMap();
  7495. function createBuffer( attribute, bufferType ) {
  7496. const array = attribute.array;
  7497. const usage = attribute.usage;
  7498. const buffer = gl.createBuffer();
  7499. gl.bindBuffer( bufferType, buffer );
  7500. gl.bufferData( bufferType, array, usage );
  7501. attribute.onUploadCallback();
  7502. let type;
  7503. if ( array instanceof Float32Array ) {
  7504. type = 5126;
  7505. } else if ( array instanceof Uint16Array ) {
  7506. if ( attribute.isFloat16BufferAttribute ) {
  7507. if ( isWebGL2 ) {
  7508. type = 5131;
  7509. } else {
  7510. throw new Error( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  7511. }
  7512. } else {
  7513. type = 5123;
  7514. }
  7515. } else if ( array instanceof Int16Array ) {
  7516. type = 5122;
  7517. } else if ( array instanceof Uint32Array ) {
  7518. type = 5125;
  7519. } else if ( array instanceof Int32Array ) {
  7520. type = 5124;
  7521. } else if ( array instanceof Int8Array ) {
  7522. type = 5120;
  7523. } else if ( array instanceof Uint8Array ) {
  7524. type = 5121;
  7525. } else if ( array instanceof Uint8ClampedArray ) {
  7526. type = 5121;
  7527. } else {
  7528. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  7529. }
  7530. return {
  7531. buffer: buffer,
  7532. type: type,
  7533. bytesPerElement: array.BYTES_PER_ELEMENT,
  7534. version: attribute.version
  7535. };
  7536. }
  7537. function updateBuffer( buffer, attribute, bufferType ) {
  7538. const array = attribute.array;
  7539. const updateRange = attribute.updateRange;
  7540. gl.bindBuffer( bufferType, buffer );
  7541. if ( updateRange.count === - 1 ) {
  7542. // Not using update ranges
  7543. gl.bufferSubData( bufferType, 0, array );
  7544. } else {
  7545. if ( isWebGL2 ) {
  7546. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7547. array, updateRange.offset, updateRange.count );
  7548. } else {
  7549. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7550. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  7551. }
  7552. updateRange.count = - 1; // reset range
  7553. }
  7554. attribute.onUploadCallback();
  7555. }
  7556. //
  7557. function get( attribute ) {
  7558. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7559. return buffers.get( attribute );
  7560. }
  7561. function remove( attribute ) {
  7562. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7563. const data = buffers.get( attribute );
  7564. if ( data ) {
  7565. gl.deleteBuffer( data.buffer );
  7566. buffers.delete( attribute );
  7567. }
  7568. }
  7569. function update( attribute, bufferType ) {
  7570. if ( attribute.isGLBufferAttribute ) {
  7571. const cached = buffers.get( attribute );
  7572. if ( ! cached || cached.version < attribute.version ) {
  7573. buffers.set( attribute, {
  7574. buffer: attribute.buffer,
  7575. type: attribute.type,
  7576. bytesPerElement: attribute.elementSize,
  7577. version: attribute.version
  7578. } );
  7579. }
  7580. return;
  7581. }
  7582. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7583. const data = buffers.get( attribute );
  7584. if ( data === undefined ) {
  7585. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  7586. } else if ( data.version < attribute.version ) {
  7587. updateBuffer( data.buffer, attribute, bufferType );
  7588. data.version = attribute.version;
  7589. }
  7590. }
  7591. return {
  7592. get: get,
  7593. remove: remove,
  7594. update: update
  7595. };
  7596. }
  7597. class PlaneGeometry extends BufferGeometry {
  7598. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  7599. super();
  7600. this.type = 'PlaneGeometry';
  7601. this.parameters = {
  7602. width: width,
  7603. height: height,
  7604. widthSegments: widthSegments,
  7605. heightSegments: heightSegments
  7606. };
  7607. const width_half = width / 2;
  7608. const height_half = height / 2;
  7609. const gridX = Math.floor( widthSegments );
  7610. const gridY = Math.floor( heightSegments );
  7611. const gridX1 = gridX + 1;
  7612. const gridY1 = gridY + 1;
  7613. const segment_width = width / gridX;
  7614. const segment_height = height / gridY;
  7615. //
  7616. const indices = [];
  7617. const vertices = [];
  7618. const normals = [];
  7619. const uvs = [];
  7620. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7621. const y = iy * segment_height - height_half;
  7622. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7623. const x = ix * segment_width - width_half;
  7624. vertices.push( x, - y, 0 );
  7625. normals.push( 0, 0, 1 );
  7626. uvs.push( ix / gridX );
  7627. uvs.push( 1 - ( iy / gridY ) );
  7628. }
  7629. }
  7630. for ( let iy = 0; iy < gridY; iy ++ ) {
  7631. for ( let ix = 0; ix < gridX; ix ++ ) {
  7632. const a = ix + gridX1 * iy;
  7633. const b = ix + gridX1 * ( iy + 1 );
  7634. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  7635. const d = ( ix + 1 ) + gridX1 * iy;
  7636. indices.push( a, b, d );
  7637. indices.push( b, c, d );
  7638. }
  7639. }
  7640. this.setIndex( indices );
  7641. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7642. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7643. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7644. }
  7645. static fromJSON( data ) {
  7646. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  7647. }
  7648. }
  7649. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7650. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7651. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  7652. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  7653. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).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";
  7654. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7655. var begin_vertex = "vec3 transformed = vec3( position );";
  7656. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7657. var bsdfs = "vec3 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}\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}\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float 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\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\n#ifdef USE_IRIDESCENCE\n\tvec3 BRDF_GGX_Iridescence( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float iridescence, const in vec3 iridescenceFresnel, const in float roughness ) {\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 = mix( F_Schlick( f0, f90, dotVH ), iridescenceFresnel, iridescence );\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\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}\nfloat 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}\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";
  7658. 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";
  7659. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + 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";
  7660. 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";
  7661. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7662. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7663. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7664. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7665. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7666. 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";
  7667. 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";
  7668. 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}";
  7669. 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";
  7670. 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";
  7671. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7672. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7673. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7674. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7675. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7676. 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}";
  7677. 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";
  7678. 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";
  7679. 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";
  7680. 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";
  7681. 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";
  7682. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  7683. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  7684. 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";
  7685. 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";
  7686. 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}";
  7687. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  7688. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7689. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  7690. 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";
  7691. 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 ( PHYSICALLY_CORRECT_LIGHTS )\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#else\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#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";
  7692. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#if defined( 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#if defined( 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#endif";
  7693. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7694. 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";
  7695. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7696. 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";
  7697. 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 SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vUv ).rgb;\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, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).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, vUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vUv ).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_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif";
  7698. 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};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\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( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\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\t#ifdef USE_IRIDESCENCE\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX_Iridescence( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness );\n\t#else\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\t#endif\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}";
  7699. 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";
  7700. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\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\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
  7701. 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";
  7702. 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";
  7703. 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";
  7704. 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";
  7705. 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";
  7706. var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif";
  7707. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7708. var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\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";
  7709. var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7710. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7711. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7712. 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";
  7713. 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";
  7714. 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";
  7715. 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";
  7716. 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 = normal * faceDirection;\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * faceDirection;\n\t\t\tbitangent = bitangent * faceDirection;\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";
  7717. var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).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( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( - vViewPosition, normal, mapN, faceDirection );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif";
  7718. 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";
  7719. 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";
  7720. 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";
  7721. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.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 : faceDirection * inversesqrt( det );\n\t\treturn normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\t}\n#endif";
  7722. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7723. var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN, faceDirection );\n\t#endif\n#endif";
  7724. var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";
  7725. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  7726. var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  7727. 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 linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( 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 invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}";
  7728. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7729. 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;";
  7730. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7731. 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";
  7732. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7733. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7734. var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n uniform 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";
  7735. var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n varying 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";
  7736. 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";
  7737. 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}";
  7738. 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";
  7739. 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";
  7740. 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";
  7741. 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";
  7742. var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
  7743. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7744. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7745. 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 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; }";
  7746. 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, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = 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, transmission.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, material.transmission );\n#endif";
  7747. 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\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 framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef texture2DLodEXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\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 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif";
  7748. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7749. var uv_pars_vertex = "#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif";
  7750. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7751. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7752. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif";
  7753. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7754. 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";
  7755. 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}";
  7756. const fragment$h = "uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7757. 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}";
  7758. 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}";
  7759. 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}";
  7760. 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}";
  7761. 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}";
  7762. 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}";
  7763. 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}";
  7764. 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}";
  7765. 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}";
  7766. 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}";
  7767. const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\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>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\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}";
  7768. 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 <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 <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}";
  7769. const vertex$a = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_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 <uv2_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}";
  7770. 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 <uv2_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, vUv2 );\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}";
  7771. const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_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 <uv2_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}";
  7772. 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 <uv2_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}";
  7773. 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}";
  7774. 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}";
  7775. const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\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( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  7776. const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\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}";
  7777. const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_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 <uv2_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}";
  7778. 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 <uv2_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}";
  7779. 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 <uv2_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 <uv2_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}";
  7780. const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define 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 SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARCOLORMAP\n\t\tuniform sampler2D specularColorMap;\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_SHEENCOLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\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 <uv2_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 <bsdfs>\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}";
  7781. const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_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 <uv2_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}";
  7782. 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 <uv2_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}";
  7783. 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>\nvoid main() {\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}";
  7784. 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}";
  7785. const vertex$2 = "#include <common>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_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 <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7786. 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 <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\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}";
  7787. 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}";
  7788. 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}";
  7789. const ShaderChunk = {
  7790. alphamap_fragment: alphamap_fragment,
  7791. alphamap_pars_fragment: alphamap_pars_fragment,
  7792. alphatest_fragment: alphatest_fragment,
  7793. alphatest_pars_fragment: alphatest_pars_fragment,
  7794. aomap_fragment: aomap_fragment,
  7795. aomap_pars_fragment: aomap_pars_fragment,
  7796. begin_vertex: begin_vertex,
  7797. beginnormal_vertex: beginnormal_vertex,
  7798. bsdfs: bsdfs,
  7799. iridescence_fragment: iridescence_fragment,
  7800. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7801. clipping_planes_fragment: clipping_planes_fragment,
  7802. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7803. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7804. clipping_planes_vertex: clipping_planes_vertex,
  7805. color_fragment: color_fragment,
  7806. color_pars_fragment: color_pars_fragment,
  7807. color_pars_vertex: color_pars_vertex,
  7808. color_vertex: color_vertex,
  7809. common: common,
  7810. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7811. defaultnormal_vertex: defaultnormal_vertex,
  7812. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7813. displacementmap_vertex: displacementmap_vertex,
  7814. emissivemap_fragment: emissivemap_fragment,
  7815. emissivemap_pars_fragment: emissivemap_pars_fragment,
  7816. encodings_fragment: encodings_fragment,
  7817. encodings_pars_fragment: encodings_pars_fragment,
  7818. envmap_fragment: envmap_fragment,
  7819. envmap_common_pars_fragment: envmap_common_pars_fragment,
  7820. envmap_pars_fragment: envmap_pars_fragment,
  7821. envmap_pars_vertex: envmap_pars_vertex,
  7822. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  7823. envmap_vertex: envmap_vertex,
  7824. fog_vertex: fog_vertex,
  7825. fog_pars_vertex: fog_pars_vertex,
  7826. fog_fragment: fog_fragment,
  7827. fog_pars_fragment: fog_pars_fragment,
  7828. gradientmap_pars_fragment: gradientmap_pars_fragment,
  7829. lightmap_fragment: lightmap_fragment,
  7830. lightmap_pars_fragment: lightmap_pars_fragment,
  7831. lights_lambert_fragment: lights_lambert_fragment,
  7832. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  7833. lights_pars_begin: lights_pars_begin,
  7834. lights_toon_fragment: lights_toon_fragment,
  7835. lights_toon_pars_fragment: lights_toon_pars_fragment,
  7836. lights_phong_fragment: lights_phong_fragment,
  7837. lights_phong_pars_fragment: lights_phong_pars_fragment,
  7838. lights_physical_fragment: lights_physical_fragment,
  7839. lights_physical_pars_fragment: lights_physical_pars_fragment,
  7840. lights_fragment_begin: lights_fragment_begin,
  7841. lights_fragment_maps: lights_fragment_maps,
  7842. lights_fragment_end: lights_fragment_end,
  7843. logdepthbuf_fragment: logdepthbuf_fragment,
  7844. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  7845. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  7846. logdepthbuf_vertex: logdepthbuf_vertex,
  7847. map_fragment: map_fragment,
  7848. map_pars_fragment: map_pars_fragment,
  7849. map_particle_fragment: map_particle_fragment,
  7850. map_particle_pars_fragment: map_particle_pars_fragment,
  7851. metalnessmap_fragment: metalnessmap_fragment,
  7852. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  7853. morphcolor_vertex: morphcolor_vertex,
  7854. morphnormal_vertex: morphnormal_vertex,
  7855. morphtarget_pars_vertex: morphtarget_pars_vertex,
  7856. morphtarget_vertex: morphtarget_vertex,
  7857. normal_fragment_begin: normal_fragment_begin,
  7858. normal_fragment_maps: normal_fragment_maps,
  7859. normal_pars_fragment: normal_pars_fragment,
  7860. normal_pars_vertex: normal_pars_vertex,
  7861. normal_vertex: normal_vertex,
  7862. normalmap_pars_fragment: normalmap_pars_fragment,
  7863. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  7864. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  7865. clearcoat_pars_fragment: clearcoat_pars_fragment,
  7866. iridescence_pars_fragment: iridescence_pars_fragment,
  7867. output_fragment: output_fragment,
  7868. packing: packing,
  7869. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  7870. project_vertex: project_vertex,
  7871. dithering_fragment: dithering_fragment,
  7872. dithering_pars_fragment: dithering_pars_fragment,
  7873. roughnessmap_fragment: roughnessmap_fragment,
  7874. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  7875. shadowmap_pars_fragment: shadowmap_pars_fragment,
  7876. shadowmap_pars_vertex: shadowmap_pars_vertex,
  7877. shadowmap_vertex: shadowmap_vertex,
  7878. shadowmask_pars_fragment: shadowmask_pars_fragment,
  7879. skinbase_vertex: skinbase_vertex,
  7880. skinning_pars_vertex: skinning_pars_vertex,
  7881. skinning_vertex: skinning_vertex,
  7882. skinnormal_vertex: skinnormal_vertex,
  7883. specularmap_fragment: specularmap_fragment,
  7884. specularmap_pars_fragment: specularmap_pars_fragment,
  7885. tonemapping_fragment: tonemapping_fragment,
  7886. tonemapping_pars_fragment: tonemapping_pars_fragment,
  7887. transmission_fragment: transmission_fragment,
  7888. transmission_pars_fragment: transmission_pars_fragment,
  7889. uv_pars_fragment: uv_pars_fragment,
  7890. uv_pars_vertex: uv_pars_vertex,
  7891. uv_vertex: uv_vertex,
  7892. uv2_pars_fragment: uv2_pars_fragment,
  7893. uv2_pars_vertex: uv2_pars_vertex,
  7894. uv2_vertex: uv2_vertex,
  7895. worldpos_vertex: worldpos_vertex,
  7896. background_vert: vertex$h,
  7897. background_frag: fragment$h,
  7898. backgroundCube_vert: vertex$g,
  7899. backgroundCube_frag: fragment$g,
  7900. cube_vert: vertex$f,
  7901. cube_frag: fragment$f,
  7902. depth_vert: vertex$e,
  7903. depth_frag: fragment$e,
  7904. distanceRGBA_vert: vertex$d,
  7905. distanceRGBA_frag: fragment$d,
  7906. equirect_vert: vertex$c,
  7907. equirect_frag: fragment$c,
  7908. linedashed_vert: vertex$b,
  7909. linedashed_frag: fragment$b,
  7910. meshbasic_vert: vertex$a,
  7911. meshbasic_frag: fragment$a,
  7912. meshlambert_vert: vertex$9,
  7913. meshlambert_frag: fragment$9,
  7914. meshmatcap_vert: vertex$8,
  7915. meshmatcap_frag: fragment$8,
  7916. meshnormal_vert: vertex$7,
  7917. meshnormal_frag: fragment$7,
  7918. meshphong_vert: vertex$6,
  7919. meshphong_frag: fragment$6,
  7920. meshphysical_vert: vertex$5,
  7921. meshphysical_frag: fragment$5,
  7922. meshtoon_vert: vertex$4,
  7923. meshtoon_frag: fragment$4,
  7924. points_vert: vertex$3,
  7925. points_frag: fragment$3,
  7926. shadow_vert: vertex$2,
  7927. shadow_frag: fragment$2,
  7928. sprite_vert: vertex$1,
  7929. sprite_frag: fragment$1
  7930. };
  7931. /**
  7932. * Uniforms library for shared webgl shaders
  7933. */
  7934. const UniformsLib = {
  7935. common: {
  7936. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  7937. opacity: { value: 1.0 },
  7938. map: { value: null },
  7939. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  7940. uv2Transform: { value: /*@__PURE__*/ new Matrix3() },
  7941. alphaMap: { value: null },
  7942. alphaTest: { value: 0 }
  7943. },
  7944. specularmap: {
  7945. specularMap: { value: null },
  7946. },
  7947. envmap: {
  7948. envMap: { value: null },
  7949. flipEnvMap: { value: - 1 },
  7950. reflectivity: { value: 1.0 }, // basic, lambert, phong
  7951. ior: { value: 1.5 }, // physical
  7952. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  7953. },
  7954. aomap: {
  7955. aoMap: { value: null },
  7956. aoMapIntensity: { value: 1 }
  7957. },
  7958. lightmap: {
  7959. lightMap: { value: null },
  7960. lightMapIntensity: { value: 1 }
  7961. },
  7962. emissivemap: {
  7963. emissiveMap: { value: null }
  7964. },
  7965. bumpmap: {
  7966. bumpMap: { value: null },
  7967. bumpScale: { value: 1 }
  7968. },
  7969. normalmap: {
  7970. normalMap: { value: null },
  7971. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  7972. },
  7973. displacementmap: {
  7974. displacementMap: { value: null },
  7975. displacementScale: { value: 1 },
  7976. displacementBias: { value: 0 }
  7977. },
  7978. roughnessmap: {
  7979. roughnessMap: { value: null }
  7980. },
  7981. metalnessmap: {
  7982. metalnessMap: { value: null }
  7983. },
  7984. gradientmap: {
  7985. gradientMap: { value: null }
  7986. },
  7987. fog: {
  7988. fogDensity: { value: 0.00025 },
  7989. fogNear: { value: 1 },
  7990. fogFar: { value: 2000 },
  7991. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  7992. },
  7993. lights: {
  7994. ambientLightColor: { value: [] },
  7995. lightProbe: { value: [] },
  7996. directionalLights: { value: [], properties: {
  7997. direction: {},
  7998. color: {}
  7999. } },
  8000. directionalLightShadows: { value: [], properties: {
  8001. shadowBias: {},
  8002. shadowNormalBias: {},
  8003. shadowRadius: {},
  8004. shadowMapSize: {}
  8005. } },
  8006. directionalShadowMap: { value: [] },
  8007. directionalShadowMatrix: { value: [] },
  8008. spotLights: { value: [], properties: {
  8009. color: {},
  8010. position: {},
  8011. direction: {},
  8012. distance: {},
  8013. coneCos: {},
  8014. penumbraCos: {},
  8015. decay: {}
  8016. } },
  8017. spotLightShadows: { value: [], properties: {
  8018. shadowBias: {},
  8019. shadowNormalBias: {},
  8020. shadowRadius: {},
  8021. shadowMapSize: {}
  8022. } },
  8023. spotLightMap: { value: [] },
  8024. spotShadowMap: { value: [] },
  8025. spotLightMatrix: { value: [] },
  8026. pointLights: { value: [], properties: {
  8027. color: {},
  8028. position: {},
  8029. decay: {},
  8030. distance: {}
  8031. } },
  8032. pointLightShadows: { value: [], properties: {
  8033. shadowBias: {},
  8034. shadowNormalBias: {},
  8035. shadowRadius: {},
  8036. shadowMapSize: {},
  8037. shadowCameraNear: {},
  8038. shadowCameraFar: {}
  8039. } },
  8040. pointShadowMap: { value: [] },
  8041. pointShadowMatrix: { value: [] },
  8042. hemisphereLights: { value: [], properties: {
  8043. direction: {},
  8044. skyColor: {},
  8045. groundColor: {}
  8046. } },
  8047. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8048. rectAreaLights: { value: [], properties: {
  8049. color: {},
  8050. position: {},
  8051. width: {},
  8052. height: {}
  8053. } },
  8054. ltc_1: { value: null },
  8055. ltc_2: { value: null }
  8056. },
  8057. points: {
  8058. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8059. opacity: { value: 1.0 },
  8060. size: { value: 1.0 },
  8061. scale: { value: 1.0 },
  8062. map: { value: null },
  8063. alphaMap: { value: null },
  8064. alphaTest: { value: 0 },
  8065. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8066. },
  8067. sprite: {
  8068. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8069. opacity: { value: 1.0 },
  8070. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  8071. rotation: { value: 0.0 },
  8072. map: { value: null },
  8073. alphaMap: { value: null },
  8074. alphaTest: { value: 0 },
  8075. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8076. }
  8077. };
  8078. const ShaderLib = {
  8079. basic: {
  8080. uniforms: /*@__PURE__*/ mergeUniforms( [
  8081. UniformsLib.common,
  8082. UniformsLib.specularmap,
  8083. UniformsLib.envmap,
  8084. UniformsLib.aomap,
  8085. UniformsLib.lightmap,
  8086. UniformsLib.fog
  8087. ] ),
  8088. vertexShader: ShaderChunk.meshbasic_vert,
  8089. fragmentShader: ShaderChunk.meshbasic_frag
  8090. },
  8091. lambert: {
  8092. uniforms: /*@__PURE__*/ mergeUniforms( [
  8093. UniformsLib.common,
  8094. UniformsLib.specularmap,
  8095. UniformsLib.envmap,
  8096. UniformsLib.aomap,
  8097. UniformsLib.lightmap,
  8098. UniformsLib.emissivemap,
  8099. UniformsLib.bumpmap,
  8100. UniformsLib.normalmap,
  8101. UniformsLib.displacementmap,
  8102. UniformsLib.fog,
  8103. UniformsLib.lights,
  8104. {
  8105. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8106. }
  8107. ] ),
  8108. vertexShader: ShaderChunk.meshlambert_vert,
  8109. fragmentShader: ShaderChunk.meshlambert_frag
  8110. },
  8111. phong: {
  8112. uniforms: /*@__PURE__*/ mergeUniforms( [
  8113. UniformsLib.common,
  8114. UniformsLib.specularmap,
  8115. UniformsLib.envmap,
  8116. UniformsLib.aomap,
  8117. UniformsLib.lightmap,
  8118. UniformsLib.emissivemap,
  8119. UniformsLib.bumpmap,
  8120. UniformsLib.normalmap,
  8121. UniformsLib.displacementmap,
  8122. UniformsLib.fog,
  8123. UniformsLib.lights,
  8124. {
  8125. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8126. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  8127. shininess: { value: 30 }
  8128. }
  8129. ] ),
  8130. vertexShader: ShaderChunk.meshphong_vert,
  8131. fragmentShader: ShaderChunk.meshphong_frag
  8132. },
  8133. standard: {
  8134. uniforms: /*@__PURE__*/ mergeUniforms( [
  8135. UniformsLib.common,
  8136. UniformsLib.envmap,
  8137. UniformsLib.aomap,
  8138. UniformsLib.lightmap,
  8139. UniformsLib.emissivemap,
  8140. UniformsLib.bumpmap,
  8141. UniformsLib.normalmap,
  8142. UniformsLib.displacementmap,
  8143. UniformsLib.roughnessmap,
  8144. UniformsLib.metalnessmap,
  8145. UniformsLib.fog,
  8146. UniformsLib.lights,
  8147. {
  8148. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8149. roughness: { value: 1.0 },
  8150. metalness: { value: 0.0 },
  8151. envMapIntensity: { value: 1 } // temporary
  8152. }
  8153. ] ),
  8154. vertexShader: ShaderChunk.meshphysical_vert,
  8155. fragmentShader: ShaderChunk.meshphysical_frag
  8156. },
  8157. toon: {
  8158. uniforms: /*@__PURE__*/ mergeUniforms( [
  8159. UniformsLib.common,
  8160. UniformsLib.aomap,
  8161. UniformsLib.lightmap,
  8162. UniformsLib.emissivemap,
  8163. UniformsLib.bumpmap,
  8164. UniformsLib.normalmap,
  8165. UniformsLib.displacementmap,
  8166. UniformsLib.gradientmap,
  8167. UniformsLib.fog,
  8168. UniformsLib.lights,
  8169. {
  8170. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8171. }
  8172. ] ),
  8173. vertexShader: ShaderChunk.meshtoon_vert,
  8174. fragmentShader: ShaderChunk.meshtoon_frag
  8175. },
  8176. matcap: {
  8177. uniforms: /*@__PURE__*/ mergeUniforms( [
  8178. UniformsLib.common,
  8179. UniformsLib.bumpmap,
  8180. UniformsLib.normalmap,
  8181. UniformsLib.displacementmap,
  8182. UniformsLib.fog,
  8183. {
  8184. matcap: { value: null }
  8185. }
  8186. ] ),
  8187. vertexShader: ShaderChunk.meshmatcap_vert,
  8188. fragmentShader: ShaderChunk.meshmatcap_frag
  8189. },
  8190. points: {
  8191. uniforms: /*@__PURE__*/ mergeUniforms( [
  8192. UniformsLib.points,
  8193. UniformsLib.fog
  8194. ] ),
  8195. vertexShader: ShaderChunk.points_vert,
  8196. fragmentShader: ShaderChunk.points_frag
  8197. },
  8198. dashed: {
  8199. uniforms: /*@__PURE__*/ mergeUniforms( [
  8200. UniformsLib.common,
  8201. UniformsLib.fog,
  8202. {
  8203. scale: { value: 1 },
  8204. dashSize: { value: 1 },
  8205. totalSize: { value: 2 }
  8206. }
  8207. ] ),
  8208. vertexShader: ShaderChunk.linedashed_vert,
  8209. fragmentShader: ShaderChunk.linedashed_frag
  8210. },
  8211. depth: {
  8212. uniforms: /*@__PURE__*/ mergeUniforms( [
  8213. UniformsLib.common,
  8214. UniformsLib.displacementmap
  8215. ] ),
  8216. vertexShader: ShaderChunk.depth_vert,
  8217. fragmentShader: ShaderChunk.depth_frag
  8218. },
  8219. normal: {
  8220. uniforms: /*@__PURE__*/ mergeUniforms( [
  8221. UniformsLib.common,
  8222. UniformsLib.bumpmap,
  8223. UniformsLib.normalmap,
  8224. UniformsLib.displacementmap,
  8225. {
  8226. opacity: { value: 1.0 }
  8227. }
  8228. ] ),
  8229. vertexShader: ShaderChunk.meshnormal_vert,
  8230. fragmentShader: ShaderChunk.meshnormal_frag
  8231. },
  8232. sprite: {
  8233. uniforms: /*@__PURE__*/ mergeUniforms( [
  8234. UniformsLib.sprite,
  8235. UniformsLib.fog
  8236. ] ),
  8237. vertexShader: ShaderChunk.sprite_vert,
  8238. fragmentShader: ShaderChunk.sprite_frag
  8239. },
  8240. background: {
  8241. uniforms: {
  8242. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  8243. t2D: { value: null },
  8244. backgroundIntensity: { value: 1 }
  8245. },
  8246. vertexShader: ShaderChunk.background_vert,
  8247. fragmentShader: ShaderChunk.background_frag
  8248. },
  8249. backgroundCube: {
  8250. uniforms: {
  8251. envMap: { value: null },
  8252. flipEnvMap: { value: - 1 },
  8253. backgroundBlurriness: { value: 0 },
  8254. backgroundIntensity: { value: 1 }
  8255. },
  8256. vertexShader: ShaderChunk.backgroundCube_vert,
  8257. fragmentShader: ShaderChunk.backgroundCube_frag
  8258. },
  8259. cube: {
  8260. uniforms: {
  8261. tCube: { value: null },
  8262. tFlip: { value: - 1 },
  8263. opacity: { value: 1.0 }
  8264. },
  8265. vertexShader: ShaderChunk.cube_vert,
  8266. fragmentShader: ShaderChunk.cube_frag
  8267. },
  8268. equirect: {
  8269. uniforms: {
  8270. tEquirect: { value: null },
  8271. },
  8272. vertexShader: ShaderChunk.equirect_vert,
  8273. fragmentShader: ShaderChunk.equirect_frag
  8274. },
  8275. distanceRGBA: {
  8276. uniforms: /*@__PURE__*/ mergeUniforms( [
  8277. UniformsLib.common,
  8278. UniformsLib.displacementmap,
  8279. {
  8280. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  8281. nearDistance: { value: 1 },
  8282. farDistance: { value: 1000 }
  8283. }
  8284. ] ),
  8285. vertexShader: ShaderChunk.distanceRGBA_vert,
  8286. fragmentShader: ShaderChunk.distanceRGBA_frag
  8287. },
  8288. shadow: {
  8289. uniforms: /*@__PURE__*/ mergeUniforms( [
  8290. UniformsLib.lights,
  8291. UniformsLib.fog,
  8292. {
  8293. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  8294. opacity: { value: 1.0 }
  8295. },
  8296. ] ),
  8297. vertexShader: ShaderChunk.shadow_vert,
  8298. fragmentShader: ShaderChunk.shadow_frag
  8299. }
  8300. };
  8301. ShaderLib.physical = {
  8302. uniforms: /*@__PURE__*/ mergeUniforms( [
  8303. ShaderLib.standard.uniforms,
  8304. {
  8305. clearcoat: { value: 0 },
  8306. clearcoatMap: { value: null },
  8307. clearcoatRoughness: { value: 0 },
  8308. clearcoatRoughnessMap: { value: null },
  8309. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  8310. clearcoatNormalMap: { value: null },
  8311. iridescence: { value: 0 },
  8312. iridescenceMap: { value: null },
  8313. iridescenceIOR: { value: 1.3 },
  8314. iridescenceThicknessMinimum: { value: 100 },
  8315. iridescenceThicknessMaximum: { value: 400 },
  8316. iridescenceThicknessMap: { value: null },
  8317. sheen: { value: 0 },
  8318. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8319. sheenColorMap: { value: null },
  8320. sheenRoughness: { value: 1 },
  8321. sheenRoughnessMap: { value: null },
  8322. transmission: { value: 0 },
  8323. transmissionMap: { value: null },
  8324. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  8325. transmissionSamplerMap: { value: null },
  8326. thickness: { value: 0 },
  8327. thicknessMap: { value: null },
  8328. attenuationDistance: { value: 0 },
  8329. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8330. specularIntensity: { value: 1 },
  8331. specularIntensityMap: { value: null },
  8332. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  8333. specularColorMap: { value: null },
  8334. }
  8335. ] ),
  8336. vertexShader: ShaderChunk.meshphysical_vert,
  8337. fragmentShader: ShaderChunk.meshphysical_frag
  8338. };
  8339. const _rgb = { r: 0, b: 0, g: 0 };
  8340. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  8341. const clearColor = new Color( 0x000000 );
  8342. let clearAlpha = alpha === true ? 0 : 1;
  8343. let planeMesh;
  8344. let boxMesh;
  8345. let currentBackground = null;
  8346. let currentBackgroundVersion = 0;
  8347. let currentTonemapping = null;
  8348. function render( renderList, scene ) {
  8349. let forceClear = false;
  8350. let background = scene.isScene === true ? scene.background : null;
  8351. if ( background && background.isTexture ) {
  8352. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  8353. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  8354. }
  8355. // Ignore background in AR
  8356. // TODO: Reconsider this.
  8357. const xr = renderer.xr;
  8358. const session = xr.getSession && xr.getSession();
  8359. if ( session && session.environmentBlendMode === 'additive' ) {
  8360. background = null;
  8361. }
  8362. if ( background === null ) {
  8363. setClear( clearColor, clearAlpha );
  8364. } else if ( background && background.isColor ) {
  8365. setClear( background, 1 );
  8366. forceClear = true;
  8367. }
  8368. if ( renderer.autoClear || forceClear ) {
  8369. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8370. }
  8371. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8372. if ( boxMesh === undefined ) {
  8373. boxMesh = new Mesh(
  8374. new BoxGeometry( 1, 1, 1 ),
  8375. new ShaderMaterial( {
  8376. name: 'BackgroundCubeMaterial',
  8377. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  8378. vertexShader: ShaderLib.backgroundCube.vertexShader,
  8379. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  8380. side: BackSide,
  8381. depthTest: false,
  8382. depthWrite: false,
  8383. fog: false
  8384. } )
  8385. );
  8386. boxMesh.geometry.deleteAttribute( 'normal' );
  8387. boxMesh.geometry.deleteAttribute( 'uv' );
  8388. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8389. this.matrixWorld.copyPosition( camera.matrixWorld );
  8390. };
  8391. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  8392. Object.defineProperty( boxMesh.material, 'envMap', {
  8393. get: function () {
  8394. return this.uniforms.envMap.value;
  8395. }
  8396. } );
  8397. objects.update( boxMesh );
  8398. }
  8399. boxMesh.material.uniforms.envMap.value = background;
  8400. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  8401. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  8402. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8403. boxMesh.material.toneMapped = ( background.encoding === sRGBEncoding ) ? false : true;
  8404. if ( currentBackground !== background ||
  8405. currentBackgroundVersion !== background.version ||
  8406. currentTonemapping !== renderer.toneMapping ) {
  8407. boxMesh.material.needsUpdate = true;
  8408. currentBackground = background;
  8409. currentBackgroundVersion = background.version;
  8410. currentTonemapping = renderer.toneMapping;
  8411. }
  8412. boxMesh.layers.enableAll();
  8413. // push to the pre-sorted opaque render list
  8414. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  8415. } else if ( background && background.isTexture ) {
  8416. if ( planeMesh === undefined ) {
  8417. planeMesh = new Mesh(
  8418. new PlaneGeometry( 2, 2 ),
  8419. new ShaderMaterial( {
  8420. name: 'BackgroundMaterial',
  8421. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  8422. vertexShader: ShaderLib.background.vertexShader,
  8423. fragmentShader: ShaderLib.background.fragmentShader,
  8424. side: FrontSide,
  8425. depthTest: false,
  8426. depthWrite: false,
  8427. fog: false
  8428. } )
  8429. );
  8430. planeMesh.geometry.deleteAttribute( 'normal' );
  8431. // add "map" material property so the renderer can evaluate it like for built-in materials
  8432. Object.defineProperty( planeMesh.material, 'map', {
  8433. get: function () {
  8434. return this.uniforms.t2D.value;
  8435. }
  8436. } );
  8437. objects.update( planeMesh );
  8438. }
  8439. planeMesh.material.uniforms.t2D.value = background;
  8440. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8441. planeMesh.material.toneMapped = ( background.encoding === sRGBEncoding ) ? false : true;
  8442. if ( background.matrixAutoUpdate === true ) {
  8443. background.updateMatrix();
  8444. }
  8445. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  8446. if ( currentBackground !== background ||
  8447. currentBackgroundVersion !== background.version ||
  8448. currentTonemapping !== renderer.toneMapping ) {
  8449. planeMesh.material.needsUpdate = true;
  8450. currentBackground = background;
  8451. currentBackgroundVersion = background.version;
  8452. currentTonemapping = renderer.toneMapping;
  8453. }
  8454. planeMesh.layers.enableAll();
  8455. // push to the pre-sorted opaque render list
  8456. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  8457. }
  8458. }
  8459. function setClear( color, alpha ) {
  8460. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  8461. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  8462. }
  8463. return {
  8464. getClearColor: function () {
  8465. return clearColor;
  8466. },
  8467. setClearColor: function ( color, alpha = 1 ) {
  8468. clearColor.set( color );
  8469. clearAlpha = alpha;
  8470. setClear( clearColor, clearAlpha );
  8471. },
  8472. getClearAlpha: function () {
  8473. return clearAlpha;
  8474. },
  8475. setClearAlpha: function ( alpha ) {
  8476. clearAlpha = alpha;
  8477. setClear( clearColor, clearAlpha );
  8478. },
  8479. render: render
  8480. };
  8481. }
  8482. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  8483. const maxVertexAttributes = gl.getParameter( 34921 );
  8484. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  8485. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8486. const bindingStates = {};
  8487. const defaultState = createBindingState( null );
  8488. let currentState = defaultState;
  8489. let forceUpdate = false;
  8490. function setup( object, material, program, geometry, index ) {
  8491. let updateBuffers = false;
  8492. if ( vaoAvailable ) {
  8493. const state = getBindingState( geometry, program, material );
  8494. if ( currentState !== state ) {
  8495. currentState = state;
  8496. bindVertexArrayObject( currentState.object );
  8497. }
  8498. updateBuffers = needsUpdate( object, geometry, program, index );
  8499. if ( updateBuffers ) saveCache( object, geometry, program, index );
  8500. } else {
  8501. const wireframe = ( material.wireframe === true );
  8502. if ( currentState.geometry !== geometry.id ||
  8503. currentState.program !== program.id ||
  8504. currentState.wireframe !== wireframe ) {
  8505. currentState.geometry = geometry.id;
  8506. currentState.program = program.id;
  8507. currentState.wireframe = wireframe;
  8508. updateBuffers = true;
  8509. }
  8510. }
  8511. if ( index !== null ) {
  8512. attributes.update( index, 34963 );
  8513. }
  8514. if ( updateBuffers || forceUpdate ) {
  8515. forceUpdate = false;
  8516. setupVertexAttributes( object, material, program, geometry );
  8517. if ( index !== null ) {
  8518. gl.bindBuffer( 34963, attributes.get( index ).buffer );
  8519. }
  8520. }
  8521. }
  8522. function createVertexArrayObject() {
  8523. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  8524. return extension.createVertexArrayOES();
  8525. }
  8526. function bindVertexArrayObject( vao ) {
  8527. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  8528. return extension.bindVertexArrayOES( vao );
  8529. }
  8530. function deleteVertexArrayObject( vao ) {
  8531. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  8532. return extension.deleteVertexArrayOES( vao );
  8533. }
  8534. function getBindingState( geometry, program, material ) {
  8535. const wireframe = ( material.wireframe === true );
  8536. let programMap = bindingStates[ geometry.id ];
  8537. if ( programMap === undefined ) {
  8538. programMap = {};
  8539. bindingStates[ geometry.id ] = programMap;
  8540. }
  8541. let stateMap = programMap[ program.id ];
  8542. if ( stateMap === undefined ) {
  8543. stateMap = {};
  8544. programMap[ program.id ] = stateMap;
  8545. }
  8546. let state = stateMap[ wireframe ];
  8547. if ( state === undefined ) {
  8548. state = createBindingState( createVertexArrayObject() );
  8549. stateMap[ wireframe ] = state;
  8550. }
  8551. return state;
  8552. }
  8553. function createBindingState( vao ) {
  8554. const newAttributes = [];
  8555. const enabledAttributes = [];
  8556. const attributeDivisors = [];
  8557. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  8558. newAttributes[ i ] = 0;
  8559. enabledAttributes[ i ] = 0;
  8560. attributeDivisors[ i ] = 0;
  8561. }
  8562. return {
  8563. // for backward compatibility on non-VAO support browser
  8564. geometry: null,
  8565. program: null,
  8566. wireframe: false,
  8567. newAttributes: newAttributes,
  8568. enabledAttributes: enabledAttributes,
  8569. attributeDivisors: attributeDivisors,
  8570. object: vao,
  8571. attributes: {},
  8572. index: null
  8573. };
  8574. }
  8575. function needsUpdate( object, geometry, program, index ) {
  8576. const cachedAttributes = currentState.attributes;
  8577. const geometryAttributes = geometry.attributes;
  8578. let attributesNum = 0;
  8579. const programAttributes = program.getAttributes();
  8580. for ( const name in programAttributes ) {
  8581. const programAttribute = programAttributes[ name ];
  8582. if ( programAttribute.location >= 0 ) {
  8583. const cachedAttribute = cachedAttributes[ name ];
  8584. let geometryAttribute = geometryAttributes[ name ];
  8585. if ( geometryAttribute === undefined ) {
  8586. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8587. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8588. }
  8589. if ( cachedAttribute === undefined ) return true;
  8590. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  8591. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  8592. attributesNum ++;
  8593. }
  8594. }
  8595. if ( currentState.attributesNum !== attributesNum ) return true;
  8596. if ( currentState.index !== index ) return true;
  8597. return false;
  8598. }
  8599. function saveCache( object, geometry, program, index ) {
  8600. const cache = {};
  8601. const attributes = geometry.attributes;
  8602. let attributesNum = 0;
  8603. const programAttributes = program.getAttributes();
  8604. for ( const name in programAttributes ) {
  8605. const programAttribute = programAttributes[ name ];
  8606. if ( programAttribute.location >= 0 ) {
  8607. let attribute = attributes[ name ];
  8608. if ( attribute === undefined ) {
  8609. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  8610. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  8611. }
  8612. const data = {};
  8613. data.attribute = attribute;
  8614. if ( attribute && attribute.data ) {
  8615. data.data = attribute.data;
  8616. }
  8617. cache[ name ] = data;
  8618. attributesNum ++;
  8619. }
  8620. }
  8621. currentState.attributes = cache;
  8622. currentState.attributesNum = attributesNum;
  8623. currentState.index = index;
  8624. }
  8625. function initAttributes() {
  8626. const newAttributes = currentState.newAttributes;
  8627. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  8628. newAttributes[ i ] = 0;
  8629. }
  8630. }
  8631. function enableAttribute( attribute ) {
  8632. enableAttributeAndDivisor( attribute, 0 );
  8633. }
  8634. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  8635. const newAttributes = currentState.newAttributes;
  8636. const enabledAttributes = currentState.enabledAttributes;
  8637. const attributeDivisors = currentState.attributeDivisors;
  8638. newAttributes[ attribute ] = 1;
  8639. if ( enabledAttributes[ attribute ] === 0 ) {
  8640. gl.enableVertexAttribArray( attribute );
  8641. enabledAttributes[ attribute ] = 1;
  8642. }
  8643. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  8644. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  8645. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  8646. attributeDivisors[ attribute ] = meshPerAttribute;
  8647. }
  8648. }
  8649. function disableUnusedAttributes() {
  8650. const newAttributes = currentState.newAttributes;
  8651. const enabledAttributes = currentState.enabledAttributes;
  8652. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  8653. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  8654. gl.disableVertexAttribArray( i );
  8655. enabledAttributes[ i ] = 0;
  8656. }
  8657. }
  8658. }
  8659. function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
  8660. if ( capabilities.isWebGL2 === true && ( type === 5124 || type === 5125 ) ) {
  8661. gl.vertexAttribIPointer( index, size, type, stride, offset );
  8662. } else {
  8663. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  8664. }
  8665. }
  8666. function setupVertexAttributes( object, material, program, geometry ) {
  8667. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  8668. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  8669. }
  8670. initAttributes();
  8671. const geometryAttributes = geometry.attributes;
  8672. const programAttributes = program.getAttributes();
  8673. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8674. for ( const name in programAttributes ) {
  8675. const programAttribute = programAttributes[ name ];
  8676. if ( programAttribute.location >= 0 ) {
  8677. let geometryAttribute = geometryAttributes[ name ];
  8678. if ( geometryAttribute === undefined ) {
  8679. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8680. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8681. }
  8682. if ( geometryAttribute !== undefined ) {
  8683. const normalized = geometryAttribute.normalized;
  8684. const size = geometryAttribute.itemSize;
  8685. const attribute = attributes.get( geometryAttribute );
  8686. // TODO Attribute may not be available on context restore
  8687. if ( attribute === undefined ) continue;
  8688. const buffer = attribute.buffer;
  8689. const type = attribute.type;
  8690. const bytesPerElement = attribute.bytesPerElement;
  8691. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  8692. const data = geometryAttribute.data;
  8693. const stride = data.stride;
  8694. const offset = geometryAttribute.offset;
  8695. if ( data.isInstancedInterleavedBuffer ) {
  8696. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8697. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  8698. }
  8699. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8700. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8701. }
  8702. } else {
  8703. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8704. enableAttribute( programAttribute.location + i );
  8705. }
  8706. }
  8707. gl.bindBuffer( 34962, buffer );
  8708. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8709. vertexAttribPointer(
  8710. programAttribute.location + i,
  8711. size / programAttribute.locationSize,
  8712. type,
  8713. normalized,
  8714. stride * bytesPerElement,
  8715. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement
  8716. );
  8717. }
  8718. } else {
  8719. if ( geometryAttribute.isInstancedBufferAttribute ) {
  8720. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8721. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  8722. }
  8723. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8724. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8725. }
  8726. } else {
  8727. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8728. enableAttribute( programAttribute.location + i );
  8729. }
  8730. }
  8731. gl.bindBuffer( 34962, buffer );
  8732. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8733. vertexAttribPointer(
  8734. programAttribute.location + i,
  8735. size / programAttribute.locationSize,
  8736. type,
  8737. normalized,
  8738. size * bytesPerElement,
  8739. ( size / programAttribute.locationSize ) * i * bytesPerElement
  8740. );
  8741. }
  8742. }
  8743. } else if ( materialDefaultAttributeValues !== undefined ) {
  8744. const value = materialDefaultAttributeValues[ name ];
  8745. if ( value !== undefined ) {
  8746. switch ( value.length ) {
  8747. case 2:
  8748. gl.vertexAttrib2fv( programAttribute.location, value );
  8749. break;
  8750. case 3:
  8751. gl.vertexAttrib3fv( programAttribute.location, value );
  8752. break;
  8753. case 4:
  8754. gl.vertexAttrib4fv( programAttribute.location, value );
  8755. break;
  8756. default:
  8757. gl.vertexAttrib1fv( programAttribute.location, value );
  8758. }
  8759. }
  8760. }
  8761. }
  8762. }
  8763. disableUnusedAttributes();
  8764. }
  8765. function dispose() {
  8766. reset();
  8767. for ( const geometryId in bindingStates ) {
  8768. const programMap = bindingStates[ geometryId ];
  8769. for ( const programId in programMap ) {
  8770. const stateMap = programMap[ programId ];
  8771. for ( const wireframe in stateMap ) {
  8772. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8773. delete stateMap[ wireframe ];
  8774. }
  8775. delete programMap[ programId ];
  8776. }
  8777. delete bindingStates[ geometryId ];
  8778. }
  8779. }
  8780. function releaseStatesOfGeometry( geometry ) {
  8781. if ( bindingStates[ geometry.id ] === undefined ) return;
  8782. const programMap = bindingStates[ geometry.id ];
  8783. for ( const programId in programMap ) {
  8784. const stateMap = programMap[ programId ];
  8785. for ( const wireframe in stateMap ) {
  8786. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8787. delete stateMap[ wireframe ];
  8788. }
  8789. delete programMap[ programId ];
  8790. }
  8791. delete bindingStates[ geometry.id ];
  8792. }
  8793. function releaseStatesOfProgram( program ) {
  8794. for ( const geometryId in bindingStates ) {
  8795. const programMap = bindingStates[ geometryId ];
  8796. if ( programMap[ program.id ] === undefined ) continue;
  8797. const stateMap = programMap[ program.id ];
  8798. for ( const wireframe in stateMap ) {
  8799. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8800. delete stateMap[ wireframe ];
  8801. }
  8802. delete programMap[ program.id ];
  8803. }
  8804. }
  8805. function reset() {
  8806. resetDefaultState();
  8807. forceUpdate = true;
  8808. if ( currentState === defaultState ) return;
  8809. currentState = defaultState;
  8810. bindVertexArrayObject( currentState.object );
  8811. }
  8812. // for backward-compatibility
  8813. function resetDefaultState() {
  8814. defaultState.geometry = null;
  8815. defaultState.program = null;
  8816. defaultState.wireframe = false;
  8817. }
  8818. return {
  8819. setup: setup,
  8820. reset: reset,
  8821. resetDefaultState: resetDefaultState,
  8822. dispose: dispose,
  8823. releaseStatesOfGeometry: releaseStatesOfGeometry,
  8824. releaseStatesOfProgram: releaseStatesOfProgram,
  8825. initAttributes: initAttributes,
  8826. enableAttribute: enableAttribute,
  8827. disableUnusedAttributes: disableUnusedAttributes
  8828. };
  8829. }
  8830. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  8831. const isWebGL2 = capabilities.isWebGL2;
  8832. let mode;
  8833. function setMode( value ) {
  8834. mode = value;
  8835. }
  8836. function render( start, count ) {
  8837. gl.drawArrays( mode, start, count );
  8838. info.update( count, mode, 1 );
  8839. }
  8840. function renderInstances( start, count, primcount ) {
  8841. if ( primcount === 0 ) return;
  8842. let extension, methodName;
  8843. if ( isWebGL2 ) {
  8844. extension = gl;
  8845. methodName = 'drawArraysInstanced';
  8846. } else {
  8847. extension = extensions.get( 'ANGLE_instanced_arrays' );
  8848. methodName = 'drawArraysInstancedANGLE';
  8849. if ( extension === null ) {
  8850. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  8851. return;
  8852. }
  8853. }
  8854. extension[ methodName ]( mode, start, count, primcount );
  8855. info.update( count, mode, primcount );
  8856. }
  8857. //
  8858. this.setMode = setMode;
  8859. this.render = render;
  8860. this.renderInstances = renderInstances;
  8861. }
  8862. function WebGLCapabilities( gl, extensions, parameters ) {
  8863. let maxAnisotropy;
  8864. function getMaxAnisotropy() {
  8865. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  8866. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  8867. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  8868. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  8869. } else {
  8870. maxAnisotropy = 0;
  8871. }
  8872. return maxAnisotropy;
  8873. }
  8874. function getMaxPrecision( precision ) {
  8875. if ( precision === 'highp' ) {
  8876. if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
  8877. gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
  8878. return 'highp';
  8879. }
  8880. precision = 'mediump';
  8881. }
  8882. if ( precision === 'mediump' ) {
  8883. if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
  8884. gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
  8885. return 'mediump';
  8886. }
  8887. }
  8888. return 'lowp';
  8889. }
  8890. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext;
  8891. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  8892. const maxPrecision = getMaxPrecision( precision );
  8893. if ( maxPrecision !== precision ) {
  8894. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  8895. precision = maxPrecision;
  8896. }
  8897. const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' );
  8898. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  8899. const maxTextures = gl.getParameter( 34930 );
  8900. const maxVertexTextures = gl.getParameter( 35660 );
  8901. const maxTextureSize = gl.getParameter( 3379 );
  8902. const maxCubemapSize = gl.getParameter( 34076 );
  8903. const maxAttributes = gl.getParameter( 34921 );
  8904. const maxVertexUniforms = gl.getParameter( 36347 );
  8905. const maxVaryings = gl.getParameter( 36348 );
  8906. const maxFragmentUniforms = gl.getParameter( 36349 );
  8907. const vertexTextures = maxVertexTextures > 0;
  8908. const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );
  8909. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  8910. const maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;
  8911. return {
  8912. isWebGL2: isWebGL2,
  8913. drawBuffers: drawBuffers,
  8914. getMaxAnisotropy: getMaxAnisotropy,
  8915. getMaxPrecision: getMaxPrecision,
  8916. precision: precision,
  8917. logarithmicDepthBuffer: logarithmicDepthBuffer,
  8918. maxTextures: maxTextures,
  8919. maxVertexTextures: maxVertexTextures,
  8920. maxTextureSize: maxTextureSize,
  8921. maxCubemapSize: maxCubemapSize,
  8922. maxAttributes: maxAttributes,
  8923. maxVertexUniforms: maxVertexUniforms,
  8924. maxVaryings: maxVaryings,
  8925. maxFragmentUniforms: maxFragmentUniforms,
  8926. vertexTextures: vertexTextures,
  8927. floatFragmentTextures: floatFragmentTextures,
  8928. floatVertexTextures: floatVertexTextures,
  8929. maxSamples: maxSamples
  8930. };
  8931. }
  8932. function WebGLClipping( properties ) {
  8933. const scope = this;
  8934. let globalState = null,
  8935. numGlobalPlanes = 0,
  8936. localClippingEnabled = false,
  8937. renderingShadows = false;
  8938. const plane = new Plane(),
  8939. viewNormalMatrix = new Matrix3(),
  8940. uniform = { value: null, needsUpdate: false };
  8941. this.uniform = uniform;
  8942. this.numPlanes = 0;
  8943. this.numIntersection = 0;
  8944. this.init = function ( planes, enableLocalClipping ) {
  8945. const enabled =
  8946. planes.length !== 0 ||
  8947. enableLocalClipping ||
  8948. // enable state of previous frame - the clipping code has to
  8949. // run another frame in order to reset the state:
  8950. numGlobalPlanes !== 0 ||
  8951. localClippingEnabled;
  8952. localClippingEnabled = enableLocalClipping;
  8953. numGlobalPlanes = planes.length;
  8954. return enabled;
  8955. };
  8956. this.beginShadows = function () {
  8957. renderingShadows = true;
  8958. projectPlanes( null );
  8959. };
  8960. this.endShadows = function () {
  8961. renderingShadows = false;
  8962. };
  8963. this.setGlobalState = function ( planes, camera ) {
  8964. globalState = projectPlanes( planes, camera, 0 );
  8965. };
  8966. this.setState = function ( material, camera, useCache ) {
  8967. const planes = material.clippingPlanes,
  8968. clipIntersection = material.clipIntersection,
  8969. clipShadows = material.clipShadows;
  8970. const materialProperties = properties.get( material );
  8971. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  8972. // there's no local clipping
  8973. if ( renderingShadows ) {
  8974. // there's no global clipping
  8975. projectPlanes( null );
  8976. } else {
  8977. resetGlobalState();
  8978. }
  8979. } else {
  8980. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  8981. lGlobal = nGlobal * 4;
  8982. let dstArray = materialProperties.clippingState || null;
  8983. uniform.value = dstArray; // ensure unique state
  8984. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  8985. for ( let i = 0; i !== lGlobal; ++ i ) {
  8986. dstArray[ i ] = globalState[ i ];
  8987. }
  8988. materialProperties.clippingState = dstArray;
  8989. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  8990. this.numPlanes += nGlobal;
  8991. }
  8992. };
  8993. function resetGlobalState() {
  8994. if ( uniform.value !== globalState ) {
  8995. uniform.value = globalState;
  8996. uniform.needsUpdate = numGlobalPlanes > 0;
  8997. }
  8998. scope.numPlanes = numGlobalPlanes;
  8999. scope.numIntersection = 0;
  9000. }
  9001. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  9002. const nPlanes = planes !== null ? planes.length : 0;
  9003. let dstArray = null;
  9004. if ( nPlanes !== 0 ) {
  9005. dstArray = uniform.value;
  9006. if ( skipTransform !== true || dstArray === null ) {
  9007. const flatSize = dstOffset + nPlanes * 4,
  9008. viewMatrix = camera.matrixWorldInverse;
  9009. viewNormalMatrix.getNormalMatrix( viewMatrix );
  9010. if ( dstArray === null || dstArray.length < flatSize ) {
  9011. dstArray = new Float32Array( flatSize );
  9012. }
  9013. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  9014. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  9015. plane.normal.toArray( dstArray, i4 );
  9016. dstArray[ i4 + 3 ] = plane.constant;
  9017. }
  9018. }
  9019. uniform.value = dstArray;
  9020. uniform.needsUpdate = true;
  9021. }
  9022. scope.numPlanes = nPlanes;
  9023. scope.numIntersection = 0;
  9024. return dstArray;
  9025. }
  9026. }
  9027. function WebGLCubeMaps( renderer ) {
  9028. let cubemaps = new WeakMap();
  9029. function mapTextureMapping( texture, mapping ) {
  9030. if ( mapping === EquirectangularReflectionMapping ) {
  9031. texture.mapping = CubeReflectionMapping;
  9032. } else if ( mapping === EquirectangularRefractionMapping ) {
  9033. texture.mapping = CubeRefractionMapping;
  9034. }
  9035. return texture;
  9036. }
  9037. function get( texture ) {
  9038. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  9039. const mapping = texture.mapping;
  9040. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  9041. if ( cubemaps.has( texture ) ) {
  9042. const cubemap = cubemaps.get( texture ).texture;
  9043. return mapTextureMapping( cubemap, texture.mapping );
  9044. } else {
  9045. const image = texture.image;
  9046. if ( image && image.height > 0 ) {
  9047. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  9048. renderTarget.fromEquirectangularTexture( renderer, texture );
  9049. cubemaps.set( texture, renderTarget );
  9050. texture.addEventListener( 'dispose', onTextureDispose );
  9051. return mapTextureMapping( renderTarget.texture, texture.mapping );
  9052. } else {
  9053. // image not yet ready. try the conversion next frame
  9054. return null;
  9055. }
  9056. }
  9057. }
  9058. }
  9059. return texture;
  9060. }
  9061. function onTextureDispose( event ) {
  9062. const texture = event.target;
  9063. texture.removeEventListener( 'dispose', onTextureDispose );
  9064. const cubemap = cubemaps.get( texture );
  9065. if ( cubemap !== undefined ) {
  9066. cubemaps.delete( texture );
  9067. cubemap.dispose();
  9068. }
  9069. }
  9070. function dispose() {
  9071. cubemaps = new WeakMap();
  9072. }
  9073. return {
  9074. get: get,
  9075. dispose: dispose
  9076. };
  9077. }
  9078. class OrthographicCamera extends Camera {
  9079. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  9080. super();
  9081. this.isOrthographicCamera = true;
  9082. this.type = 'OrthographicCamera';
  9083. this.zoom = 1;
  9084. this.view = null;
  9085. this.left = left;
  9086. this.right = right;
  9087. this.top = top;
  9088. this.bottom = bottom;
  9089. this.near = near;
  9090. this.far = far;
  9091. this.updateProjectionMatrix();
  9092. }
  9093. copy( source, recursive ) {
  9094. super.copy( source, recursive );
  9095. this.left = source.left;
  9096. this.right = source.right;
  9097. this.top = source.top;
  9098. this.bottom = source.bottom;
  9099. this.near = source.near;
  9100. this.far = source.far;
  9101. this.zoom = source.zoom;
  9102. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9103. return this;
  9104. }
  9105. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  9106. if ( this.view === null ) {
  9107. this.view = {
  9108. enabled: true,
  9109. fullWidth: 1,
  9110. fullHeight: 1,
  9111. offsetX: 0,
  9112. offsetY: 0,
  9113. width: 1,
  9114. height: 1
  9115. };
  9116. }
  9117. this.view.enabled = true;
  9118. this.view.fullWidth = fullWidth;
  9119. this.view.fullHeight = fullHeight;
  9120. this.view.offsetX = x;
  9121. this.view.offsetY = y;
  9122. this.view.width = width;
  9123. this.view.height = height;
  9124. this.updateProjectionMatrix();
  9125. }
  9126. clearViewOffset() {
  9127. if ( this.view !== null ) {
  9128. this.view.enabled = false;
  9129. }
  9130. this.updateProjectionMatrix();
  9131. }
  9132. updateProjectionMatrix() {
  9133. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9134. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9135. const cx = ( this.right + this.left ) / 2;
  9136. const cy = ( this.top + this.bottom ) / 2;
  9137. let left = cx - dx;
  9138. let right = cx + dx;
  9139. let top = cy + dy;
  9140. let bottom = cy - dy;
  9141. if ( this.view !== null && this.view.enabled ) {
  9142. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  9143. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  9144. left += scaleW * this.view.offsetX;
  9145. right = left + scaleW * this.view.width;
  9146. top -= scaleH * this.view.offsetY;
  9147. bottom = top - scaleH * this.view.height;
  9148. }
  9149. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  9150. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  9151. }
  9152. toJSON( meta ) {
  9153. const data = super.toJSON( meta );
  9154. data.object.zoom = this.zoom;
  9155. data.object.left = this.left;
  9156. data.object.right = this.right;
  9157. data.object.top = this.top;
  9158. data.object.bottom = this.bottom;
  9159. data.object.near = this.near;
  9160. data.object.far = this.far;
  9161. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9162. return data;
  9163. }
  9164. }
  9165. const LOD_MIN = 4;
  9166. // The standard deviations (radians) associated with the extra mips. These are
  9167. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9168. // geometric shadowing function. These sigma values squared must match the
  9169. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9170. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  9171. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9172. // samples and exit early, but not recompile the shader.
  9173. const MAX_SAMPLES = 20;
  9174. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  9175. const _clearColor = /*@__PURE__*/ new Color();
  9176. let _oldTarget = null;
  9177. // Golden Ratio
  9178. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  9179. const INV_PHI = 1 / PHI;
  9180. // Vertices of a dodecahedron (except the opposites, which represent the
  9181. // same axis), used as axis directions evenly spread on a sphere.
  9182. const _axisDirections = [
  9183. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  9184. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  9185. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  9186. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  9187. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  9188. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  9189. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  9190. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  9191. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  9192. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  9193. /**
  9194. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9195. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9196. * blur to be quickly accessed based on material roughness. It is packed into a
  9197. * special CubeUV format that allows us to perform custom interpolation so that
  9198. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9199. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9200. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9201. * higher roughness levels. In this way we maintain resolution to smoothly
  9202. * interpolate diffuse lighting while limiting sampling computation.
  9203. *
  9204. * Paper: Fast, Accurate Image-Based Lighting
  9205. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9206. */
  9207. class PMREMGenerator {
  9208. constructor( renderer ) {
  9209. this._renderer = renderer;
  9210. this._pingPongRenderTarget = null;
  9211. this._lodMax = 0;
  9212. this._cubeSize = 0;
  9213. this._lodPlanes = [];
  9214. this._sizeLods = [];
  9215. this._sigmas = [];
  9216. this._blurMaterial = null;
  9217. this._cubemapMaterial = null;
  9218. this._equirectMaterial = null;
  9219. this._compileMaterial( this._blurMaterial );
  9220. }
  9221. /**
  9222. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9223. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9224. * in radians to be applied to the scene before PMREM generation. Optional near
  9225. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9226. * is placed at the origin).
  9227. */
  9228. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  9229. _oldTarget = this._renderer.getRenderTarget();
  9230. this._setSize( 256 );
  9231. const cubeUVRenderTarget = this._allocateTargets();
  9232. cubeUVRenderTarget.depthBuffer = true;
  9233. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  9234. if ( sigma > 0 ) {
  9235. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  9236. }
  9237. this._applyPMREM( cubeUVRenderTarget );
  9238. this._cleanup( cubeUVRenderTarget );
  9239. return cubeUVRenderTarget;
  9240. }
  9241. /**
  9242. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9243. * or HDR. The ideal input image size is 1k (1024 x 512),
  9244. * as this matches best with the 256 x 256 cubemap output.
  9245. */
  9246. fromEquirectangular( equirectangular, renderTarget = null ) {
  9247. return this._fromTexture( equirectangular, renderTarget );
  9248. }
  9249. /**
  9250. * Generates a PMREM from an cubemap texture, which can be either LDR
  9251. * or HDR. The ideal input cube size is 256 x 256,
  9252. * as this matches best with the 256 x 256 cubemap output.
  9253. */
  9254. fromCubemap( cubemap, renderTarget = null ) {
  9255. return this._fromTexture( cubemap, renderTarget );
  9256. }
  9257. /**
  9258. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9259. * your texture's network fetch for increased concurrency.
  9260. */
  9261. compileCubemapShader() {
  9262. if ( this._cubemapMaterial === null ) {
  9263. this._cubemapMaterial = _getCubemapMaterial();
  9264. this._compileMaterial( this._cubemapMaterial );
  9265. }
  9266. }
  9267. /**
  9268. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9269. * your texture's network fetch for increased concurrency.
  9270. */
  9271. compileEquirectangularShader() {
  9272. if ( this._equirectMaterial === null ) {
  9273. this._equirectMaterial = _getEquirectMaterial();
  9274. this._compileMaterial( this._equirectMaterial );
  9275. }
  9276. }
  9277. /**
  9278. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9279. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9280. * one of them will cause any others to also become unusable.
  9281. */
  9282. dispose() {
  9283. this._dispose();
  9284. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  9285. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  9286. }
  9287. // private interface
  9288. _setSize( cubeSize ) {
  9289. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  9290. this._cubeSize = Math.pow( 2, this._lodMax );
  9291. }
  9292. _dispose() {
  9293. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  9294. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  9295. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  9296. this._lodPlanes[ i ].dispose();
  9297. }
  9298. }
  9299. _cleanup( outputTarget ) {
  9300. this._renderer.setRenderTarget( _oldTarget );
  9301. outputTarget.scissorTest = false;
  9302. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  9303. }
  9304. _fromTexture( texture, renderTarget ) {
  9305. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  9306. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  9307. } else { // Equirectangular
  9308. this._setSize( texture.image.width / 4 );
  9309. }
  9310. _oldTarget = this._renderer.getRenderTarget();
  9311. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9312. this._textureToCubeUV( texture, cubeUVRenderTarget );
  9313. this._applyPMREM( cubeUVRenderTarget );
  9314. this._cleanup( cubeUVRenderTarget );
  9315. return cubeUVRenderTarget;
  9316. }
  9317. _allocateTargets() {
  9318. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  9319. const height = 4 * this._cubeSize;
  9320. const params = {
  9321. magFilter: LinearFilter,
  9322. minFilter: LinearFilter,
  9323. generateMipmaps: false,
  9324. type: HalfFloatType,
  9325. format: RGBAFormat,
  9326. encoding: LinearEncoding,
  9327. depthBuffer: false
  9328. };
  9329. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  9330. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  9331. if ( this._pingPongRenderTarget !== null ) {
  9332. this._dispose();
  9333. }
  9334. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  9335. const { _lodMax } = this;
  9336. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  9337. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  9338. }
  9339. return cubeUVRenderTarget;
  9340. }
  9341. _compileMaterial( material ) {
  9342. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  9343. this._renderer.compile( tmpMesh, _flatCamera );
  9344. }
  9345. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  9346. const fov = 90;
  9347. const aspect = 1;
  9348. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  9349. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  9350. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  9351. const renderer = this._renderer;
  9352. const originalAutoClear = renderer.autoClear;
  9353. const toneMapping = renderer.toneMapping;
  9354. renderer.getClearColor( _clearColor );
  9355. renderer.toneMapping = NoToneMapping;
  9356. renderer.autoClear = false;
  9357. const backgroundMaterial = new MeshBasicMaterial( {
  9358. name: 'PMREM.Background',
  9359. side: BackSide,
  9360. depthWrite: false,
  9361. depthTest: false,
  9362. } );
  9363. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  9364. let useSolidColor = false;
  9365. const background = scene.background;
  9366. if ( background ) {
  9367. if ( background.isColor ) {
  9368. backgroundMaterial.color.copy( background );
  9369. scene.background = null;
  9370. useSolidColor = true;
  9371. }
  9372. } else {
  9373. backgroundMaterial.color.copy( _clearColor );
  9374. useSolidColor = true;
  9375. }
  9376. for ( let i = 0; i < 6; i ++ ) {
  9377. const col = i % 3;
  9378. if ( col === 0 ) {
  9379. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9380. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  9381. } else if ( col === 1 ) {
  9382. cubeCamera.up.set( 0, 0, upSign[ i ] );
  9383. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  9384. } else {
  9385. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9386. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  9387. }
  9388. const size = this._cubeSize;
  9389. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  9390. renderer.setRenderTarget( cubeUVRenderTarget );
  9391. if ( useSolidColor ) {
  9392. renderer.render( backgroundBox, cubeCamera );
  9393. }
  9394. renderer.render( scene, cubeCamera );
  9395. }
  9396. backgroundBox.geometry.dispose();
  9397. backgroundBox.material.dispose();
  9398. renderer.toneMapping = toneMapping;
  9399. renderer.autoClear = originalAutoClear;
  9400. scene.background = background;
  9401. }
  9402. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  9403. const renderer = this._renderer;
  9404. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  9405. if ( isCubeTexture ) {
  9406. if ( this._cubemapMaterial === null ) {
  9407. this._cubemapMaterial = _getCubemapMaterial();
  9408. }
  9409. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;
  9410. } else {
  9411. if ( this._equirectMaterial === null ) {
  9412. this._equirectMaterial = _getEquirectMaterial();
  9413. }
  9414. }
  9415. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  9416. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  9417. const uniforms = material.uniforms;
  9418. uniforms[ 'envMap' ].value = texture;
  9419. const size = this._cubeSize;
  9420. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  9421. renderer.setRenderTarget( cubeUVRenderTarget );
  9422. renderer.render( mesh, _flatCamera );
  9423. }
  9424. _applyPMREM( cubeUVRenderTarget ) {
  9425. const renderer = this._renderer;
  9426. const autoClear = renderer.autoClear;
  9427. renderer.autoClear = false;
  9428. for ( let i = 1; i < this._lodPlanes.length; i ++ ) {
  9429. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  9430. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  9431. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  9432. }
  9433. renderer.autoClear = autoClear;
  9434. }
  9435. /**
  9436. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9437. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9438. * the blur latitudinally (around the poles), and then longitudinally (towards
  9439. * the poles) to approximate the orthogonally-separable blur. It is least
  9440. * accurate at the poles, but still does a decent job.
  9441. */
  9442. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  9443. const pingPongRenderTarget = this._pingPongRenderTarget;
  9444. this._halfBlur(
  9445. cubeUVRenderTarget,
  9446. pingPongRenderTarget,
  9447. lodIn,
  9448. lodOut,
  9449. sigma,
  9450. 'latitudinal',
  9451. poleAxis );
  9452. this._halfBlur(
  9453. pingPongRenderTarget,
  9454. cubeUVRenderTarget,
  9455. lodOut,
  9456. lodOut,
  9457. sigma,
  9458. 'longitudinal',
  9459. poleAxis );
  9460. }
  9461. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  9462. const renderer = this._renderer;
  9463. const blurMaterial = this._blurMaterial;
  9464. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  9465. console.error(
  9466. 'blur direction must be either latitudinal or longitudinal!' );
  9467. }
  9468. // Number of standard deviations at which to cut off the discrete approximation.
  9469. const STANDARD_DEVIATIONS = 3;
  9470. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  9471. const blurUniforms = blurMaterial.uniforms;
  9472. const pixels = this._sizeLods[ lodIn ] - 1;
  9473. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  9474. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9475. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  9476. if ( samples > MAX_SAMPLES ) {
  9477. console.warn( `sigmaRadians, ${
  9478. sigmaRadians}, is too large and will clip, as it requested ${
  9479. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  9480. }
  9481. const weights = [];
  9482. let sum = 0;
  9483. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  9484. const x = i / sigmaPixels;
  9485. const weight = Math.exp( - x * x / 2 );
  9486. weights.push( weight );
  9487. if ( i === 0 ) {
  9488. sum += weight;
  9489. } else if ( i < samples ) {
  9490. sum += 2 * weight;
  9491. }
  9492. }
  9493. for ( let i = 0; i < weights.length; i ++ ) {
  9494. weights[ i ] = weights[ i ] / sum;
  9495. }
  9496. blurUniforms[ 'envMap' ].value = targetIn.texture;
  9497. blurUniforms[ 'samples' ].value = samples;
  9498. blurUniforms[ 'weights' ].value = weights;
  9499. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  9500. if ( poleAxis ) {
  9501. blurUniforms[ 'poleAxis' ].value = poleAxis;
  9502. }
  9503. const { _lodMax } = this;
  9504. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  9505. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  9506. const outputSize = this._sizeLods[ lodOut ];
  9507. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  9508. const y = 4 * ( this._cubeSize - outputSize );
  9509. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  9510. renderer.setRenderTarget( targetOut );
  9511. renderer.render( blurMesh, _flatCamera );
  9512. }
  9513. }
  9514. function _createPlanes( lodMax ) {
  9515. const lodPlanes = [];
  9516. const sizeLods = [];
  9517. const sigmas = [];
  9518. let lod = lodMax;
  9519. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  9520. for ( let i = 0; i < totalLods; i ++ ) {
  9521. const sizeLod = Math.pow( 2, lod );
  9522. sizeLods.push( sizeLod );
  9523. let sigma = 1.0 / sizeLod;
  9524. if ( i > lodMax - LOD_MIN ) {
  9525. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  9526. } else if ( i === 0 ) {
  9527. sigma = 0;
  9528. }
  9529. sigmas.push( sigma );
  9530. const texelSize = 1.0 / ( sizeLod - 2 );
  9531. const min = - texelSize;
  9532. const max = 1 + texelSize;
  9533. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  9534. const cubeFaces = 6;
  9535. const vertices = 6;
  9536. const positionSize = 3;
  9537. const uvSize = 2;
  9538. const faceIndexSize = 1;
  9539. const position = new Float32Array( positionSize * vertices * cubeFaces );
  9540. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  9541. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  9542. for ( let face = 0; face < cubeFaces; face ++ ) {
  9543. const x = ( face % 3 ) * 2 / 3 - 1;
  9544. const y = face > 2 ? 0 : - 1;
  9545. const coordinates = [
  9546. x, y, 0,
  9547. x + 2 / 3, y, 0,
  9548. x + 2 / 3, y + 1, 0,
  9549. x, y, 0,
  9550. x + 2 / 3, y + 1, 0,
  9551. x, y + 1, 0
  9552. ];
  9553. position.set( coordinates, positionSize * vertices * face );
  9554. uv.set( uv1, uvSize * vertices * face );
  9555. const fill = [ face, face, face, face, face, face ];
  9556. faceIndex.set( fill, faceIndexSize * vertices * face );
  9557. }
  9558. const planes = new BufferGeometry();
  9559. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  9560. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  9561. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  9562. lodPlanes.push( planes );
  9563. if ( lod > LOD_MIN ) {
  9564. lod --;
  9565. }
  9566. }
  9567. return { lodPlanes, sizeLods, sigmas };
  9568. }
  9569. function _createRenderTarget( width, height, params ) {
  9570. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  9571. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9572. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9573. cubeUVRenderTarget.scissorTest = true;
  9574. return cubeUVRenderTarget;
  9575. }
  9576. function _setViewport( target, x, y, width, height ) {
  9577. target.viewport.set( x, y, width, height );
  9578. target.scissor.set( x, y, width, height );
  9579. }
  9580. function _getBlurShader( lodMax, width, height ) {
  9581. const weights = new Float32Array( MAX_SAMPLES );
  9582. const poleAxis = new Vector3( 0, 1, 0 );
  9583. const shaderMaterial = new ShaderMaterial( {
  9584. name: 'SphericalGaussianBlur',
  9585. defines: {
  9586. 'n': MAX_SAMPLES,
  9587. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  9588. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  9589. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  9590. },
  9591. uniforms: {
  9592. 'envMap': { value: null },
  9593. 'samples': { value: 1 },
  9594. 'weights': { value: weights },
  9595. 'latitudinal': { value: false },
  9596. 'dTheta': { value: 0 },
  9597. 'mipInt': { value: 0 },
  9598. 'poleAxis': { value: poleAxis }
  9599. },
  9600. vertexShader: _getCommonVertexShader(),
  9601. fragmentShader: /* glsl */`
  9602. precision mediump float;
  9603. precision mediump int;
  9604. varying vec3 vOutputDirection;
  9605. uniform sampler2D envMap;
  9606. uniform int samples;
  9607. uniform float weights[ n ];
  9608. uniform bool latitudinal;
  9609. uniform float dTheta;
  9610. uniform float mipInt;
  9611. uniform vec3 poleAxis;
  9612. #define ENVMAP_TYPE_CUBE_UV
  9613. #include <cube_uv_reflection_fragment>
  9614. vec3 getSample( float theta, vec3 axis ) {
  9615. float cosTheta = cos( theta );
  9616. // Rodrigues' axis-angle rotation
  9617. vec3 sampleDirection = vOutputDirection * cosTheta
  9618. + cross( axis, vOutputDirection ) * sin( theta )
  9619. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9620. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  9621. }
  9622. void main() {
  9623. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  9624. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  9625. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  9626. }
  9627. axis = normalize( axis );
  9628. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9629. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  9630. for ( int i = 1; i < n; i++ ) {
  9631. if ( i >= samples ) {
  9632. break;
  9633. }
  9634. float theta = dTheta * float( i );
  9635. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  9636. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  9637. }
  9638. }
  9639. `,
  9640. blending: NoBlending,
  9641. depthTest: false,
  9642. depthWrite: false
  9643. } );
  9644. return shaderMaterial;
  9645. }
  9646. function _getEquirectMaterial() {
  9647. return new ShaderMaterial( {
  9648. name: 'EquirectangularToCubeUV',
  9649. uniforms: {
  9650. 'envMap': { value: null }
  9651. },
  9652. vertexShader: _getCommonVertexShader(),
  9653. fragmentShader: /* glsl */`
  9654. precision mediump float;
  9655. precision mediump int;
  9656. varying vec3 vOutputDirection;
  9657. uniform sampler2D envMap;
  9658. #include <common>
  9659. void main() {
  9660. vec3 outputDirection = normalize( vOutputDirection );
  9661. vec2 uv = equirectUv( outputDirection );
  9662. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  9663. }
  9664. `,
  9665. blending: NoBlending,
  9666. depthTest: false,
  9667. depthWrite: false
  9668. } );
  9669. }
  9670. function _getCubemapMaterial() {
  9671. return new ShaderMaterial( {
  9672. name: 'CubemapToCubeUV',
  9673. uniforms: {
  9674. 'envMap': { value: null },
  9675. 'flipEnvMap': { value: - 1 }
  9676. },
  9677. vertexShader: _getCommonVertexShader(),
  9678. fragmentShader: /* glsl */`
  9679. precision mediump float;
  9680. precision mediump int;
  9681. uniform float flipEnvMap;
  9682. varying vec3 vOutputDirection;
  9683. uniform samplerCube envMap;
  9684. void main() {
  9685. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  9686. }
  9687. `,
  9688. blending: NoBlending,
  9689. depthTest: false,
  9690. depthWrite: false
  9691. } );
  9692. }
  9693. function _getCommonVertexShader() {
  9694. return /* glsl */`
  9695. precision mediump float;
  9696. precision mediump int;
  9697. attribute float faceIndex;
  9698. varying vec3 vOutputDirection;
  9699. // RH coordinate system; PMREM face-indexing convention
  9700. vec3 getDirection( vec2 uv, float face ) {
  9701. uv = 2.0 * uv - 1.0;
  9702. vec3 direction = vec3( uv, 1.0 );
  9703. if ( face == 0.0 ) {
  9704. direction = direction.zyx; // ( 1, v, u ) pos x
  9705. } else if ( face == 1.0 ) {
  9706. direction = direction.xzy;
  9707. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  9708. } else if ( face == 2.0 ) {
  9709. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  9710. } else if ( face == 3.0 ) {
  9711. direction = direction.zyx;
  9712. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  9713. } else if ( face == 4.0 ) {
  9714. direction = direction.xzy;
  9715. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  9716. } else if ( face == 5.0 ) {
  9717. direction.z *= -1.0; // ( u, v, -1 ) neg z
  9718. }
  9719. return direction;
  9720. }
  9721. void main() {
  9722. vOutputDirection = getDirection( uv, faceIndex );
  9723. gl_Position = vec4( position, 1.0 );
  9724. }
  9725. `;
  9726. }
  9727. function WebGLCubeUVMaps( renderer ) {
  9728. let cubeUVmaps = new WeakMap();
  9729. let pmremGenerator = null;
  9730. function get( texture ) {
  9731. if ( texture && texture.isTexture ) {
  9732. const mapping = texture.mapping;
  9733. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  9734. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  9735. // equirect/cube map to cubeUV conversion
  9736. if ( isEquirectMap || isCubeMap ) {
  9737. if ( texture.isRenderTargetTexture && texture.needsPMREMUpdate === true ) {
  9738. texture.needsPMREMUpdate = false;
  9739. let renderTarget = cubeUVmaps.get( texture );
  9740. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  9741. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  9742. cubeUVmaps.set( texture, renderTarget );
  9743. return renderTarget.texture;
  9744. } else {
  9745. if ( cubeUVmaps.has( texture ) ) {
  9746. return cubeUVmaps.get( texture ).texture;
  9747. } else {
  9748. const image = texture.image;
  9749. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  9750. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  9751. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  9752. cubeUVmaps.set( texture, renderTarget );
  9753. texture.addEventListener( 'dispose', onTextureDispose );
  9754. return renderTarget.texture;
  9755. } else {
  9756. // image not yet ready. try the conversion next frame
  9757. return null;
  9758. }
  9759. }
  9760. }
  9761. }
  9762. }
  9763. return texture;
  9764. }
  9765. function isCubeTextureComplete( image ) {
  9766. let count = 0;
  9767. const length = 6;
  9768. for ( let i = 0; i < length; i ++ ) {
  9769. if ( image[ i ] !== undefined ) count ++;
  9770. }
  9771. return count === length;
  9772. }
  9773. function onTextureDispose( event ) {
  9774. const texture = event.target;
  9775. texture.removeEventListener( 'dispose', onTextureDispose );
  9776. const cubemapUV = cubeUVmaps.get( texture );
  9777. if ( cubemapUV !== undefined ) {
  9778. cubeUVmaps.delete( texture );
  9779. cubemapUV.dispose();
  9780. }
  9781. }
  9782. function dispose() {
  9783. cubeUVmaps = new WeakMap();
  9784. if ( pmremGenerator !== null ) {
  9785. pmremGenerator.dispose();
  9786. pmremGenerator = null;
  9787. }
  9788. }
  9789. return {
  9790. get: get,
  9791. dispose: dispose
  9792. };
  9793. }
  9794. function WebGLExtensions( gl ) {
  9795. const extensions = {};
  9796. function getExtension( name ) {
  9797. if ( extensions[ name ] !== undefined ) {
  9798. return extensions[ name ];
  9799. }
  9800. let extension;
  9801. switch ( name ) {
  9802. case 'WEBGL_depth_texture':
  9803. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  9804. break;
  9805. case 'EXT_texture_filter_anisotropic':
  9806. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  9807. break;
  9808. case 'WEBGL_compressed_texture_s3tc':
  9809. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  9810. break;
  9811. case 'WEBGL_compressed_texture_pvrtc':
  9812. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  9813. break;
  9814. default:
  9815. extension = gl.getExtension( name );
  9816. }
  9817. extensions[ name ] = extension;
  9818. return extension;
  9819. }
  9820. return {
  9821. has: function ( name ) {
  9822. return getExtension( name ) !== null;
  9823. },
  9824. init: function ( capabilities ) {
  9825. if ( capabilities.isWebGL2 ) {
  9826. getExtension( 'EXT_color_buffer_float' );
  9827. } else {
  9828. getExtension( 'WEBGL_depth_texture' );
  9829. getExtension( 'OES_texture_float' );
  9830. getExtension( 'OES_texture_half_float' );
  9831. getExtension( 'OES_texture_half_float_linear' );
  9832. getExtension( 'OES_standard_derivatives' );
  9833. getExtension( 'OES_element_index_uint' );
  9834. getExtension( 'OES_vertex_array_object' );
  9835. getExtension( 'ANGLE_instanced_arrays' );
  9836. }
  9837. getExtension( 'OES_texture_float_linear' );
  9838. getExtension( 'EXT_color_buffer_half_float' );
  9839. getExtension( 'WEBGL_multisampled_render_to_texture' );
  9840. },
  9841. get: function ( name ) {
  9842. const extension = getExtension( name );
  9843. if ( extension === null ) {
  9844. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  9845. }
  9846. return extension;
  9847. }
  9848. };
  9849. }
  9850. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  9851. const geometries = {};
  9852. const wireframeAttributes = new WeakMap();
  9853. function onGeometryDispose( event ) {
  9854. const geometry = event.target;
  9855. if ( geometry.index !== null ) {
  9856. attributes.remove( geometry.index );
  9857. }
  9858. for ( const name in geometry.attributes ) {
  9859. attributes.remove( geometry.attributes[ name ] );
  9860. }
  9861. geometry.removeEventListener( 'dispose', onGeometryDispose );
  9862. delete geometries[ geometry.id ];
  9863. const attribute = wireframeAttributes.get( geometry );
  9864. if ( attribute ) {
  9865. attributes.remove( attribute );
  9866. wireframeAttributes.delete( geometry );
  9867. }
  9868. bindingStates.releaseStatesOfGeometry( geometry );
  9869. if ( geometry.isInstancedBufferGeometry === true ) {
  9870. delete geometry._maxInstanceCount;
  9871. }
  9872. //
  9873. info.memory.geometries --;
  9874. }
  9875. function get( object, geometry ) {
  9876. if ( geometries[ geometry.id ] === true ) return geometry;
  9877. geometry.addEventListener( 'dispose', onGeometryDispose );
  9878. geometries[ geometry.id ] = true;
  9879. info.memory.geometries ++;
  9880. return geometry;
  9881. }
  9882. function update( geometry ) {
  9883. const geometryAttributes = geometry.attributes;
  9884. // Updating index buffer in VAO now. See WebGLBindingStates.
  9885. for ( const name in geometryAttributes ) {
  9886. attributes.update( geometryAttributes[ name ], 34962 );
  9887. }
  9888. // morph targets
  9889. const morphAttributes = geometry.morphAttributes;
  9890. for ( const name in morphAttributes ) {
  9891. const array = morphAttributes[ name ];
  9892. for ( let i = 0, l = array.length; i < l; i ++ ) {
  9893. attributes.update( array[ i ], 34962 );
  9894. }
  9895. }
  9896. }
  9897. function updateWireframeAttribute( geometry ) {
  9898. const indices = [];
  9899. const geometryIndex = geometry.index;
  9900. const geometryPosition = geometry.attributes.position;
  9901. let version = 0;
  9902. if ( geometryIndex !== null ) {
  9903. const array = geometryIndex.array;
  9904. version = geometryIndex.version;
  9905. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  9906. const a = array[ i + 0 ];
  9907. const b = array[ i + 1 ];
  9908. const c = array[ i + 2 ];
  9909. indices.push( a, b, b, c, c, a );
  9910. }
  9911. } else {
  9912. const array = geometryPosition.array;
  9913. version = geometryPosition.version;
  9914. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  9915. const a = i + 0;
  9916. const b = i + 1;
  9917. const c = i + 2;
  9918. indices.push( a, b, b, c, c, a );
  9919. }
  9920. }
  9921. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  9922. attribute.version = version;
  9923. // Updating index buffer in VAO now. See WebGLBindingStates
  9924. //
  9925. const previousAttribute = wireframeAttributes.get( geometry );
  9926. if ( previousAttribute ) attributes.remove( previousAttribute );
  9927. //
  9928. wireframeAttributes.set( geometry, attribute );
  9929. }
  9930. function getWireframeAttribute( geometry ) {
  9931. const currentAttribute = wireframeAttributes.get( geometry );
  9932. if ( currentAttribute ) {
  9933. const geometryIndex = geometry.index;
  9934. if ( geometryIndex !== null ) {
  9935. // if the attribute is obsolete, create a new one
  9936. if ( currentAttribute.version < geometryIndex.version ) {
  9937. updateWireframeAttribute( geometry );
  9938. }
  9939. }
  9940. } else {
  9941. updateWireframeAttribute( geometry );
  9942. }
  9943. return wireframeAttributes.get( geometry );
  9944. }
  9945. return {
  9946. get: get,
  9947. update: update,
  9948. getWireframeAttribute: getWireframeAttribute
  9949. };
  9950. }
  9951. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  9952. const isWebGL2 = capabilities.isWebGL2;
  9953. let mode;
  9954. function setMode( value ) {
  9955. mode = value;
  9956. }
  9957. let type, bytesPerElement;
  9958. function setIndex( value ) {
  9959. type = value.type;
  9960. bytesPerElement = value.bytesPerElement;
  9961. }
  9962. function render( start, count ) {
  9963. gl.drawElements( mode, count, type, start * bytesPerElement );
  9964. info.update( count, mode, 1 );
  9965. }
  9966. function renderInstances( start, count, primcount ) {
  9967. if ( primcount === 0 ) return;
  9968. let extension, methodName;
  9969. if ( isWebGL2 ) {
  9970. extension = gl;
  9971. methodName = 'drawElementsInstanced';
  9972. } else {
  9973. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9974. methodName = 'drawElementsInstancedANGLE';
  9975. if ( extension === null ) {
  9976. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9977. return;
  9978. }
  9979. }
  9980. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  9981. info.update( count, mode, primcount );
  9982. }
  9983. //
  9984. this.setMode = setMode;
  9985. this.setIndex = setIndex;
  9986. this.render = render;
  9987. this.renderInstances = renderInstances;
  9988. }
  9989. function WebGLInfo( gl ) {
  9990. const memory = {
  9991. geometries: 0,
  9992. textures: 0
  9993. };
  9994. const render = {
  9995. frame: 0,
  9996. calls: 0,
  9997. triangles: 0,
  9998. points: 0,
  9999. lines: 0
  10000. };
  10001. function update( count, mode, instanceCount ) {
  10002. render.calls ++;
  10003. switch ( mode ) {
  10004. case 4:
  10005. render.triangles += instanceCount * ( count / 3 );
  10006. break;
  10007. case 1:
  10008. render.lines += instanceCount * ( count / 2 );
  10009. break;
  10010. case 3:
  10011. render.lines += instanceCount * ( count - 1 );
  10012. break;
  10013. case 2:
  10014. render.lines += instanceCount * count;
  10015. break;
  10016. case 0:
  10017. render.points += instanceCount * count;
  10018. break;
  10019. default:
  10020. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  10021. break;
  10022. }
  10023. }
  10024. function reset() {
  10025. render.frame ++;
  10026. render.calls = 0;
  10027. render.triangles = 0;
  10028. render.points = 0;
  10029. render.lines = 0;
  10030. }
  10031. return {
  10032. memory: memory,
  10033. render: render,
  10034. programs: null,
  10035. autoReset: true,
  10036. reset: reset,
  10037. update: update
  10038. };
  10039. }
  10040. function numericalSort( a, b ) {
  10041. return a[ 0 ] - b[ 0 ];
  10042. }
  10043. function absNumericalSort( a, b ) {
  10044. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  10045. }
  10046. function WebGLMorphtargets( gl, capabilities, textures ) {
  10047. const influencesList = {};
  10048. const morphInfluences = new Float32Array( 8 );
  10049. const morphTextures = new WeakMap();
  10050. const morph = new Vector4();
  10051. const workInfluences = [];
  10052. for ( let i = 0; i < 8; i ++ ) {
  10053. workInfluences[ i ] = [ i, 0 ];
  10054. }
  10055. function update( object, geometry, material, program ) {
  10056. const objectInfluences = object.morphTargetInfluences;
  10057. if ( capabilities.isWebGL2 === true ) {
  10058. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10059. // into an array of data textures. Each layer represents a single morph target.
  10060. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10061. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10062. let entry = morphTextures.get( geometry );
  10063. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10064. if ( entry !== undefined ) entry.texture.dispose();
  10065. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10066. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10067. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10068. const morphTargets = geometry.morphAttributes.position || [];
  10069. const morphNormals = geometry.morphAttributes.normal || [];
  10070. const morphColors = geometry.morphAttributes.color || [];
  10071. let vertexDataCount = 0;
  10072. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10073. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10074. if ( hasMorphColors === true ) vertexDataCount = 3;
  10075. let width = geometry.attributes.position.count * vertexDataCount;
  10076. let height = 1;
  10077. if ( width > capabilities.maxTextureSize ) {
  10078. height = Math.ceil( width / capabilities.maxTextureSize );
  10079. width = capabilities.maxTextureSize;
  10080. }
  10081. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10082. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10083. texture.type = FloatType;
  10084. texture.needsUpdate = true;
  10085. // fill buffer
  10086. const vertexDataStride = vertexDataCount * 4;
  10087. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10088. const morphTarget = morphTargets[ i ];
  10089. const morphNormal = morphNormals[ i ];
  10090. const morphColor = morphColors[ i ];
  10091. const offset = width * height * 4 * i;
  10092. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10093. const stride = j * vertexDataStride;
  10094. if ( hasMorphPosition === true ) {
  10095. morph.fromBufferAttribute( morphTarget, j );
  10096. buffer[ offset + stride + 0 ] = morph.x;
  10097. buffer[ offset + stride + 1 ] = morph.y;
  10098. buffer[ offset + stride + 2 ] = morph.z;
  10099. buffer[ offset + stride + 3 ] = 0;
  10100. }
  10101. if ( hasMorphNormals === true ) {
  10102. morph.fromBufferAttribute( morphNormal, j );
  10103. buffer[ offset + stride + 4 ] = morph.x;
  10104. buffer[ offset + stride + 5 ] = morph.y;
  10105. buffer[ offset + stride + 6 ] = morph.z;
  10106. buffer[ offset + stride + 7 ] = 0;
  10107. }
  10108. if ( hasMorphColors === true ) {
  10109. morph.fromBufferAttribute( morphColor, j );
  10110. buffer[ offset + stride + 8 ] = morph.x;
  10111. buffer[ offset + stride + 9 ] = morph.y;
  10112. buffer[ offset + stride + 10 ] = morph.z;
  10113. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  10114. }
  10115. }
  10116. }
  10117. entry = {
  10118. count: morphTargetsCount,
  10119. texture: texture,
  10120. size: new Vector2( width, height )
  10121. };
  10122. morphTextures.set( geometry, entry );
  10123. function disposeTexture() {
  10124. texture.dispose();
  10125. morphTextures.delete( geometry );
  10126. geometry.removeEventListener( 'dispose', disposeTexture );
  10127. }
  10128. geometry.addEventListener( 'dispose', disposeTexture );
  10129. }
  10130. //
  10131. let morphInfluencesSum = 0;
  10132. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10133. morphInfluencesSum += objectInfluences[ i ];
  10134. }
  10135. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10136. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10137. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  10138. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  10139. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  10140. } else {
  10141. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10142. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10143. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10144. let influences = influencesList[ geometry.id ];
  10145. if ( influences === undefined || influences.length !== length ) {
  10146. // initialise list
  10147. influences = [];
  10148. for ( let i = 0; i < length; i ++ ) {
  10149. influences[ i ] = [ i, 0 ];
  10150. }
  10151. influencesList[ geometry.id ] = influences;
  10152. }
  10153. // Collect influences
  10154. for ( let i = 0; i < length; i ++ ) {
  10155. const influence = influences[ i ];
  10156. influence[ 0 ] = i;
  10157. influence[ 1 ] = objectInfluences[ i ];
  10158. }
  10159. influences.sort( absNumericalSort );
  10160. for ( let i = 0; i < 8; i ++ ) {
  10161. if ( i < length && influences[ i ][ 1 ] ) {
  10162. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  10163. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  10164. } else {
  10165. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  10166. workInfluences[ i ][ 1 ] = 0;
  10167. }
  10168. }
  10169. workInfluences.sort( numericalSort );
  10170. const morphTargets = geometry.morphAttributes.position;
  10171. const morphNormals = geometry.morphAttributes.normal;
  10172. let morphInfluencesSum = 0;
  10173. for ( let i = 0; i < 8; i ++ ) {
  10174. const influence = workInfluences[ i ];
  10175. const index = influence[ 0 ];
  10176. const value = influence[ 1 ];
  10177. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  10178. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  10179. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  10180. }
  10181. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  10182. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  10183. }
  10184. morphInfluences[ i ] = value;
  10185. morphInfluencesSum += value;
  10186. } else {
  10187. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  10188. geometry.deleteAttribute( 'morphTarget' + i );
  10189. }
  10190. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  10191. geometry.deleteAttribute( 'morphNormal' + i );
  10192. }
  10193. morphInfluences[ i ] = 0;
  10194. }
  10195. }
  10196. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10197. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10198. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10199. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10200. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10201. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  10202. }
  10203. }
  10204. return {
  10205. update: update
  10206. };
  10207. }
  10208. function WebGLObjects( gl, geometries, attributes, info ) {
  10209. let updateMap = new WeakMap();
  10210. function update( object ) {
  10211. const frame = info.render.frame;
  10212. const geometry = object.geometry;
  10213. const buffergeometry = geometries.get( object, geometry );
  10214. // Update once per frame
  10215. if ( updateMap.get( buffergeometry ) !== frame ) {
  10216. geometries.update( buffergeometry );
  10217. updateMap.set( buffergeometry, frame );
  10218. }
  10219. if ( object.isInstancedMesh ) {
  10220. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10221. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10222. }
  10223. attributes.update( object.instanceMatrix, 34962 );
  10224. if ( object.instanceColor !== null ) {
  10225. attributes.update( object.instanceColor, 34962 );
  10226. }
  10227. }
  10228. return buffergeometry;
  10229. }
  10230. function dispose() {
  10231. updateMap = new WeakMap();
  10232. }
  10233. function onInstancedMeshDispose( event ) {
  10234. const instancedMesh = event.target;
  10235. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10236. attributes.remove( instancedMesh.instanceMatrix );
  10237. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10238. }
  10239. return {
  10240. update: update,
  10241. dispose: dispose
  10242. };
  10243. }
  10244. /**
  10245. * Uniforms of a program.
  10246. * Those form a tree structure with a special top-level container for the root,
  10247. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10248. *
  10249. *
  10250. * Properties of inner nodes including the top-level container:
  10251. *
  10252. * .seq - array of nested uniforms
  10253. * .map - nested uniforms by name
  10254. *
  10255. *
  10256. * Methods of all nodes except the top-level container:
  10257. *
  10258. * .setValue( gl, value, [textures] )
  10259. *
  10260. * uploads a uniform value(s)
  10261. * the 'textures' parameter is needed for sampler uniforms
  10262. *
  10263. *
  10264. * Static methods of the top-level container (textures factorizations):
  10265. *
  10266. * .upload( gl, seq, values, textures )
  10267. *
  10268. * sets uniforms in 'seq' to 'values[id].value'
  10269. *
  10270. * .seqWithValue( seq, values ) : filteredSeq
  10271. *
  10272. * filters 'seq' entries with corresponding entry in values
  10273. *
  10274. *
  10275. * Methods of the top-level container (textures factorizations):
  10276. *
  10277. * .setValue( gl, name, value, textures )
  10278. *
  10279. * sets uniform with name 'name' to 'value'
  10280. *
  10281. * .setOptional( gl, obj, prop )
  10282. *
  10283. * like .set for an optional property of the object
  10284. *
  10285. */
  10286. const emptyTexture = /*@__PURE__*/ new Texture();
  10287. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  10288. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  10289. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  10290. // --- Utilities ---
  10291. // Array Caches (provide typed arrays for temporary by size)
  10292. const arrayCacheF32 = [];
  10293. const arrayCacheI32 = [];
  10294. // Float32Array caches used for uploading Matrix uniforms
  10295. const mat4array = new Float32Array( 16 );
  10296. const mat3array = new Float32Array( 9 );
  10297. const mat2array = new Float32Array( 4 );
  10298. // Flattening for arrays of vectors and matrices
  10299. function flatten( array, nBlocks, blockSize ) {
  10300. const firstElem = array[ 0 ];
  10301. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10302. // unoptimized: ! isNaN( firstElem )
  10303. // see http://jacksondunstan.com/articles/983
  10304. const n = nBlocks * blockSize;
  10305. let r = arrayCacheF32[ n ];
  10306. if ( r === undefined ) {
  10307. r = new Float32Array( n );
  10308. arrayCacheF32[ n ] = r;
  10309. }
  10310. if ( nBlocks !== 0 ) {
  10311. firstElem.toArray( r, 0 );
  10312. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10313. offset += blockSize;
  10314. array[ i ].toArray( r, offset );
  10315. }
  10316. }
  10317. return r;
  10318. }
  10319. function arraysEqual( a, b ) {
  10320. if ( a.length !== b.length ) return false;
  10321. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10322. if ( a[ i ] !== b[ i ] ) return false;
  10323. }
  10324. return true;
  10325. }
  10326. function copyArray( a, b ) {
  10327. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10328. a[ i ] = b[ i ];
  10329. }
  10330. }
  10331. // Texture unit allocation
  10332. function allocTexUnits( textures, n ) {
  10333. let r = arrayCacheI32[ n ];
  10334. if ( r === undefined ) {
  10335. r = new Int32Array( n );
  10336. arrayCacheI32[ n ] = r;
  10337. }
  10338. for ( let i = 0; i !== n; ++ i ) {
  10339. r[ i ] = textures.allocateTextureUnit();
  10340. }
  10341. return r;
  10342. }
  10343. // --- Setters ---
  10344. // Note: Defining these methods externally, because they come in a bunch
  10345. // and this way their names minify.
  10346. // Single scalar
  10347. function setValueV1f( gl, v ) {
  10348. const cache = this.cache;
  10349. if ( cache[ 0 ] === v ) return;
  10350. gl.uniform1f( this.addr, v );
  10351. cache[ 0 ] = v;
  10352. }
  10353. // Single float vector (from flat array or THREE.VectorN)
  10354. function setValueV2f( gl, v ) {
  10355. const cache = this.cache;
  10356. if ( v.x !== undefined ) {
  10357. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10358. gl.uniform2f( this.addr, v.x, v.y );
  10359. cache[ 0 ] = v.x;
  10360. cache[ 1 ] = v.y;
  10361. }
  10362. } else {
  10363. if ( arraysEqual( cache, v ) ) return;
  10364. gl.uniform2fv( this.addr, v );
  10365. copyArray( cache, v );
  10366. }
  10367. }
  10368. function setValueV3f( gl, v ) {
  10369. const cache = this.cache;
  10370. if ( v.x !== undefined ) {
  10371. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10372. gl.uniform3f( this.addr, v.x, v.y, v.z );
  10373. cache[ 0 ] = v.x;
  10374. cache[ 1 ] = v.y;
  10375. cache[ 2 ] = v.z;
  10376. }
  10377. } else if ( v.r !== undefined ) {
  10378. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  10379. gl.uniform3f( this.addr, v.r, v.g, v.b );
  10380. cache[ 0 ] = v.r;
  10381. cache[ 1 ] = v.g;
  10382. cache[ 2 ] = v.b;
  10383. }
  10384. } else {
  10385. if ( arraysEqual( cache, v ) ) return;
  10386. gl.uniform3fv( this.addr, v );
  10387. copyArray( cache, v );
  10388. }
  10389. }
  10390. function setValueV4f( gl, v ) {
  10391. const cache = this.cache;
  10392. if ( v.x !== undefined ) {
  10393. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10394. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  10395. cache[ 0 ] = v.x;
  10396. cache[ 1 ] = v.y;
  10397. cache[ 2 ] = v.z;
  10398. cache[ 3 ] = v.w;
  10399. }
  10400. } else {
  10401. if ( arraysEqual( cache, v ) ) return;
  10402. gl.uniform4fv( this.addr, v );
  10403. copyArray( cache, v );
  10404. }
  10405. }
  10406. // Single matrix (from flat array or THREE.MatrixN)
  10407. function setValueM2( gl, v ) {
  10408. const cache = this.cache;
  10409. const elements = v.elements;
  10410. if ( elements === undefined ) {
  10411. if ( arraysEqual( cache, v ) ) return;
  10412. gl.uniformMatrix2fv( this.addr, false, v );
  10413. copyArray( cache, v );
  10414. } else {
  10415. if ( arraysEqual( cache, elements ) ) return;
  10416. mat2array.set( elements );
  10417. gl.uniformMatrix2fv( this.addr, false, mat2array );
  10418. copyArray( cache, elements );
  10419. }
  10420. }
  10421. function setValueM3( gl, v ) {
  10422. const cache = this.cache;
  10423. const elements = v.elements;
  10424. if ( elements === undefined ) {
  10425. if ( arraysEqual( cache, v ) ) return;
  10426. gl.uniformMatrix3fv( this.addr, false, v );
  10427. copyArray( cache, v );
  10428. } else {
  10429. if ( arraysEqual( cache, elements ) ) return;
  10430. mat3array.set( elements );
  10431. gl.uniformMatrix3fv( this.addr, false, mat3array );
  10432. copyArray( cache, elements );
  10433. }
  10434. }
  10435. function setValueM4( gl, v ) {
  10436. const cache = this.cache;
  10437. const elements = v.elements;
  10438. if ( elements === undefined ) {
  10439. if ( arraysEqual( cache, v ) ) return;
  10440. gl.uniformMatrix4fv( this.addr, false, v );
  10441. copyArray( cache, v );
  10442. } else {
  10443. if ( arraysEqual( cache, elements ) ) return;
  10444. mat4array.set( elements );
  10445. gl.uniformMatrix4fv( this.addr, false, mat4array );
  10446. copyArray( cache, elements );
  10447. }
  10448. }
  10449. // Single integer / boolean
  10450. function setValueV1i( gl, v ) {
  10451. const cache = this.cache;
  10452. if ( cache[ 0 ] === v ) return;
  10453. gl.uniform1i( this.addr, v );
  10454. cache[ 0 ] = v;
  10455. }
  10456. // Single integer / boolean vector (from flat array or THREE.VectorN)
  10457. function setValueV2i( gl, v ) {
  10458. const cache = this.cache;
  10459. if ( v.x !== undefined ) {
  10460. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10461. gl.uniform2i( this.addr, v.x, v.y );
  10462. cache[ 0 ] = v.x;
  10463. cache[ 1 ] = v.y;
  10464. }
  10465. } else {
  10466. if ( arraysEqual( cache, v ) ) return;
  10467. gl.uniform2iv( this.addr, v );
  10468. copyArray( cache, v );
  10469. }
  10470. }
  10471. function setValueV3i( gl, v ) {
  10472. const cache = this.cache;
  10473. if ( v.x !== undefined ) {
  10474. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10475. gl.uniform3i( this.addr, v.x, v.y, v.z );
  10476. cache[ 0 ] = v.x;
  10477. cache[ 1 ] = v.y;
  10478. cache[ 2 ] = v.z;
  10479. }
  10480. } else {
  10481. if ( arraysEqual( cache, v ) ) return;
  10482. gl.uniform3iv( this.addr, v );
  10483. copyArray( cache, v );
  10484. }
  10485. }
  10486. function setValueV4i( gl, v ) {
  10487. const cache = this.cache;
  10488. if ( v.x !== undefined ) {
  10489. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10490. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  10491. cache[ 0 ] = v.x;
  10492. cache[ 1 ] = v.y;
  10493. cache[ 2 ] = v.z;
  10494. cache[ 3 ] = v.w;
  10495. }
  10496. } else {
  10497. if ( arraysEqual( cache, v ) ) return;
  10498. gl.uniform4iv( this.addr, v );
  10499. copyArray( cache, v );
  10500. }
  10501. }
  10502. // Single unsigned integer
  10503. function setValueV1ui( gl, v ) {
  10504. const cache = this.cache;
  10505. if ( cache[ 0 ] === v ) return;
  10506. gl.uniform1ui( this.addr, v );
  10507. cache[ 0 ] = v;
  10508. }
  10509. // Single unsigned integer vector (from flat array or THREE.VectorN)
  10510. function setValueV2ui( gl, v ) {
  10511. const cache = this.cache;
  10512. if ( v.x !== undefined ) {
  10513. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10514. gl.uniform2ui( this.addr, v.x, v.y );
  10515. cache[ 0 ] = v.x;
  10516. cache[ 1 ] = v.y;
  10517. }
  10518. } else {
  10519. if ( arraysEqual( cache, v ) ) return;
  10520. gl.uniform2uiv( this.addr, v );
  10521. copyArray( cache, v );
  10522. }
  10523. }
  10524. function setValueV3ui( gl, v ) {
  10525. const cache = this.cache;
  10526. if ( v.x !== undefined ) {
  10527. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10528. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  10529. cache[ 0 ] = v.x;
  10530. cache[ 1 ] = v.y;
  10531. cache[ 2 ] = v.z;
  10532. }
  10533. } else {
  10534. if ( arraysEqual( cache, v ) ) return;
  10535. gl.uniform3uiv( this.addr, v );
  10536. copyArray( cache, v );
  10537. }
  10538. }
  10539. function setValueV4ui( gl, v ) {
  10540. const cache = this.cache;
  10541. if ( v.x !== undefined ) {
  10542. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10543. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  10544. cache[ 0 ] = v.x;
  10545. cache[ 1 ] = v.y;
  10546. cache[ 2 ] = v.z;
  10547. cache[ 3 ] = v.w;
  10548. }
  10549. } else {
  10550. if ( arraysEqual( cache, v ) ) return;
  10551. gl.uniform4uiv( this.addr, v );
  10552. copyArray( cache, v );
  10553. }
  10554. }
  10555. // Single texture (2D / Cube)
  10556. function setValueT1( gl, v, textures ) {
  10557. const cache = this.cache;
  10558. const unit = textures.allocateTextureUnit();
  10559. if ( cache[ 0 ] !== unit ) {
  10560. gl.uniform1i( this.addr, unit );
  10561. cache[ 0 ] = unit;
  10562. }
  10563. textures.setTexture2D( v || emptyTexture, unit );
  10564. }
  10565. function setValueT3D1( gl, v, textures ) {
  10566. const cache = this.cache;
  10567. const unit = textures.allocateTextureUnit();
  10568. if ( cache[ 0 ] !== unit ) {
  10569. gl.uniform1i( this.addr, unit );
  10570. cache[ 0 ] = unit;
  10571. }
  10572. textures.setTexture3D( v || empty3dTexture, unit );
  10573. }
  10574. function setValueT6( gl, v, textures ) {
  10575. const cache = this.cache;
  10576. const unit = textures.allocateTextureUnit();
  10577. if ( cache[ 0 ] !== unit ) {
  10578. gl.uniform1i( this.addr, unit );
  10579. cache[ 0 ] = unit;
  10580. }
  10581. textures.setTextureCube( v || emptyCubeTexture, unit );
  10582. }
  10583. function setValueT2DArray1( gl, v, textures ) {
  10584. const cache = this.cache;
  10585. const unit = textures.allocateTextureUnit();
  10586. if ( cache[ 0 ] !== unit ) {
  10587. gl.uniform1i( this.addr, unit );
  10588. cache[ 0 ] = unit;
  10589. }
  10590. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  10591. }
  10592. // Helper to pick the right setter for the singular case
  10593. function getSingularSetter( type ) {
  10594. switch ( type ) {
  10595. case 0x1406: return setValueV1f; // FLOAT
  10596. case 0x8b50: return setValueV2f; // _VEC2
  10597. case 0x8b51: return setValueV3f; // _VEC3
  10598. case 0x8b52: return setValueV4f; // _VEC4
  10599. case 0x8b5a: return setValueM2; // _MAT2
  10600. case 0x8b5b: return setValueM3; // _MAT3
  10601. case 0x8b5c: return setValueM4; // _MAT4
  10602. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  10603. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  10604. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  10605. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  10606. case 0x1405: return setValueV1ui; // UINT
  10607. case 0x8dc6: return setValueV2ui; // _VEC2
  10608. case 0x8dc7: return setValueV3ui; // _VEC3
  10609. case 0x8dc8: return setValueV4ui; // _VEC4
  10610. case 0x8b5e: // SAMPLER_2D
  10611. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10612. case 0x8dca: // INT_SAMPLER_2D
  10613. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10614. case 0x8b62: // SAMPLER_2D_SHADOW
  10615. return setValueT1;
  10616. case 0x8b5f: // SAMPLER_3D
  10617. case 0x8dcb: // INT_SAMPLER_3D
  10618. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10619. return setValueT3D1;
  10620. case 0x8b60: // SAMPLER_CUBE
  10621. case 0x8dcc: // INT_SAMPLER_CUBE
  10622. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10623. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10624. return setValueT6;
  10625. case 0x8dc1: // SAMPLER_2D_ARRAY
  10626. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10627. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10628. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10629. return setValueT2DArray1;
  10630. }
  10631. }
  10632. // Array of scalars
  10633. function setValueV1fArray( gl, v ) {
  10634. gl.uniform1fv( this.addr, v );
  10635. }
  10636. // Array of vectors (from flat array or array of THREE.VectorN)
  10637. function setValueV2fArray( gl, v ) {
  10638. const data = flatten( v, this.size, 2 );
  10639. gl.uniform2fv( this.addr, data );
  10640. }
  10641. function setValueV3fArray( gl, v ) {
  10642. const data = flatten( v, this.size, 3 );
  10643. gl.uniform3fv( this.addr, data );
  10644. }
  10645. function setValueV4fArray( gl, v ) {
  10646. const data = flatten( v, this.size, 4 );
  10647. gl.uniform4fv( this.addr, data );
  10648. }
  10649. // Array of matrices (from flat array or array of THREE.MatrixN)
  10650. function setValueM2Array( gl, v ) {
  10651. const data = flatten( v, this.size, 4 );
  10652. gl.uniformMatrix2fv( this.addr, false, data );
  10653. }
  10654. function setValueM3Array( gl, v ) {
  10655. const data = flatten( v, this.size, 9 );
  10656. gl.uniformMatrix3fv( this.addr, false, data );
  10657. }
  10658. function setValueM4Array( gl, v ) {
  10659. const data = flatten( v, this.size, 16 );
  10660. gl.uniformMatrix4fv( this.addr, false, data );
  10661. }
  10662. // Array of integer / boolean
  10663. function setValueV1iArray( gl, v ) {
  10664. gl.uniform1iv( this.addr, v );
  10665. }
  10666. // Array of integer / boolean vectors (from flat array)
  10667. function setValueV2iArray( gl, v ) {
  10668. gl.uniform2iv( this.addr, v );
  10669. }
  10670. function setValueV3iArray( gl, v ) {
  10671. gl.uniform3iv( this.addr, v );
  10672. }
  10673. function setValueV4iArray( gl, v ) {
  10674. gl.uniform4iv( this.addr, v );
  10675. }
  10676. // Array of unsigned integer
  10677. function setValueV1uiArray( gl, v ) {
  10678. gl.uniform1uiv( this.addr, v );
  10679. }
  10680. // Array of unsigned integer vectors (from flat array)
  10681. function setValueV2uiArray( gl, v ) {
  10682. gl.uniform2uiv( this.addr, v );
  10683. }
  10684. function setValueV3uiArray( gl, v ) {
  10685. gl.uniform3uiv( this.addr, v );
  10686. }
  10687. function setValueV4uiArray( gl, v ) {
  10688. gl.uniform4uiv( this.addr, v );
  10689. }
  10690. // Array of textures (2D / 3D / Cube / 2DArray)
  10691. function setValueT1Array( gl, v, textures ) {
  10692. const cache = this.cache;
  10693. const n = v.length;
  10694. const units = allocTexUnits( textures, n );
  10695. if ( ! arraysEqual( cache, units ) ) {
  10696. gl.uniform1iv( this.addr, units );
  10697. copyArray( cache, units );
  10698. }
  10699. for ( let i = 0; i !== n; ++ i ) {
  10700. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  10701. }
  10702. }
  10703. function setValueT3DArray( gl, v, textures ) {
  10704. const cache = this.cache;
  10705. const n = v.length;
  10706. const units = allocTexUnits( textures, n );
  10707. if ( ! arraysEqual( cache, units ) ) {
  10708. gl.uniform1iv( this.addr, units );
  10709. copyArray( cache, units );
  10710. }
  10711. for ( let i = 0; i !== n; ++ i ) {
  10712. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  10713. }
  10714. }
  10715. function setValueT6Array( gl, v, textures ) {
  10716. const cache = this.cache;
  10717. const n = v.length;
  10718. const units = allocTexUnits( textures, n );
  10719. if ( ! arraysEqual( cache, units ) ) {
  10720. gl.uniform1iv( this.addr, units );
  10721. copyArray( cache, units );
  10722. }
  10723. for ( let i = 0; i !== n; ++ i ) {
  10724. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  10725. }
  10726. }
  10727. function setValueT2DArrayArray( gl, v, textures ) {
  10728. const cache = this.cache;
  10729. const n = v.length;
  10730. const units = allocTexUnits( textures, n );
  10731. if ( ! arraysEqual( cache, units ) ) {
  10732. gl.uniform1iv( this.addr, units );
  10733. copyArray( cache, units );
  10734. }
  10735. for ( let i = 0; i !== n; ++ i ) {
  10736. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  10737. }
  10738. }
  10739. // Helper to pick the right setter for a pure (bottom-level) array
  10740. function getPureArraySetter( type ) {
  10741. switch ( type ) {
  10742. case 0x1406: return setValueV1fArray; // FLOAT
  10743. case 0x8b50: return setValueV2fArray; // _VEC2
  10744. case 0x8b51: return setValueV3fArray; // _VEC3
  10745. case 0x8b52: return setValueV4fArray; // _VEC4
  10746. case 0x8b5a: return setValueM2Array; // _MAT2
  10747. case 0x8b5b: return setValueM3Array; // _MAT3
  10748. case 0x8b5c: return setValueM4Array; // _MAT4
  10749. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  10750. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  10751. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  10752. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  10753. case 0x1405: return setValueV1uiArray; // UINT
  10754. case 0x8dc6: return setValueV2uiArray; // _VEC2
  10755. case 0x8dc7: return setValueV3uiArray; // _VEC3
  10756. case 0x8dc8: return setValueV4uiArray; // _VEC4
  10757. case 0x8b5e: // SAMPLER_2D
  10758. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10759. case 0x8dca: // INT_SAMPLER_2D
  10760. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10761. case 0x8b62: // SAMPLER_2D_SHADOW
  10762. return setValueT1Array;
  10763. case 0x8b5f: // SAMPLER_3D
  10764. case 0x8dcb: // INT_SAMPLER_3D
  10765. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10766. return setValueT3DArray;
  10767. case 0x8b60: // SAMPLER_CUBE
  10768. case 0x8dcc: // INT_SAMPLER_CUBE
  10769. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10770. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10771. return setValueT6Array;
  10772. case 0x8dc1: // SAMPLER_2D_ARRAY
  10773. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10774. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10775. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10776. return setValueT2DArrayArray;
  10777. }
  10778. }
  10779. // --- Uniform Classes ---
  10780. class SingleUniform {
  10781. constructor( id, activeInfo, addr ) {
  10782. this.id = id;
  10783. this.addr = addr;
  10784. this.cache = [];
  10785. this.setValue = getSingularSetter( activeInfo.type );
  10786. // this.path = activeInfo.name; // DEBUG
  10787. }
  10788. }
  10789. class PureArrayUniform {
  10790. constructor( id, activeInfo, addr ) {
  10791. this.id = id;
  10792. this.addr = addr;
  10793. this.cache = [];
  10794. this.size = activeInfo.size;
  10795. this.setValue = getPureArraySetter( activeInfo.type );
  10796. // this.path = activeInfo.name; // DEBUG
  10797. }
  10798. }
  10799. class StructuredUniform {
  10800. constructor( id ) {
  10801. this.id = id;
  10802. this.seq = [];
  10803. this.map = {};
  10804. }
  10805. setValue( gl, value, textures ) {
  10806. const seq = this.seq;
  10807. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10808. const u = seq[ i ];
  10809. u.setValue( gl, value[ u.id ], textures );
  10810. }
  10811. }
  10812. }
  10813. // --- Top-level ---
  10814. // Parser - builds up the property tree from the path strings
  10815. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  10816. // extracts
  10817. // - the identifier (member name or array index)
  10818. // - followed by an optional right bracket (found when array index)
  10819. // - followed by an optional left bracket or dot (type of subscript)
  10820. //
  10821. // Note: These portions can be read in a non-overlapping fashion and
  10822. // allow straightforward parsing of the hierarchy that WebGL encodes
  10823. // in the uniform names.
  10824. function addUniform( container, uniformObject ) {
  10825. container.seq.push( uniformObject );
  10826. container.map[ uniformObject.id ] = uniformObject;
  10827. }
  10828. function parseUniform( activeInfo, addr, container ) {
  10829. const path = activeInfo.name,
  10830. pathLength = path.length;
  10831. // reset RegExp object, because of the early exit of a previous run
  10832. RePathPart.lastIndex = 0;
  10833. while ( true ) {
  10834. const match = RePathPart.exec( path ),
  10835. matchEnd = RePathPart.lastIndex;
  10836. let id = match[ 1 ];
  10837. const idIsIndex = match[ 2 ] === ']',
  10838. subscript = match[ 3 ];
  10839. if ( idIsIndex ) id = id | 0; // convert to integer
  10840. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  10841. // bare name or "pure" bottom-level array "[0]" suffix
  10842. addUniform( container, subscript === undefined ?
  10843. new SingleUniform( id, activeInfo, addr ) :
  10844. new PureArrayUniform( id, activeInfo, addr ) );
  10845. break;
  10846. } else {
  10847. // step into inner node / create it in case it doesn't exist
  10848. const map = container.map;
  10849. let next = map[ id ];
  10850. if ( next === undefined ) {
  10851. next = new StructuredUniform( id );
  10852. addUniform( container, next );
  10853. }
  10854. container = next;
  10855. }
  10856. }
  10857. }
  10858. // Root Container
  10859. class WebGLUniforms {
  10860. constructor( gl, program ) {
  10861. this.seq = [];
  10862. this.map = {};
  10863. const n = gl.getProgramParameter( program, 35718 );
  10864. for ( let i = 0; i < n; ++ i ) {
  10865. const info = gl.getActiveUniform( program, i ),
  10866. addr = gl.getUniformLocation( program, info.name );
  10867. parseUniform( info, addr, this );
  10868. }
  10869. }
  10870. setValue( gl, name, value, textures ) {
  10871. const u = this.map[ name ];
  10872. if ( u !== undefined ) u.setValue( gl, value, textures );
  10873. }
  10874. setOptional( gl, object, name ) {
  10875. const v = object[ name ];
  10876. if ( v !== undefined ) this.setValue( gl, name, v );
  10877. }
  10878. static upload( gl, seq, values, textures ) {
  10879. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10880. const u = seq[ i ],
  10881. v = values[ u.id ];
  10882. if ( v.needsUpdate !== false ) {
  10883. // note: always updating when .needsUpdate is undefined
  10884. u.setValue( gl, v.value, textures );
  10885. }
  10886. }
  10887. }
  10888. static seqWithValue( seq, values ) {
  10889. const r = [];
  10890. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10891. const u = seq[ i ];
  10892. if ( u.id in values ) r.push( u );
  10893. }
  10894. return r;
  10895. }
  10896. }
  10897. function WebGLShader( gl, type, string ) {
  10898. const shader = gl.createShader( type );
  10899. gl.shaderSource( shader, string );
  10900. gl.compileShader( shader );
  10901. return shader;
  10902. }
  10903. let programIdCount = 0;
  10904. function handleSource( string, errorLine ) {
  10905. const lines = string.split( '\n' );
  10906. const lines2 = [];
  10907. const from = Math.max( errorLine - 6, 0 );
  10908. const to = Math.min( errorLine + 6, lines.length );
  10909. for ( let i = from; i < to; i ++ ) {
  10910. const line = i + 1;
  10911. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  10912. }
  10913. return lines2.join( '\n' );
  10914. }
  10915. function getEncodingComponents( encoding ) {
  10916. switch ( encoding ) {
  10917. case LinearEncoding:
  10918. return [ 'Linear', '( value )' ];
  10919. case sRGBEncoding:
  10920. return [ 'sRGB', '( value )' ];
  10921. default:
  10922. console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding );
  10923. return [ 'Linear', '( value )' ];
  10924. }
  10925. }
  10926. function getShaderErrors( gl, shader, type ) {
  10927. const status = gl.getShaderParameter( shader, 35713 );
  10928. const errors = gl.getShaderInfoLog( shader ).trim();
  10929. if ( status && errors === '' ) return '';
  10930. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  10931. if ( errorMatches ) {
  10932. // --enable-privileged-webgl-extension
  10933. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10934. const errorLine = parseInt( errorMatches[ 1 ] );
  10935. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  10936. } else {
  10937. return errors;
  10938. }
  10939. }
  10940. function getTexelEncodingFunction( functionName, encoding ) {
  10941. const components = getEncodingComponents( encoding );
  10942. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  10943. }
  10944. function getToneMappingFunction( functionName, toneMapping ) {
  10945. let toneMappingName;
  10946. switch ( toneMapping ) {
  10947. case LinearToneMapping:
  10948. toneMappingName = 'Linear';
  10949. break;
  10950. case ReinhardToneMapping:
  10951. toneMappingName = 'Reinhard';
  10952. break;
  10953. case CineonToneMapping:
  10954. toneMappingName = 'OptimizedCineon';
  10955. break;
  10956. case ACESFilmicToneMapping:
  10957. toneMappingName = 'ACESFilmic';
  10958. break;
  10959. case CustomToneMapping:
  10960. toneMappingName = 'Custom';
  10961. break;
  10962. default:
  10963. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  10964. toneMappingName = 'Linear';
  10965. }
  10966. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  10967. }
  10968. function generateExtensions( parameters ) {
  10969. const chunks = [
  10970. ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  10971. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  10972. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  10973. ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  10974. ];
  10975. return chunks.filter( filterEmptyLine ).join( '\n' );
  10976. }
  10977. function generateDefines( defines ) {
  10978. const chunks = [];
  10979. for ( const name in defines ) {
  10980. const value = defines[ name ];
  10981. if ( value === false ) continue;
  10982. chunks.push( '#define ' + name + ' ' + value );
  10983. }
  10984. return chunks.join( '\n' );
  10985. }
  10986. function fetchAttributeLocations( gl, program ) {
  10987. const attributes = {};
  10988. const n = gl.getProgramParameter( program, 35721 );
  10989. for ( let i = 0; i < n; i ++ ) {
  10990. const info = gl.getActiveAttrib( program, i );
  10991. const name = info.name;
  10992. let locationSize = 1;
  10993. if ( info.type === 35674 ) locationSize = 2;
  10994. if ( info.type === 35675 ) locationSize = 3;
  10995. if ( info.type === 35676 ) locationSize = 4;
  10996. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  10997. attributes[ name ] = {
  10998. type: info.type,
  10999. location: gl.getAttribLocation( program, name ),
  11000. locationSize: locationSize
  11001. };
  11002. }
  11003. return attributes;
  11004. }
  11005. function filterEmptyLine( string ) {
  11006. return string !== '';
  11007. }
  11008. function replaceLightNums( string, parameters ) {
  11009. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  11010. return string
  11011. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  11012. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  11013. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  11014. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  11015. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  11016. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  11017. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  11018. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  11019. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  11020. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  11021. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  11022. }
  11023. function replaceClippingPlaneNums( string, parameters ) {
  11024. return string
  11025. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  11026. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  11027. }
  11028. // Resolve Includes
  11029. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11030. function resolveIncludes( string ) {
  11031. return string.replace( includePattern, includeReplacer );
  11032. }
  11033. function includeReplacer( match, include ) {
  11034. const string = ShaderChunk[ include ];
  11035. if ( string === undefined ) {
  11036. throw new Error( 'Can not resolve #include <' + include + '>' );
  11037. }
  11038. return resolveIncludes( string );
  11039. }
  11040. // Unroll Loops
  11041. 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;
  11042. function unrollLoops( string ) {
  11043. return string.replace( unrollLoopPattern, loopReplacer );
  11044. }
  11045. function loopReplacer( match, start, end, snippet ) {
  11046. let string = '';
  11047. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  11048. string += snippet
  11049. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  11050. .replace( /UNROLLED_LOOP_INDEX/g, i );
  11051. }
  11052. return string;
  11053. }
  11054. //
  11055. function generatePrecision( parameters ) {
  11056. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11057. if ( parameters.precision === 'highp' ) {
  11058. precisionstring += '\n#define HIGH_PRECISION';
  11059. } else if ( parameters.precision === 'mediump' ) {
  11060. precisionstring += '\n#define MEDIUM_PRECISION';
  11061. } else if ( parameters.precision === 'lowp' ) {
  11062. precisionstring += '\n#define LOW_PRECISION';
  11063. }
  11064. return precisionstring;
  11065. }
  11066. function generateShadowMapTypeDefine( parameters ) {
  11067. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11068. if ( parameters.shadowMapType === PCFShadowMap ) {
  11069. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11070. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  11071. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11072. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  11073. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11074. }
  11075. return shadowMapTypeDefine;
  11076. }
  11077. function generateEnvMapTypeDefine( parameters ) {
  11078. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11079. if ( parameters.envMap ) {
  11080. switch ( parameters.envMapMode ) {
  11081. case CubeReflectionMapping:
  11082. case CubeRefractionMapping:
  11083. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11084. break;
  11085. case CubeUVReflectionMapping:
  11086. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11087. break;
  11088. }
  11089. }
  11090. return envMapTypeDefine;
  11091. }
  11092. function generateEnvMapModeDefine( parameters ) {
  11093. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11094. if ( parameters.envMap ) {
  11095. switch ( parameters.envMapMode ) {
  11096. case CubeRefractionMapping:
  11097. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11098. break;
  11099. }
  11100. }
  11101. return envMapModeDefine;
  11102. }
  11103. function generateEnvMapBlendingDefine( parameters ) {
  11104. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11105. if ( parameters.envMap ) {
  11106. switch ( parameters.combine ) {
  11107. case MultiplyOperation:
  11108. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11109. break;
  11110. case MixOperation:
  11111. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11112. break;
  11113. case AddOperation:
  11114. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11115. break;
  11116. }
  11117. }
  11118. return envMapBlendingDefine;
  11119. }
  11120. function generateCubeUVSize( parameters ) {
  11121. const imageHeight = parameters.envMapCubeUVHeight;
  11122. if ( imageHeight === null ) return null;
  11123. const maxMip = Math.log2( imageHeight ) - 2;
  11124. const texelHeight = 1.0 / imageHeight;
  11125. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  11126. return { texelWidth, texelHeight, maxMip };
  11127. }
  11128. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  11129. // TODO Send this event to Three.js DevTools
  11130. // console.log( 'WebGLProgram', cacheKey );
  11131. const gl = renderer.getContext();
  11132. const defines = parameters.defines;
  11133. let vertexShader = parameters.vertexShader;
  11134. let fragmentShader = parameters.fragmentShader;
  11135. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  11136. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  11137. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  11138. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  11139. const envMapCubeUVSize = generateCubeUVSize( parameters );
  11140. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  11141. const customDefines = generateDefines( defines );
  11142. const program = gl.createProgram();
  11143. let prefixVertex, prefixFragment;
  11144. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11145. if ( parameters.isRawShaderMaterial ) {
  11146. prefixVertex = [
  11147. customDefines
  11148. ].filter( filterEmptyLine ).join( '\n' );
  11149. if ( prefixVertex.length > 0 ) {
  11150. prefixVertex += '\n';
  11151. }
  11152. prefixFragment = [
  11153. customExtensions,
  11154. customDefines
  11155. ].filter( filterEmptyLine ).join( '\n' );
  11156. if ( prefixFragment.length > 0 ) {
  11157. prefixFragment += '\n';
  11158. }
  11159. } else {
  11160. prefixVertex = [
  11161. generatePrecision( parameters ),
  11162. '#define SHADER_NAME ' + parameters.shaderName,
  11163. customDefines,
  11164. parameters.instancing ? '#define USE_INSTANCING' : '',
  11165. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  11166. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  11167. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11168. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11169. parameters.map ? '#define USE_MAP' : '',
  11170. parameters.envMap ? '#define USE_ENVMAP' : '',
  11171. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11172. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11173. parameters.aoMap ? '#define USE_AOMAP' : '',
  11174. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11175. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11176. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11177. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11178. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11179. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11180. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11181. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11182. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11183. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11184. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  11185. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11186. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  11187. parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '',
  11188. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11189. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11190. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11191. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11192. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11193. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11194. parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '',
  11195. parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '',
  11196. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11197. parameters.vertexColors ? '#define USE_COLOR' : '',
  11198. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11199. parameters.vertexUvs ? '#define USE_UV' : '',
  11200. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11201. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11202. parameters.skinning ? '#define USE_SKINNING' : '',
  11203. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  11204. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  11205. ( parameters.morphColors && parameters.isWebGL2 ) ? '#define USE_MORPHCOLORS' : '',
  11206. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE' : '',
  11207. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  11208. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  11209. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11210. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11211. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11212. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11213. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  11214. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11215. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11216. 'uniform mat4 modelMatrix;',
  11217. 'uniform mat4 modelViewMatrix;',
  11218. 'uniform mat4 projectionMatrix;',
  11219. 'uniform mat4 viewMatrix;',
  11220. 'uniform mat3 normalMatrix;',
  11221. 'uniform vec3 cameraPosition;',
  11222. 'uniform bool isOrthographic;',
  11223. '#ifdef USE_INSTANCING',
  11224. ' attribute mat4 instanceMatrix;',
  11225. '#endif',
  11226. '#ifdef USE_INSTANCING_COLOR',
  11227. ' attribute vec3 instanceColor;',
  11228. '#endif',
  11229. 'attribute vec3 position;',
  11230. 'attribute vec3 normal;',
  11231. 'attribute vec2 uv;',
  11232. '#ifdef USE_TANGENT',
  11233. ' attribute vec4 tangent;',
  11234. '#endif',
  11235. '#if defined( USE_COLOR_ALPHA )',
  11236. ' attribute vec4 color;',
  11237. '#elif defined( USE_COLOR )',
  11238. ' attribute vec3 color;',
  11239. '#endif',
  11240. '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )',
  11241. ' attribute vec3 morphTarget0;',
  11242. ' attribute vec3 morphTarget1;',
  11243. ' attribute vec3 morphTarget2;',
  11244. ' attribute vec3 morphTarget3;',
  11245. ' #ifdef USE_MORPHNORMALS',
  11246. ' attribute vec3 morphNormal0;',
  11247. ' attribute vec3 morphNormal1;',
  11248. ' attribute vec3 morphNormal2;',
  11249. ' attribute vec3 morphNormal3;',
  11250. ' #else',
  11251. ' attribute vec3 morphTarget4;',
  11252. ' attribute vec3 morphTarget5;',
  11253. ' attribute vec3 morphTarget6;',
  11254. ' attribute vec3 morphTarget7;',
  11255. ' #endif',
  11256. '#endif',
  11257. '#ifdef USE_SKINNING',
  11258. ' attribute vec4 skinIndex;',
  11259. ' attribute vec4 skinWeight;',
  11260. '#endif',
  11261. '\n'
  11262. ].filter( filterEmptyLine ).join( '\n' );
  11263. prefixFragment = [
  11264. customExtensions,
  11265. generatePrecision( parameters ),
  11266. '#define SHADER_NAME ' + parameters.shaderName,
  11267. customDefines,
  11268. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11269. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11270. parameters.map ? '#define USE_MAP' : '',
  11271. parameters.matcap ? '#define USE_MATCAP' : '',
  11272. parameters.envMap ? '#define USE_ENVMAP' : '',
  11273. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  11274. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11275. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  11276. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  11277. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  11278. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  11279. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11280. parameters.aoMap ? '#define USE_AOMAP' : '',
  11281. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11282. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11283. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11284. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11285. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11286. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  11287. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11288. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11289. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11290. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  11291. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11292. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11293. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11294. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  11295. parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '',
  11296. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11297. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11298. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11299. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  11300. parameters.sheen ? '#define USE_SHEEN' : '',
  11301. parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '',
  11302. parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '',
  11303. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11304. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11305. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11306. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  11307. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11308. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  11309. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11310. parameters.vertexUvs ? '#define USE_UV' : '',
  11311. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11312. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  11313. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11314. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11315. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11316. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11317. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11318. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  11319. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  11320. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11321. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11322. 'uniform mat4 viewMatrix;',
  11323. 'uniform vec3 cameraPosition;',
  11324. 'uniform bool isOrthographic;',
  11325. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  11326. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  11327. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  11328. parameters.dithering ? '#define DITHERING' : '',
  11329. parameters.opaque ? '#define OPAQUE' : '',
  11330. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  11331. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
  11332. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  11333. '\n'
  11334. ].filter( filterEmptyLine ).join( '\n' );
  11335. }
  11336. vertexShader = resolveIncludes( vertexShader );
  11337. vertexShader = replaceLightNums( vertexShader, parameters );
  11338. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  11339. fragmentShader = resolveIncludes( fragmentShader );
  11340. fragmentShader = replaceLightNums( fragmentShader, parameters );
  11341. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  11342. vertexShader = unrollLoops( vertexShader );
  11343. fragmentShader = unrollLoops( fragmentShader );
  11344. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  11345. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11346. versionString = '#version 300 es\n';
  11347. prefixVertex = [
  11348. 'precision mediump sampler2DArray;',
  11349. '#define attribute in',
  11350. '#define varying out',
  11351. '#define texture2D texture'
  11352. ].join( '\n' ) + '\n' + prefixVertex;
  11353. prefixFragment = [
  11354. '#define varying in',
  11355. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  11356. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  11357. '#define gl_FragDepthEXT gl_FragDepth',
  11358. '#define texture2D texture',
  11359. '#define textureCube texture',
  11360. '#define texture2DProj textureProj',
  11361. '#define texture2DLodEXT textureLod',
  11362. '#define texture2DProjLodEXT textureProjLod',
  11363. '#define textureCubeLodEXT textureLod',
  11364. '#define texture2DGradEXT textureGrad',
  11365. '#define texture2DProjGradEXT textureProjGrad',
  11366. '#define textureCubeGradEXT textureGrad'
  11367. ].join( '\n' ) + '\n' + prefixFragment;
  11368. }
  11369. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11370. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  11371. // console.log( '*VERTEX*', vertexGlsl );
  11372. // console.log( '*FRAGMENT*', fragmentGlsl );
  11373. const glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
  11374. const glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
  11375. gl.attachShader( program, glVertexShader );
  11376. gl.attachShader( program, glFragmentShader );
  11377. // Force a particular attribute to index 0.
  11378. if ( parameters.index0AttributeName !== undefined ) {
  11379. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  11380. } else if ( parameters.morphTargets === true ) {
  11381. // programs with morphTargets displace position out of attribute 0
  11382. gl.bindAttribLocation( program, 0, 'position' );
  11383. }
  11384. gl.linkProgram( program );
  11385. // check for link errors
  11386. if ( renderer.debug.checkShaderErrors ) {
  11387. const programLog = gl.getProgramInfoLog( program ).trim();
  11388. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  11389. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  11390. let runnable = true;
  11391. let haveDiagnostics = true;
  11392. if ( gl.getProgramParameter( program, 35714 ) === false ) {
  11393. runnable = false;
  11394. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  11395. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  11396. console.error(
  11397. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  11398. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, 35715 ) + '\n\n' +
  11399. 'Program Info Log: ' + programLog + '\n' +
  11400. vertexErrors + '\n' +
  11401. fragmentErrors
  11402. );
  11403. } else if ( programLog !== '' ) {
  11404. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  11405. } else if ( vertexLog === '' || fragmentLog === '' ) {
  11406. haveDiagnostics = false;
  11407. }
  11408. if ( haveDiagnostics ) {
  11409. this.diagnostics = {
  11410. runnable: runnable,
  11411. programLog: programLog,
  11412. vertexShader: {
  11413. log: vertexLog,
  11414. prefix: prefixVertex
  11415. },
  11416. fragmentShader: {
  11417. log: fragmentLog,
  11418. prefix: prefixFragment
  11419. }
  11420. };
  11421. }
  11422. }
  11423. // Clean up
  11424. // Crashes in iOS9 and iOS10. #18402
  11425. // gl.detachShader( program, glVertexShader );
  11426. // gl.detachShader( program, glFragmentShader );
  11427. gl.deleteShader( glVertexShader );
  11428. gl.deleteShader( glFragmentShader );
  11429. // set up caching for uniform locations
  11430. let cachedUniforms;
  11431. this.getUniforms = function () {
  11432. if ( cachedUniforms === undefined ) {
  11433. cachedUniforms = new WebGLUniforms( gl, program );
  11434. }
  11435. return cachedUniforms;
  11436. };
  11437. // set up caching for attribute locations
  11438. let cachedAttributes;
  11439. this.getAttributes = function () {
  11440. if ( cachedAttributes === undefined ) {
  11441. cachedAttributes = fetchAttributeLocations( gl, program );
  11442. }
  11443. return cachedAttributes;
  11444. };
  11445. // free resource
  11446. this.destroy = function () {
  11447. bindingStates.releaseStatesOfProgram( this );
  11448. gl.deleteProgram( program );
  11449. this.program = undefined;
  11450. };
  11451. //
  11452. this.name = parameters.shaderName;
  11453. this.id = programIdCount ++;
  11454. this.cacheKey = cacheKey;
  11455. this.usedTimes = 1;
  11456. this.program = program;
  11457. this.vertexShader = glVertexShader;
  11458. this.fragmentShader = glFragmentShader;
  11459. return this;
  11460. }
  11461. let _id = 0;
  11462. class WebGLShaderCache {
  11463. constructor() {
  11464. this.shaderCache = new Map();
  11465. this.materialCache = new Map();
  11466. }
  11467. update( material ) {
  11468. const vertexShader = material.vertexShader;
  11469. const fragmentShader = material.fragmentShader;
  11470. const vertexShaderStage = this._getShaderStage( vertexShader );
  11471. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  11472. const materialShaders = this._getShaderCacheForMaterial( material );
  11473. if ( materialShaders.has( vertexShaderStage ) === false ) {
  11474. materialShaders.add( vertexShaderStage );
  11475. vertexShaderStage.usedTimes ++;
  11476. }
  11477. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  11478. materialShaders.add( fragmentShaderStage );
  11479. fragmentShaderStage.usedTimes ++;
  11480. }
  11481. return this;
  11482. }
  11483. remove( material ) {
  11484. const materialShaders = this.materialCache.get( material );
  11485. for ( const shaderStage of materialShaders ) {
  11486. shaderStage.usedTimes --;
  11487. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  11488. }
  11489. this.materialCache.delete( material );
  11490. return this;
  11491. }
  11492. getVertexShaderID( material ) {
  11493. return this._getShaderStage( material.vertexShader ).id;
  11494. }
  11495. getFragmentShaderID( material ) {
  11496. return this._getShaderStage( material.fragmentShader ).id;
  11497. }
  11498. dispose() {
  11499. this.shaderCache.clear();
  11500. this.materialCache.clear();
  11501. }
  11502. _getShaderCacheForMaterial( material ) {
  11503. const cache = this.materialCache;
  11504. let set = cache.get( material );
  11505. if ( set === undefined ) {
  11506. set = new Set();
  11507. cache.set( material, set );
  11508. }
  11509. return set;
  11510. }
  11511. _getShaderStage( code ) {
  11512. const cache = this.shaderCache;
  11513. let stage = cache.get( code );
  11514. if ( stage === undefined ) {
  11515. stage = new WebGLShaderStage( code );
  11516. cache.set( code, stage );
  11517. }
  11518. return stage;
  11519. }
  11520. }
  11521. class WebGLShaderStage {
  11522. constructor( code ) {
  11523. this.id = _id ++;
  11524. this.code = code;
  11525. this.usedTimes = 0;
  11526. }
  11527. }
  11528. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  11529. const _programLayers = new Layers();
  11530. const _customShaders = new WebGLShaderCache();
  11531. const programs = [];
  11532. const isWebGL2 = capabilities.isWebGL2;
  11533. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11534. const vertexTextures = capabilities.vertexTextures;
  11535. let precision = capabilities.precision;
  11536. const shaderIDs = {
  11537. MeshDepthMaterial: 'depth',
  11538. MeshDistanceMaterial: 'distanceRGBA',
  11539. MeshNormalMaterial: 'normal',
  11540. MeshBasicMaterial: 'basic',
  11541. MeshLambertMaterial: 'lambert',
  11542. MeshPhongMaterial: 'phong',
  11543. MeshToonMaterial: 'toon',
  11544. MeshStandardMaterial: 'physical',
  11545. MeshPhysicalMaterial: 'physical',
  11546. MeshMatcapMaterial: 'matcap',
  11547. LineBasicMaterial: 'basic',
  11548. LineDashedMaterial: 'dashed',
  11549. PointsMaterial: 'points',
  11550. ShadowMaterial: 'shadow',
  11551. SpriteMaterial: 'sprite'
  11552. };
  11553. function getParameters( material, lights, shadows, scene, object ) {
  11554. const fog = scene.fog;
  11555. const geometry = object.geometry;
  11556. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11557. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  11558. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  11559. const shaderID = shaderIDs[ material.type ];
  11560. // heuristics to create shader parameters according to lights in the scene
  11561. // (not to blow over maxLights budget)
  11562. if ( material.precision !== null ) {
  11563. precision = capabilities.getMaxPrecision( material.precision );
  11564. if ( precision !== material.precision ) {
  11565. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  11566. }
  11567. }
  11568. //
  11569. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11570. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11571. let morphTextureStride = 0;
  11572. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  11573. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  11574. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  11575. //
  11576. let vertexShader, fragmentShader;
  11577. let customVertexShaderID, customFragmentShaderID;
  11578. if ( shaderID ) {
  11579. const shader = ShaderLib[ shaderID ];
  11580. vertexShader = shader.vertexShader;
  11581. fragmentShader = shader.fragmentShader;
  11582. } else {
  11583. vertexShader = material.vertexShader;
  11584. fragmentShader = material.fragmentShader;
  11585. _customShaders.update( material );
  11586. customVertexShaderID = _customShaders.getVertexShaderID( material );
  11587. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  11588. }
  11589. const currentRenderTarget = renderer.getRenderTarget();
  11590. const useAlphaTest = material.alphaTest > 0;
  11591. const useClearcoat = material.clearcoat > 0;
  11592. const useIridescence = material.iridescence > 0;
  11593. const parameters = {
  11594. isWebGL2: isWebGL2,
  11595. shaderID: shaderID,
  11596. shaderName: material.type,
  11597. vertexShader: vertexShader,
  11598. fragmentShader: fragmentShader,
  11599. defines: material.defines,
  11600. customVertexShaderID: customVertexShaderID,
  11601. customFragmentShaderID: customFragmentShaderID,
  11602. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11603. glslVersion: material.glslVersion,
  11604. precision: precision,
  11605. instancing: object.isInstancedMesh === true,
  11606. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11607. supportsVertexTextures: vertexTextures,
  11608. outputEncoding: ( currentRenderTarget === null ) ? renderer.outputEncoding : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding ),
  11609. map: !! material.map,
  11610. matcap: !! material.matcap,
  11611. envMap: !! envMap,
  11612. envMapMode: envMap && envMap.mapping,
  11613. envMapCubeUVHeight: envMapCubeUVHeight,
  11614. lightMap: !! material.lightMap,
  11615. aoMap: !! material.aoMap,
  11616. emissiveMap: !! material.emissiveMap,
  11617. bumpMap: !! material.bumpMap,
  11618. normalMap: !! material.normalMap,
  11619. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11620. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11621. decodeVideoTexture: !! material.map && ( material.map.isVideoTexture === true ) && ( material.map.encoding === sRGBEncoding ),
  11622. clearcoat: useClearcoat,
  11623. clearcoatMap: useClearcoat && !! material.clearcoatMap,
  11624. clearcoatRoughnessMap: useClearcoat && !! material.clearcoatRoughnessMap,
  11625. clearcoatNormalMap: useClearcoat && !! material.clearcoatNormalMap,
  11626. iridescence: useIridescence,
  11627. iridescenceMap: useIridescence && !! material.iridescenceMap,
  11628. iridescenceThicknessMap: useIridescence && !! material.iridescenceThicknessMap,
  11629. displacementMap: !! material.displacementMap,
  11630. roughnessMap: !! material.roughnessMap,
  11631. metalnessMap: !! material.metalnessMap,
  11632. specularMap: !! material.specularMap,
  11633. specularIntensityMap: !! material.specularIntensityMap,
  11634. specularColorMap: !! material.specularColorMap,
  11635. opaque: material.transparent === false && material.blending === NormalBlending,
  11636. alphaMap: !! material.alphaMap,
  11637. alphaTest: useAlphaTest,
  11638. gradientMap: !! material.gradientMap,
  11639. sheen: material.sheen > 0,
  11640. sheenColorMap: !! material.sheenColorMap,
  11641. sheenRoughnessMap: !! material.sheenRoughnessMap,
  11642. transmission: material.transmission > 0,
  11643. transmissionMap: !! material.transmissionMap,
  11644. thicknessMap: !! material.thicknessMap,
  11645. combine: material.combine,
  11646. vertexTangents: ( !! material.normalMap && !! geometry.attributes.tangent ),
  11647. vertexColors: material.vertexColors,
  11648. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  11649. vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatMap || !! material.clearcoatRoughnessMap || !! material.clearcoatNormalMap || !! material.iridescenceMap || !! material.iridescenceThicknessMap || !! material.displacementMap || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || !! material.sheenColorMap || !! material.sheenRoughnessMap,
  11650. uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || !! material.iridescenceMap || !! material.iridescenceThicknessMap || material.transmission > 0 || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || material.sheen > 0 || !! material.sheenColorMap || !! material.sheenRoughnessMap ) && !! material.displacementMap,
  11651. fog: !! fog,
  11652. useFog: material.fog === true,
  11653. fogExp2: ( fog && fog.isFogExp2 ),
  11654. flatShading: !! material.flatShading,
  11655. sizeAttenuation: material.sizeAttenuation,
  11656. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11657. skinning: object.isSkinnedMesh === true,
  11658. morphTargets: geometry.morphAttributes.position !== undefined,
  11659. morphNormals: geometry.morphAttributes.normal !== undefined,
  11660. morphColors: geometry.morphAttributes.color !== undefined,
  11661. morphTargetsCount: morphTargetsCount,
  11662. morphTextureStride: morphTextureStride,
  11663. numDirLights: lights.directional.length,
  11664. numPointLights: lights.point.length,
  11665. numSpotLights: lights.spot.length,
  11666. numSpotLightMaps: lights.spotLightMap.length,
  11667. numRectAreaLights: lights.rectArea.length,
  11668. numHemiLights: lights.hemi.length,
  11669. numDirLightShadows: lights.directionalShadowMap.length,
  11670. numPointLightShadows: lights.pointShadowMap.length,
  11671. numSpotLightShadows: lights.spotShadowMap.length,
  11672. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  11673. numClippingPlanes: clipping.numPlanes,
  11674. numClipIntersection: clipping.numIntersection,
  11675. dithering: material.dithering,
  11676. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11677. shadowMapType: renderer.shadowMap.type,
  11678. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11679. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11680. premultipliedAlpha: material.premultipliedAlpha,
  11681. doubleSided: material.side === DoubleSide,
  11682. flipSided: material.side === BackSide,
  11683. useDepthPacking: !! material.depthPacking,
  11684. depthPacking: material.depthPacking || 0,
  11685. index0AttributeName: material.index0AttributeName,
  11686. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11687. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11688. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11689. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11690. rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ),
  11691. rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  11692. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  11693. customProgramCacheKey: material.customProgramCacheKey()
  11694. };
  11695. return parameters;
  11696. }
  11697. function getProgramCacheKey( parameters ) {
  11698. const array = [];
  11699. if ( parameters.shaderID ) {
  11700. array.push( parameters.shaderID );
  11701. } else {
  11702. array.push( parameters.customVertexShaderID );
  11703. array.push( parameters.customFragmentShaderID );
  11704. }
  11705. if ( parameters.defines !== undefined ) {
  11706. for ( const name in parameters.defines ) {
  11707. array.push( name );
  11708. array.push( parameters.defines[ name ] );
  11709. }
  11710. }
  11711. if ( parameters.isRawShaderMaterial === false ) {
  11712. getProgramCacheKeyParameters( array, parameters );
  11713. getProgramCacheKeyBooleans( array, parameters );
  11714. array.push( renderer.outputEncoding );
  11715. }
  11716. array.push( parameters.customProgramCacheKey );
  11717. return array.join();
  11718. }
  11719. function getProgramCacheKeyParameters( array, parameters ) {
  11720. array.push( parameters.precision );
  11721. array.push( parameters.outputEncoding );
  11722. array.push( parameters.envMapMode );
  11723. array.push( parameters.envMapCubeUVHeight );
  11724. array.push( parameters.combine );
  11725. array.push( parameters.vertexUvs );
  11726. array.push( parameters.fogExp2 );
  11727. array.push( parameters.sizeAttenuation );
  11728. array.push( parameters.morphTargetsCount );
  11729. array.push( parameters.morphAttributeCount );
  11730. array.push( parameters.numDirLights );
  11731. array.push( parameters.numPointLights );
  11732. array.push( parameters.numSpotLights );
  11733. array.push( parameters.numSpotLightMaps );
  11734. array.push( parameters.numHemiLights );
  11735. array.push( parameters.numRectAreaLights );
  11736. array.push( parameters.numDirLightShadows );
  11737. array.push( parameters.numPointLightShadows );
  11738. array.push( parameters.numSpotLightShadows );
  11739. array.push( parameters.numSpotLightShadowsWithMaps );
  11740. array.push( parameters.shadowMapType );
  11741. array.push( parameters.toneMapping );
  11742. array.push( parameters.numClippingPlanes );
  11743. array.push( parameters.numClipIntersection );
  11744. array.push( parameters.depthPacking );
  11745. }
  11746. function getProgramCacheKeyBooleans( array, parameters ) {
  11747. _programLayers.disableAll();
  11748. if ( parameters.isWebGL2 )
  11749. _programLayers.enable( 0 );
  11750. if ( parameters.supportsVertexTextures )
  11751. _programLayers.enable( 1 );
  11752. if ( parameters.instancing )
  11753. _programLayers.enable( 2 );
  11754. if ( parameters.instancingColor )
  11755. _programLayers.enable( 3 );
  11756. if ( parameters.map )
  11757. _programLayers.enable( 4 );
  11758. if ( parameters.matcap )
  11759. _programLayers.enable( 5 );
  11760. if ( parameters.envMap )
  11761. _programLayers.enable( 6 );
  11762. if ( parameters.lightMap )
  11763. _programLayers.enable( 7 );
  11764. if ( parameters.aoMap )
  11765. _programLayers.enable( 8 );
  11766. if ( parameters.emissiveMap )
  11767. _programLayers.enable( 9 );
  11768. if ( parameters.bumpMap )
  11769. _programLayers.enable( 10 );
  11770. if ( parameters.normalMap )
  11771. _programLayers.enable( 11 );
  11772. if ( parameters.objectSpaceNormalMap )
  11773. _programLayers.enable( 12 );
  11774. if ( parameters.tangentSpaceNormalMap )
  11775. _programLayers.enable( 13 );
  11776. if ( parameters.clearcoat )
  11777. _programLayers.enable( 14 );
  11778. if ( parameters.clearcoatMap )
  11779. _programLayers.enable( 15 );
  11780. if ( parameters.clearcoatRoughnessMap )
  11781. _programLayers.enable( 16 );
  11782. if ( parameters.clearcoatNormalMap )
  11783. _programLayers.enable( 17 );
  11784. if ( parameters.iridescence )
  11785. _programLayers.enable( 18 );
  11786. if ( parameters.iridescenceMap )
  11787. _programLayers.enable( 19 );
  11788. if ( parameters.iridescenceThicknessMap )
  11789. _programLayers.enable( 20 );
  11790. if ( parameters.displacementMap )
  11791. _programLayers.enable( 21 );
  11792. if ( parameters.specularMap )
  11793. _programLayers.enable( 22 );
  11794. if ( parameters.roughnessMap )
  11795. _programLayers.enable( 23 );
  11796. if ( parameters.metalnessMap )
  11797. _programLayers.enable( 24 );
  11798. if ( parameters.gradientMap )
  11799. _programLayers.enable( 25 );
  11800. if ( parameters.alphaMap )
  11801. _programLayers.enable( 26 );
  11802. if ( parameters.alphaTest )
  11803. _programLayers.enable( 27 );
  11804. if ( parameters.vertexColors )
  11805. _programLayers.enable( 28 );
  11806. if ( parameters.vertexAlphas )
  11807. _programLayers.enable( 29 );
  11808. if ( parameters.vertexUvs )
  11809. _programLayers.enable( 30 );
  11810. if ( parameters.vertexTangents )
  11811. _programLayers.enable( 31 );
  11812. if ( parameters.uvsVertexOnly )
  11813. _programLayers.enable( 32 );
  11814. array.push( _programLayers.mask );
  11815. _programLayers.disableAll();
  11816. if ( parameters.fog )
  11817. _programLayers.enable( 0 );
  11818. if ( parameters.useFog )
  11819. _programLayers.enable( 1 );
  11820. if ( parameters.flatShading )
  11821. _programLayers.enable( 2 );
  11822. if ( parameters.logarithmicDepthBuffer )
  11823. _programLayers.enable( 3 );
  11824. if ( parameters.skinning )
  11825. _programLayers.enable( 4 );
  11826. if ( parameters.morphTargets )
  11827. _programLayers.enable( 5 );
  11828. if ( parameters.morphNormals )
  11829. _programLayers.enable( 6 );
  11830. if ( parameters.morphColors )
  11831. _programLayers.enable( 7 );
  11832. if ( parameters.premultipliedAlpha )
  11833. _programLayers.enable( 8 );
  11834. if ( parameters.shadowMapEnabled )
  11835. _programLayers.enable( 9 );
  11836. if ( parameters.physicallyCorrectLights )
  11837. _programLayers.enable( 10 );
  11838. if ( parameters.doubleSided )
  11839. _programLayers.enable( 11 );
  11840. if ( parameters.flipSided )
  11841. _programLayers.enable( 12 );
  11842. if ( parameters.useDepthPacking )
  11843. _programLayers.enable( 13 );
  11844. if ( parameters.dithering )
  11845. _programLayers.enable( 14 );
  11846. if ( parameters.specularIntensityMap )
  11847. _programLayers.enable( 15 );
  11848. if ( parameters.specularColorMap )
  11849. _programLayers.enable( 16 );
  11850. if ( parameters.transmission )
  11851. _programLayers.enable( 17 );
  11852. if ( parameters.transmissionMap )
  11853. _programLayers.enable( 18 );
  11854. if ( parameters.thicknessMap )
  11855. _programLayers.enable( 19 );
  11856. if ( parameters.sheen )
  11857. _programLayers.enable( 20 );
  11858. if ( parameters.sheenColorMap )
  11859. _programLayers.enable( 21 );
  11860. if ( parameters.sheenRoughnessMap )
  11861. _programLayers.enable( 22 );
  11862. if ( parameters.decodeVideoTexture )
  11863. _programLayers.enable( 23 );
  11864. if ( parameters.opaque )
  11865. _programLayers.enable( 24 );
  11866. array.push( _programLayers.mask );
  11867. }
  11868. function getUniforms( material ) {
  11869. const shaderID = shaderIDs[ material.type ];
  11870. let uniforms;
  11871. if ( shaderID ) {
  11872. const shader = ShaderLib[ shaderID ];
  11873. uniforms = UniformsUtils.clone( shader.uniforms );
  11874. } else {
  11875. uniforms = material.uniforms;
  11876. }
  11877. return uniforms;
  11878. }
  11879. function acquireProgram( parameters, cacheKey ) {
  11880. let program;
  11881. // Check if code has been already compiled
  11882. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  11883. const preexistingProgram = programs[ p ];
  11884. if ( preexistingProgram.cacheKey === cacheKey ) {
  11885. program = preexistingProgram;
  11886. ++ program.usedTimes;
  11887. break;
  11888. }
  11889. }
  11890. if ( program === undefined ) {
  11891. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  11892. programs.push( program );
  11893. }
  11894. return program;
  11895. }
  11896. function releaseProgram( program ) {
  11897. if ( -- program.usedTimes === 0 ) {
  11898. // Remove from unordered set
  11899. const i = programs.indexOf( program );
  11900. programs[ i ] = programs[ programs.length - 1 ];
  11901. programs.pop();
  11902. // Free WebGL resources
  11903. program.destroy();
  11904. }
  11905. }
  11906. function releaseShaderCache( material ) {
  11907. _customShaders.remove( material );
  11908. }
  11909. function dispose() {
  11910. _customShaders.dispose();
  11911. }
  11912. return {
  11913. getParameters: getParameters,
  11914. getProgramCacheKey: getProgramCacheKey,
  11915. getUniforms: getUniforms,
  11916. acquireProgram: acquireProgram,
  11917. releaseProgram: releaseProgram,
  11918. releaseShaderCache: releaseShaderCache,
  11919. // Exposed for resource monitoring & error feedback via renderer.info:
  11920. programs: programs,
  11921. dispose: dispose
  11922. };
  11923. }
  11924. function WebGLProperties() {
  11925. let properties = new WeakMap();
  11926. function get( object ) {
  11927. let map = properties.get( object );
  11928. if ( map === undefined ) {
  11929. map = {};
  11930. properties.set( object, map );
  11931. }
  11932. return map;
  11933. }
  11934. function remove( object ) {
  11935. properties.delete( object );
  11936. }
  11937. function update( object, key, value ) {
  11938. properties.get( object )[ key ] = value;
  11939. }
  11940. function dispose() {
  11941. properties = new WeakMap();
  11942. }
  11943. return {
  11944. get: get,
  11945. remove: remove,
  11946. update: update,
  11947. dispose: dispose
  11948. };
  11949. }
  11950. function painterSortStable( a, b ) {
  11951. if ( a.groupOrder !== b.groupOrder ) {
  11952. return a.groupOrder - b.groupOrder;
  11953. } else if ( a.renderOrder !== b.renderOrder ) {
  11954. return a.renderOrder - b.renderOrder;
  11955. } else if ( a.material.id !== b.material.id ) {
  11956. return a.material.id - b.material.id;
  11957. } else if ( a.z !== b.z ) {
  11958. return a.z - b.z;
  11959. } else {
  11960. return a.id - b.id;
  11961. }
  11962. }
  11963. function reversePainterSortStable( a, b ) {
  11964. if ( a.groupOrder !== b.groupOrder ) {
  11965. return a.groupOrder - b.groupOrder;
  11966. } else if ( a.renderOrder !== b.renderOrder ) {
  11967. return a.renderOrder - b.renderOrder;
  11968. } else if ( a.z !== b.z ) {
  11969. return b.z - a.z;
  11970. } else {
  11971. return a.id - b.id;
  11972. }
  11973. }
  11974. function WebGLRenderList() {
  11975. const renderItems = [];
  11976. let renderItemsIndex = 0;
  11977. const opaque = [];
  11978. const transmissive = [];
  11979. const transparent = [];
  11980. function init() {
  11981. renderItemsIndex = 0;
  11982. opaque.length = 0;
  11983. transmissive.length = 0;
  11984. transparent.length = 0;
  11985. }
  11986. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  11987. let renderItem = renderItems[ renderItemsIndex ];
  11988. if ( renderItem === undefined ) {
  11989. renderItem = {
  11990. id: object.id,
  11991. object: object,
  11992. geometry: geometry,
  11993. material: material,
  11994. groupOrder: groupOrder,
  11995. renderOrder: object.renderOrder,
  11996. z: z,
  11997. group: group
  11998. };
  11999. renderItems[ renderItemsIndex ] = renderItem;
  12000. } else {
  12001. renderItem.id = object.id;
  12002. renderItem.object = object;
  12003. renderItem.geometry = geometry;
  12004. renderItem.material = material;
  12005. renderItem.groupOrder = groupOrder;
  12006. renderItem.renderOrder = object.renderOrder;
  12007. renderItem.z = z;
  12008. renderItem.group = group;
  12009. }
  12010. renderItemsIndex ++;
  12011. return renderItem;
  12012. }
  12013. function push( object, geometry, material, groupOrder, z, group ) {
  12014. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12015. if ( material.transmission > 0.0 ) {
  12016. transmissive.push( renderItem );
  12017. } else if ( material.transparent === true ) {
  12018. transparent.push( renderItem );
  12019. } else {
  12020. opaque.push( renderItem );
  12021. }
  12022. }
  12023. function unshift( object, geometry, material, groupOrder, z, group ) {
  12024. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12025. if ( material.transmission > 0.0 ) {
  12026. transmissive.unshift( renderItem );
  12027. } else if ( material.transparent === true ) {
  12028. transparent.unshift( renderItem );
  12029. } else {
  12030. opaque.unshift( renderItem );
  12031. }
  12032. }
  12033. function sort( customOpaqueSort, customTransparentSort ) {
  12034. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  12035. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  12036. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  12037. }
  12038. function finish() {
  12039. // Clear references from inactive renderItems in the list
  12040. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  12041. const renderItem = renderItems[ i ];
  12042. if ( renderItem.id === null ) break;
  12043. renderItem.id = null;
  12044. renderItem.object = null;
  12045. renderItem.geometry = null;
  12046. renderItem.material = null;
  12047. renderItem.group = null;
  12048. }
  12049. }
  12050. return {
  12051. opaque: opaque,
  12052. transmissive: transmissive,
  12053. transparent: transparent,
  12054. init: init,
  12055. push: push,
  12056. unshift: unshift,
  12057. finish: finish,
  12058. sort: sort
  12059. };
  12060. }
  12061. function WebGLRenderLists() {
  12062. let lists = new WeakMap();
  12063. function get( scene, renderCallDepth ) {
  12064. const listArray = lists.get( scene );
  12065. let list;
  12066. if ( listArray === undefined ) {
  12067. list = new WebGLRenderList();
  12068. lists.set( scene, [ list ] );
  12069. } else {
  12070. if ( renderCallDepth >= listArray.length ) {
  12071. list = new WebGLRenderList();
  12072. listArray.push( list );
  12073. } else {
  12074. list = listArray[ renderCallDepth ];
  12075. }
  12076. }
  12077. return list;
  12078. }
  12079. function dispose() {
  12080. lists = new WeakMap();
  12081. }
  12082. return {
  12083. get: get,
  12084. dispose: dispose
  12085. };
  12086. }
  12087. function UniformsCache() {
  12088. const lights = {};
  12089. return {
  12090. get: function ( light ) {
  12091. if ( lights[ light.id ] !== undefined ) {
  12092. return lights[ light.id ];
  12093. }
  12094. let uniforms;
  12095. switch ( light.type ) {
  12096. case 'DirectionalLight':
  12097. uniforms = {
  12098. direction: new Vector3(),
  12099. color: new Color()
  12100. };
  12101. break;
  12102. case 'SpotLight':
  12103. uniforms = {
  12104. position: new Vector3(),
  12105. direction: new Vector3(),
  12106. color: new Color(),
  12107. distance: 0,
  12108. coneCos: 0,
  12109. penumbraCos: 0,
  12110. decay: 0
  12111. };
  12112. break;
  12113. case 'PointLight':
  12114. uniforms = {
  12115. position: new Vector3(),
  12116. color: new Color(),
  12117. distance: 0,
  12118. decay: 0
  12119. };
  12120. break;
  12121. case 'HemisphereLight':
  12122. uniforms = {
  12123. direction: new Vector3(),
  12124. skyColor: new Color(),
  12125. groundColor: new Color()
  12126. };
  12127. break;
  12128. case 'RectAreaLight':
  12129. uniforms = {
  12130. color: new Color(),
  12131. position: new Vector3(),
  12132. halfWidth: new Vector3(),
  12133. halfHeight: new Vector3()
  12134. };
  12135. break;
  12136. }
  12137. lights[ light.id ] = uniforms;
  12138. return uniforms;
  12139. }
  12140. };
  12141. }
  12142. function ShadowUniformsCache() {
  12143. const lights = {};
  12144. return {
  12145. get: function ( light ) {
  12146. if ( lights[ light.id ] !== undefined ) {
  12147. return lights[ light.id ];
  12148. }
  12149. let uniforms;
  12150. switch ( light.type ) {
  12151. case 'DirectionalLight':
  12152. uniforms = {
  12153. shadowBias: 0,
  12154. shadowNormalBias: 0,
  12155. shadowRadius: 1,
  12156. shadowMapSize: new Vector2()
  12157. };
  12158. break;
  12159. case 'SpotLight':
  12160. uniforms = {
  12161. shadowBias: 0,
  12162. shadowNormalBias: 0,
  12163. shadowRadius: 1,
  12164. shadowMapSize: new Vector2()
  12165. };
  12166. break;
  12167. case 'PointLight':
  12168. uniforms = {
  12169. shadowBias: 0,
  12170. shadowNormalBias: 0,
  12171. shadowRadius: 1,
  12172. shadowMapSize: new Vector2(),
  12173. shadowCameraNear: 1,
  12174. shadowCameraFar: 1000
  12175. };
  12176. break;
  12177. // TODO (abelnation): set RectAreaLight shadow uniforms
  12178. }
  12179. lights[ light.id ] = uniforms;
  12180. return uniforms;
  12181. }
  12182. };
  12183. }
  12184. let nextVersion = 0;
  12185. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  12186. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  12187. }
  12188. function WebGLLights( extensions, capabilities ) {
  12189. const cache = new UniformsCache();
  12190. const shadowCache = ShadowUniformsCache();
  12191. const state = {
  12192. version: 0,
  12193. hash: {
  12194. directionalLength: - 1,
  12195. pointLength: - 1,
  12196. spotLength: - 1,
  12197. rectAreaLength: - 1,
  12198. hemiLength: - 1,
  12199. numDirectionalShadows: - 1,
  12200. numPointShadows: - 1,
  12201. numSpotShadows: - 1,
  12202. numSpotMaps: - 1
  12203. },
  12204. ambient: [ 0, 0, 0 ],
  12205. probe: [],
  12206. directional: [],
  12207. directionalShadow: [],
  12208. directionalShadowMap: [],
  12209. directionalShadowMatrix: [],
  12210. spot: [],
  12211. spotLightMap: [],
  12212. spotShadow: [],
  12213. spotShadowMap: [],
  12214. spotLightMatrix: [],
  12215. rectArea: [],
  12216. rectAreaLTC1: null,
  12217. rectAreaLTC2: null,
  12218. point: [],
  12219. pointShadow: [],
  12220. pointShadowMap: [],
  12221. pointShadowMatrix: [],
  12222. hemi: [],
  12223. numSpotLightShadowsWithMaps: 0
  12224. };
  12225. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  12226. const vector3 = new Vector3();
  12227. const matrix4 = new Matrix4();
  12228. const matrix42 = new Matrix4();
  12229. function setup( lights, physicallyCorrectLights ) {
  12230. let r = 0, g = 0, b = 0;
  12231. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  12232. let directionalLength = 0;
  12233. let pointLength = 0;
  12234. let spotLength = 0;
  12235. let rectAreaLength = 0;
  12236. let hemiLength = 0;
  12237. let numDirectionalShadows = 0;
  12238. let numPointShadows = 0;
  12239. let numSpotShadows = 0;
  12240. let numSpotMaps = 0;
  12241. let numSpotShadowsWithMaps = 0;
  12242. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  12243. lights.sort( shadowCastingAndTexturingLightsFirst );
  12244. // artist-friendly light intensity scaling factor
  12245. const scaleFactor = ( physicallyCorrectLights !== true ) ? Math.PI : 1;
  12246. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12247. const light = lights[ i ];
  12248. const color = light.color;
  12249. const intensity = light.intensity;
  12250. const distance = light.distance;
  12251. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12252. if ( light.isAmbientLight ) {
  12253. r += color.r * intensity * scaleFactor;
  12254. g += color.g * intensity * scaleFactor;
  12255. b += color.b * intensity * scaleFactor;
  12256. } else if ( light.isLightProbe ) {
  12257. for ( let j = 0; j < 9; j ++ ) {
  12258. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  12259. }
  12260. } else if ( light.isDirectionalLight ) {
  12261. const uniforms = cache.get( light );
  12262. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12263. if ( light.castShadow ) {
  12264. const shadow = light.shadow;
  12265. const shadowUniforms = shadowCache.get( light );
  12266. shadowUniforms.shadowBias = shadow.bias;
  12267. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12268. shadowUniforms.shadowRadius = shadow.radius;
  12269. shadowUniforms.shadowMapSize = shadow.mapSize;
  12270. state.directionalShadow[ directionalLength ] = shadowUniforms;
  12271. state.directionalShadowMap[ directionalLength ] = shadowMap;
  12272. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  12273. numDirectionalShadows ++;
  12274. }
  12275. state.directional[ directionalLength ] = uniforms;
  12276. directionalLength ++;
  12277. } else if ( light.isSpotLight ) {
  12278. const uniforms = cache.get( light );
  12279. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12280. uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor );
  12281. uniforms.distance = distance;
  12282. uniforms.coneCos = Math.cos( light.angle );
  12283. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  12284. uniforms.decay = light.decay;
  12285. state.spot[ spotLength ] = uniforms;
  12286. const shadow = light.shadow;
  12287. if ( light.map ) {
  12288. state.spotLightMap[ numSpotMaps ] = light.map;
  12289. numSpotMaps ++;
  12290. // make sure the lightMatrix is up to date
  12291. // TODO : do it if required only
  12292. shadow.updateMatrices( light );
  12293. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  12294. }
  12295. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  12296. if ( light.castShadow ) {
  12297. const shadowUniforms = shadowCache.get( light );
  12298. shadowUniforms.shadowBias = shadow.bias;
  12299. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12300. shadowUniforms.shadowRadius = shadow.radius;
  12301. shadowUniforms.shadowMapSize = shadow.mapSize;
  12302. state.spotShadow[ spotLength ] = shadowUniforms;
  12303. state.spotShadowMap[ spotLength ] = shadowMap;
  12304. numSpotShadows ++;
  12305. }
  12306. spotLength ++;
  12307. } else if ( light.isRectAreaLight ) {
  12308. const uniforms = cache.get( light );
  12309. uniforms.color.copy( color ).multiplyScalar( intensity );
  12310. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12311. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12312. state.rectArea[ rectAreaLength ] = uniforms;
  12313. rectAreaLength ++;
  12314. } else if ( light.isPointLight ) {
  12315. const uniforms = cache.get( light );
  12316. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12317. uniforms.distance = light.distance;
  12318. uniforms.decay = light.decay;
  12319. if ( light.castShadow ) {
  12320. const shadow = light.shadow;
  12321. const shadowUniforms = shadowCache.get( light );
  12322. shadowUniforms.shadowBias = shadow.bias;
  12323. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12324. shadowUniforms.shadowRadius = shadow.radius;
  12325. shadowUniforms.shadowMapSize = shadow.mapSize;
  12326. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12327. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12328. state.pointShadow[ pointLength ] = shadowUniforms;
  12329. state.pointShadowMap[ pointLength ] = shadowMap;
  12330. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  12331. numPointShadows ++;
  12332. }
  12333. state.point[ pointLength ] = uniforms;
  12334. pointLength ++;
  12335. } else if ( light.isHemisphereLight ) {
  12336. const uniforms = cache.get( light );
  12337. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor );
  12338. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor );
  12339. state.hemi[ hemiLength ] = uniforms;
  12340. hemiLength ++;
  12341. }
  12342. }
  12343. if ( rectAreaLength > 0 ) {
  12344. if ( capabilities.isWebGL2 ) {
  12345. // WebGL 2
  12346. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12347. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12348. } else {
  12349. // WebGL 1
  12350. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  12351. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12352. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12353. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  12354. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12355. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12356. } else {
  12357. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  12358. }
  12359. }
  12360. }
  12361. state.ambient[ 0 ] = r;
  12362. state.ambient[ 1 ] = g;
  12363. state.ambient[ 2 ] = b;
  12364. const hash = state.hash;
  12365. if ( hash.directionalLength !== directionalLength ||
  12366. hash.pointLength !== pointLength ||
  12367. hash.spotLength !== spotLength ||
  12368. hash.rectAreaLength !== rectAreaLength ||
  12369. hash.hemiLength !== hemiLength ||
  12370. hash.numDirectionalShadows !== numDirectionalShadows ||
  12371. hash.numPointShadows !== numPointShadows ||
  12372. hash.numSpotShadows !== numSpotShadows ||
  12373. hash.numSpotMaps !== numSpotMaps ) {
  12374. state.directional.length = directionalLength;
  12375. state.spot.length = spotLength;
  12376. state.rectArea.length = rectAreaLength;
  12377. state.point.length = pointLength;
  12378. state.hemi.length = hemiLength;
  12379. state.directionalShadow.length = numDirectionalShadows;
  12380. state.directionalShadowMap.length = numDirectionalShadows;
  12381. state.pointShadow.length = numPointShadows;
  12382. state.pointShadowMap.length = numPointShadows;
  12383. state.spotShadow.length = numSpotShadows;
  12384. state.spotShadowMap.length = numSpotShadows;
  12385. state.directionalShadowMatrix.length = numDirectionalShadows;
  12386. state.pointShadowMatrix.length = numPointShadows;
  12387. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  12388. state.spotLightMap.length = numSpotMaps;
  12389. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  12390. hash.directionalLength = directionalLength;
  12391. hash.pointLength = pointLength;
  12392. hash.spotLength = spotLength;
  12393. hash.rectAreaLength = rectAreaLength;
  12394. hash.hemiLength = hemiLength;
  12395. hash.numDirectionalShadows = numDirectionalShadows;
  12396. hash.numPointShadows = numPointShadows;
  12397. hash.numSpotShadows = numSpotShadows;
  12398. hash.numSpotMaps = numSpotMaps;
  12399. state.version = nextVersion ++;
  12400. }
  12401. }
  12402. function setupView( lights, camera ) {
  12403. let directionalLength = 0;
  12404. let pointLength = 0;
  12405. let spotLength = 0;
  12406. let rectAreaLength = 0;
  12407. let hemiLength = 0;
  12408. const viewMatrix = camera.matrixWorldInverse;
  12409. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12410. const light = lights[ i ];
  12411. if ( light.isDirectionalLight ) {
  12412. const uniforms = state.directional[ directionalLength ];
  12413. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12414. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12415. uniforms.direction.sub( vector3 );
  12416. uniforms.direction.transformDirection( viewMatrix );
  12417. directionalLength ++;
  12418. } else if ( light.isSpotLight ) {
  12419. const uniforms = state.spot[ spotLength ];
  12420. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12421. uniforms.position.applyMatrix4( viewMatrix );
  12422. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12423. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12424. uniforms.direction.sub( vector3 );
  12425. uniforms.direction.transformDirection( viewMatrix );
  12426. spotLength ++;
  12427. } else if ( light.isRectAreaLight ) {
  12428. const uniforms = state.rectArea[ rectAreaLength ];
  12429. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12430. uniforms.position.applyMatrix4( viewMatrix );
  12431. // extract local rotation of light to derive width/height half vectors
  12432. matrix42.identity();
  12433. matrix4.copy( light.matrixWorld );
  12434. matrix4.premultiply( viewMatrix );
  12435. matrix42.extractRotation( matrix4 );
  12436. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12437. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12438. uniforms.halfWidth.applyMatrix4( matrix42 );
  12439. uniforms.halfHeight.applyMatrix4( matrix42 );
  12440. rectAreaLength ++;
  12441. } else if ( light.isPointLight ) {
  12442. const uniforms = state.point[ pointLength ];
  12443. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12444. uniforms.position.applyMatrix4( viewMatrix );
  12445. pointLength ++;
  12446. } else if ( light.isHemisphereLight ) {
  12447. const uniforms = state.hemi[ hemiLength ];
  12448. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12449. uniforms.direction.transformDirection( viewMatrix );
  12450. hemiLength ++;
  12451. }
  12452. }
  12453. }
  12454. return {
  12455. setup: setup,
  12456. setupView: setupView,
  12457. state: state
  12458. };
  12459. }
  12460. function WebGLRenderState( extensions, capabilities ) {
  12461. const lights = new WebGLLights( extensions, capabilities );
  12462. const lightsArray = [];
  12463. const shadowsArray = [];
  12464. function init() {
  12465. lightsArray.length = 0;
  12466. shadowsArray.length = 0;
  12467. }
  12468. function pushLight( light ) {
  12469. lightsArray.push( light );
  12470. }
  12471. function pushShadow( shadowLight ) {
  12472. shadowsArray.push( shadowLight );
  12473. }
  12474. function setupLights( physicallyCorrectLights ) {
  12475. lights.setup( lightsArray, physicallyCorrectLights );
  12476. }
  12477. function setupLightsView( camera ) {
  12478. lights.setupView( lightsArray, camera );
  12479. }
  12480. const state = {
  12481. lightsArray: lightsArray,
  12482. shadowsArray: shadowsArray,
  12483. lights: lights
  12484. };
  12485. return {
  12486. init: init,
  12487. state: state,
  12488. setupLights: setupLights,
  12489. setupLightsView: setupLightsView,
  12490. pushLight: pushLight,
  12491. pushShadow: pushShadow
  12492. };
  12493. }
  12494. function WebGLRenderStates( extensions, capabilities ) {
  12495. let renderStates = new WeakMap();
  12496. function get( scene, renderCallDepth = 0 ) {
  12497. const renderStateArray = renderStates.get( scene );
  12498. let renderState;
  12499. if ( renderStateArray === undefined ) {
  12500. renderState = new WebGLRenderState( extensions, capabilities );
  12501. renderStates.set( scene, [ renderState ] );
  12502. } else {
  12503. if ( renderCallDepth >= renderStateArray.length ) {
  12504. renderState = new WebGLRenderState( extensions, capabilities );
  12505. renderStateArray.push( renderState );
  12506. } else {
  12507. renderState = renderStateArray[ renderCallDepth ];
  12508. }
  12509. }
  12510. return renderState;
  12511. }
  12512. function dispose() {
  12513. renderStates = new WeakMap();
  12514. }
  12515. return {
  12516. get: get,
  12517. dispose: dispose
  12518. };
  12519. }
  12520. class MeshDepthMaterial extends Material {
  12521. constructor( parameters ) {
  12522. super();
  12523. this.isMeshDepthMaterial = true;
  12524. this.type = 'MeshDepthMaterial';
  12525. this.depthPacking = BasicDepthPacking;
  12526. this.map = null;
  12527. this.alphaMap = null;
  12528. this.displacementMap = null;
  12529. this.displacementScale = 1;
  12530. this.displacementBias = 0;
  12531. this.wireframe = false;
  12532. this.wireframeLinewidth = 1;
  12533. this.setValues( parameters );
  12534. }
  12535. copy( source ) {
  12536. super.copy( source );
  12537. this.depthPacking = source.depthPacking;
  12538. this.map = source.map;
  12539. this.alphaMap = source.alphaMap;
  12540. this.displacementMap = source.displacementMap;
  12541. this.displacementScale = source.displacementScale;
  12542. this.displacementBias = source.displacementBias;
  12543. this.wireframe = source.wireframe;
  12544. this.wireframeLinewidth = source.wireframeLinewidth;
  12545. return this;
  12546. }
  12547. }
  12548. class MeshDistanceMaterial extends Material {
  12549. constructor( parameters ) {
  12550. super();
  12551. this.isMeshDistanceMaterial = true;
  12552. this.type = 'MeshDistanceMaterial';
  12553. this.referencePosition = new Vector3();
  12554. this.nearDistance = 1;
  12555. this.farDistance = 1000;
  12556. this.map = null;
  12557. this.alphaMap = null;
  12558. this.displacementMap = null;
  12559. this.displacementScale = 1;
  12560. this.displacementBias = 0;
  12561. this.setValues( parameters );
  12562. }
  12563. copy( source ) {
  12564. super.copy( source );
  12565. this.referencePosition.copy( source.referencePosition );
  12566. this.nearDistance = source.nearDistance;
  12567. this.farDistance = source.farDistance;
  12568. this.map = source.map;
  12569. this.alphaMap = source.alphaMap;
  12570. this.displacementMap = source.displacementMap;
  12571. this.displacementScale = source.displacementScale;
  12572. this.displacementBias = source.displacementBias;
  12573. return this;
  12574. }
  12575. }
  12576. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12577. 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}";
  12578. function WebGLShadowMap( _renderer, _objects, _capabilities ) {
  12579. let _frustum = new Frustum();
  12580. const _shadowMapSize = new Vector2(),
  12581. _viewportSize = new Vector2(),
  12582. _viewport = new Vector4(),
  12583. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  12584. _distanceMaterial = new MeshDistanceMaterial(),
  12585. _materialCache = {},
  12586. _maxTextureSize = _capabilities.maxTextureSize;
  12587. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  12588. const shadowMaterialVertical = new ShaderMaterial( {
  12589. defines: {
  12590. VSM_SAMPLES: 8
  12591. },
  12592. uniforms: {
  12593. shadow_pass: { value: null },
  12594. resolution: { value: new Vector2() },
  12595. radius: { value: 4.0 }
  12596. },
  12597. vertexShader: vertex,
  12598. fragmentShader: fragment
  12599. } );
  12600. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12601. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12602. const fullScreenTri = new BufferGeometry();
  12603. fullScreenTri.setAttribute(
  12604. 'position',
  12605. new BufferAttribute(
  12606. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  12607. 3
  12608. )
  12609. );
  12610. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  12611. const scope = this;
  12612. this.enabled = false;
  12613. this.autoUpdate = true;
  12614. this.needsUpdate = false;
  12615. this.type = PCFShadowMap;
  12616. this.render = function ( lights, scene, camera ) {
  12617. if ( scope.enabled === false ) return;
  12618. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  12619. if ( lights.length === 0 ) return;
  12620. const currentRenderTarget = _renderer.getRenderTarget();
  12621. const activeCubeFace = _renderer.getActiveCubeFace();
  12622. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12623. const _state = _renderer.state;
  12624. // Set GL state for depth map.
  12625. _state.setBlending( NoBlending );
  12626. _state.buffers.color.setClear( 1, 1, 1, 1 );
  12627. _state.buffers.depth.setTest( true );
  12628. _state.setScissorTest( false );
  12629. // render depth map
  12630. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  12631. const light = lights[ i ];
  12632. const shadow = light.shadow;
  12633. if ( shadow === undefined ) {
  12634. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  12635. continue;
  12636. }
  12637. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  12638. _shadowMapSize.copy( shadow.mapSize );
  12639. const shadowFrameExtents = shadow.getFrameExtents();
  12640. _shadowMapSize.multiply( shadowFrameExtents );
  12641. _viewportSize.copy( shadow.mapSize );
  12642. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  12643. if ( _shadowMapSize.x > _maxTextureSize ) {
  12644. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  12645. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12646. shadow.mapSize.x = _viewportSize.x;
  12647. }
  12648. if ( _shadowMapSize.y > _maxTextureSize ) {
  12649. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  12650. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12651. shadow.mapSize.y = _viewportSize.y;
  12652. }
  12653. }
  12654. if ( shadow.map === null ) {
  12655. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  12656. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12657. shadow.map.texture.name = light.name + '.shadowMap';
  12658. shadow.camera.updateProjectionMatrix();
  12659. }
  12660. _renderer.setRenderTarget( shadow.map );
  12661. _renderer.clear();
  12662. const viewportCount = shadow.getViewportCount();
  12663. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  12664. const viewport = shadow.getViewport( vp );
  12665. _viewport.set(
  12666. _viewportSize.x * viewport.x,
  12667. _viewportSize.y * viewport.y,
  12668. _viewportSize.x * viewport.z,
  12669. _viewportSize.y * viewport.w
  12670. );
  12671. _state.viewport( _viewport );
  12672. shadow.updateMatrices( light, vp );
  12673. _frustum = shadow.getFrustum();
  12674. renderObject( scene, camera, shadow.camera, light, this.type );
  12675. }
  12676. // do blur pass for VSM
  12677. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  12678. VSMPass( shadow, camera );
  12679. }
  12680. shadow.needsUpdate = false;
  12681. }
  12682. scope.needsUpdate = false;
  12683. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  12684. };
  12685. function VSMPass( shadow, camera ) {
  12686. const geometry = _objects.update( fullScreenMesh );
  12687. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  12688. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  12689. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  12690. shadowMaterialVertical.needsUpdate = true;
  12691. shadowMaterialHorizontal.needsUpdate = true;
  12692. }
  12693. if ( shadow.mapPass === null ) {
  12694. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  12695. }
  12696. // vertical pass
  12697. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12698. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12699. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12700. _renderer.setRenderTarget( shadow.mapPass );
  12701. _renderer.clear();
  12702. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  12703. // horizontal pass
  12704. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12705. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12706. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12707. _renderer.setRenderTarget( shadow.map );
  12708. _renderer.clear();
  12709. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  12710. }
  12711. function getDepthMaterial( object, material, light, shadowCameraNear, shadowCameraFar, type ) {
  12712. let result = null;
  12713. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  12714. if ( customMaterial !== undefined ) {
  12715. result = customMaterial;
  12716. } else {
  12717. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  12718. if ( ( _renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  12719. ( material.displacementMap && material.displacementScale !== 0 ) ||
  12720. ( material.alphaMap && material.alphaTest > 0 ) ||
  12721. ( material.map && material.alphaTest > 0 ) ) {
  12722. // in this case we need a unique material instance reflecting the
  12723. // appropriate state
  12724. const keyA = result.uuid, keyB = material.uuid;
  12725. let materialsForVariant = _materialCache[ keyA ];
  12726. if ( materialsForVariant === undefined ) {
  12727. materialsForVariant = {};
  12728. _materialCache[ keyA ] = materialsForVariant;
  12729. }
  12730. let cachedMaterial = materialsForVariant[ keyB ];
  12731. if ( cachedMaterial === undefined ) {
  12732. cachedMaterial = result.clone();
  12733. materialsForVariant[ keyB ] = cachedMaterial;
  12734. }
  12735. result = cachedMaterial;
  12736. }
  12737. }
  12738. result.visible = material.visible;
  12739. result.wireframe = material.wireframe;
  12740. if ( type === VSMShadowMap ) {
  12741. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  12742. } else {
  12743. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  12744. }
  12745. result.alphaMap = material.alphaMap;
  12746. result.alphaTest = material.alphaTest;
  12747. result.map = material.map;
  12748. result.clipShadows = material.clipShadows;
  12749. result.clippingPlanes = material.clippingPlanes;
  12750. result.clipIntersection = material.clipIntersection;
  12751. result.displacementMap = material.displacementMap;
  12752. result.displacementScale = material.displacementScale;
  12753. result.displacementBias = material.displacementBias;
  12754. result.wireframeLinewidth = material.wireframeLinewidth;
  12755. result.linewidth = material.linewidth;
  12756. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  12757. result.referencePosition.setFromMatrixPosition( light.matrixWorld );
  12758. result.nearDistance = shadowCameraNear;
  12759. result.farDistance = shadowCameraFar;
  12760. }
  12761. return result;
  12762. }
  12763. function renderObject( object, camera, shadowCamera, light, type ) {
  12764. if ( object.visible === false ) return;
  12765. const visible = object.layers.test( camera.layers );
  12766. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  12767. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  12768. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  12769. const geometry = _objects.update( object );
  12770. const material = object.material;
  12771. if ( Array.isArray( material ) ) {
  12772. const groups = geometry.groups;
  12773. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  12774. const group = groups[ k ];
  12775. const groupMaterial = material[ group.materialIndex ];
  12776. if ( groupMaterial && groupMaterial.visible ) {
  12777. const depthMaterial = getDepthMaterial( object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );
  12778. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  12779. }
  12780. }
  12781. } else if ( material.visible ) {
  12782. const depthMaterial = getDepthMaterial( object, material, light, shadowCamera.near, shadowCamera.far, type );
  12783. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  12784. }
  12785. }
  12786. }
  12787. const children = object.children;
  12788. for ( let i = 0, l = children.length; i < l; i ++ ) {
  12789. renderObject( children[ i ], camera, shadowCamera, light, type );
  12790. }
  12791. }
  12792. }
  12793. function WebGLState( gl, extensions, capabilities ) {
  12794. const isWebGL2 = capabilities.isWebGL2;
  12795. function ColorBuffer() {
  12796. let locked = false;
  12797. const color = new Vector4();
  12798. let currentColorMask = null;
  12799. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  12800. return {
  12801. setMask: function ( colorMask ) {
  12802. if ( currentColorMask !== colorMask && ! locked ) {
  12803. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  12804. currentColorMask = colorMask;
  12805. }
  12806. },
  12807. setLocked: function ( lock ) {
  12808. locked = lock;
  12809. },
  12810. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  12811. if ( premultipliedAlpha === true ) {
  12812. r *= a; g *= a; b *= a;
  12813. }
  12814. color.set( r, g, b, a );
  12815. if ( currentColorClear.equals( color ) === false ) {
  12816. gl.clearColor( r, g, b, a );
  12817. currentColorClear.copy( color );
  12818. }
  12819. },
  12820. reset: function () {
  12821. locked = false;
  12822. currentColorMask = null;
  12823. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  12824. }
  12825. };
  12826. }
  12827. function DepthBuffer() {
  12828. let locked = false;
  12829. let currentDepthMask = null;
  12830. let currentDepthFunc = null;
  12831. let currentDepthClear = null;
  12832. return {
  12833. setTest: function ( depthTest ) {
  12834. if ( depthTest ) {
  12835. enable( 2929 );
  12836. } else {
  12837. disable( 2929 );
  12838. }
  12839. },
  12840. setMask: function ( depthMask ) {
  12841. if ( currentDepthMask !== depthMask && ! locked ) {
  12842. gl.depthMask( depthMask );
  12843. currentDepthMask = depthMask;
  12844. }
  12845. },
  12846. setFunc: function ( depthFunc ) {
  12847. if ( currentDepthFunc !== depthFunc ) {
  12848. switch ( depthFunc ) {
  12849. case NeverDepth:
  12850. gl.depthFunc( 512 );
  12851. break;
  12852. case AlwaysDepth:
  12853. gl.depthFunc( 519 );
  12854. break;
  12855. case LessDepth:
  12856. gl.depthFunc( 513 );
  12857. break;
  12858. case LessEqualDepth:
  12859. gl.depthFunc( 515 );
  12860. break;
  12861. case EqualDepth:
  12862. gl.depthFunc( 514 );
  12863. break;
  12864. case GreaterEqualDepth:
  12865. gl.depthFunc( 518 );
  12866. break;
  12867. case GreaterDepth:
  12868. gl.depthFunc( 516 );
  12869. break;
  12870. case NotEqualDepth:
  12871. gl.depthFunc( 517 );
  12872. break;
  12873. default:
  12874. gl.depthFunc( 515 );
  12875. }
  12876. currentDepthFunc = depthFunc;
  12877. }
  12878. },
  12879. setLocked: function ( lock ) {
  12880. locked = lock;
  12881. },
  12882. setClear: function ( depth ) {
  12883. if ( currentDepthClear !== depth ) {
  12884. gl.clearDepth( depth );
  12885. currentDepthClear = depth;
  12886. }
  12887. },
  12888. reset: function () {
  12889. locked = false;
  12890. currentDepthMask = null;
  12891. currentDepthFunc = null;
  12892. currentDepthClear = null;
  12893. }
  12894. };
  12895. }
  12896. function StencilBuffer() {
  12897. let locked = false;
  12898. let currentStencilMask = null;
  12899. let currentStencilFunc = null;
  12900. let currentStencilRef = null;
  12901. let currentStencilFuncMask = null;
  12902. let currentStencilFail = null;
  12903. let currentStencilZFail = null;
  12904. let currentStencilZPass = null;
  12905. let currentStencilClear = null;
  12906. return {
  12907. setTest: function ( stencilTest ) {
  12908. if ( ! locked ) {
  12909. if ( stencilTest ) {
  12910. enable( 2960 );
  12911. } else {
  12912. disable( 2960 );
  12913. }
  12914. }
  12915. },
  12916. setMask: function ( stencilMask ) {
  12917. if ( currentStencilMask !== stencilMask && ! locked ) {
  12918. gl.stencilMask( stencilMask );
  12919. currentStencilMask = stencilMask;
  12920. }
  12921. },
  12922. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  12923. if ( currentStencilFunc !== stencilFunc ||
  12924. currentStencilRef !== stencilRef ||
  12925. currentStencilFuncMask !== stencilMask ) {
  12926. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  12927. currentStencilFunc = stencilFunc;
  12928. currentStencilRef = stencilRef;
  12929. currentStencilFuncMask = stencilMask;
  12930. }
  12931. },
  12932. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  12933. if ( currentStencilFail !== stencilFail ||
  12934. currentStencilZFail !== stencilZFail ||
  12935. currentStencilZPass !== stencilZPass ) {
  12936. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  12937. currentStencilFail = stencilFail;
  12938. currentStencilZFail = stencilZFail;
  12939. currentStencilZPass = stencilZPass;
  12940. }
  12941. },
  12942. setLocked: function ( lock ) {
  12943. locked = lock;
  12944. },
  12945. setClear: function ( stencil ) {
  12946. if ( currentStencilClear !== stencil ) {
  12947. gl.clearStencil( stencil );
  12948. currentStencilClear = stencil;
  12949. }
  12950. },
  12951. reset: function () {
  12952. locked = false;
  12953. currentStencilMask = null;
  12954. currentStencilFunc = null;
  12955. currentStencilRef = null;
  12956. currentStencilFuncMask = null;
  12957. currentStencilFail = null;
  12958. currentStencilZFail = null;
  12959. currentStencilZPass = null;
  12960. currentStencilClear = null;
  12961. }
  12962. };
  12963. }
  12964. //
  12965. const colorBuffer = new ColorBuffer();
  12966. const depthBuffer = new DepthBuffer();
  12967. const stencilBuffer = new StencilBuffer();
  12968. const uboBindings = new WeakMap();
  12969. const uboProgramMap = new WeakMap();
  12970. let enabledCapabilities = {};
  12971. let currentBoundFramebuffers = {};
  12972. let currentDrawbuffers = new WeakMap();
  12973. let defaultDrawbuffers = [];
  12974. let currentProgram = null;
  12975. let currentBlendingEnabled = false;
  12976. let currentBlending = null;
  12977. let currentBlendEquation = null;
  12978. let currentBlendSrc = null;
  12979. let currentBlendDst = null;
  12980. let currentBlendEquationAlpha = null;
  12981. let currentBlendSrcAlpha = null;
  12982. let currentBlendDstAlpha = null;
  12983. let currentPremultipledAlpha = false;
  12984. let currentFlipSided = null;
  12985. let currentCullFace = null;
  12986. let currentLineWidth = null;
  12987. let currentPolygonOffsetFactor = null;
  12988. let currentPolygonOffsetUnits = null;
  12989. const maxTextures = gl.getParameter( 35661 );
  12990. let lineWidthAvailable = false;
  12991. let version = 0;
  12992. const glVersion = gl.getParameter( 7938 );
  12993. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  12994. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  12995. lineWidthAvailable = ( version >= 1.0 );
  12996. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  12997. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  12998. lineWidthAvailable = ( version >= 2.0 );
  12999. }
  13000. let currentTextureSlot = null;
  13001. let currentBoundTextures = {};
  13002. const scissorParam = gl.getParameter( 3088 );
  13003. const viewportParam = gl.getParameter( 2978 );
  13004. const currentScissor = new Vector4().fromArray( scissorParam );
  13005. const currentViewport = new Vector4().fromArray( viewportParam );
  13006. function createTexture( type, target, count ) {
  13007. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  13008. const texture = gl.createTexture();
  13009. gl.bindTexture( type, texture );
  13010. gl.texParameteri( type, 10241, 9728 );
  13011. gl.texParameteri( type, 10240, 9728 );
  13012. for ( let i = 0; i < count; i ++ ) {
  13013. gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
  13014. }
  13015. return texture;
  13016. }
  13017. const emptyTextures = {};
  13018. emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
  13019. emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
  13020. // init
  13021. colorBuffer.setClear( 0, 0, 0, 1 );
  13022. depthBuffer.setClear( 1 );
  13023. stencilBuffer.setClear( 0 );
  13024. enable( 2929 );
  13025. depthBuffer.setFunc( LessEqualDepth );
  13026. setFlipSided( false );
  13027. setCullFace( CullFaceBack );
  13028. enable( 2884 );
  13029. setBlending( NoBlending );
  13030. //
  13031. function enable( id ) {
  13032. if ( enabledCapabilities[ id ] !== true ) {
  13033. gl.enable( id );
  13034. enabledCapabilities[ id ] = true;
  13035. }
  13036. }
  13037. function disable( id ) {
  13038. if ( enabledCapabilities[ id ] !== false ) {
  13039. gl.disable( id );
  13040. enabledCapabilities[ id ] = false;
  13041. }
  13042. }
  13043. function bindFramebuffer( target, framebuffer ) {
  13044. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  13045. gl.bindFramebuffer( target, framebuffer );
  13046. currentBoundFramebuffers[ target ] = framebuffer;
  13047. if ( isWebGL2 ) {
  13048. // 36009 is equivalent to 36160
  13049. if ( target === 36009 ) {
  13050. currentBoundFramebuffers[ 36160 ] = framebuffer;
  13051. }
  13052. if ( target === 36160 ) {
  13053. currentBoundFramebuffers[ 36009 ] = framebuffer;
  13054. }
  13055. }
  13056. return true;
  13057. }
  13058. return false;
  13059. }
  13060. function drawBuffers( renderTarget, framebuffer ) {
  13061. let drawBuffers = defaultDrawbuffers;
  13062. let needsUpdate = false;
  13063. if ( renderTarget ) {
  13064. drawBuffers = currentDrawbuffers.get( framebuffer );
  13065. if ( drawBuffers === undefined ) {
  13066. drawBuffers = [];
  13067. currentDrawbuffers.set( framebuffer, drawBuffers );
  13068. }
  13069. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13070. const textures = renderTarget.texture;
  13071. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== 36064 ) {
  13072. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13073. drawBuffers[ i ] = 36064 + i;
  13074. }
  13075. drawBuffers.length = textures.length;
  13076. needsUpdate = true;
  13077. }
  13078. } else {
  13079. if ( drawBuffers[ 0 ] !== 36064 ) {
  13080. drawBuffers[ 0 ] = 36064;
  13081. needsUpdate = true;
  13082. }
  13083. }
  13084. } else {
  13085. if ( drawBuffers[ 0 ] !== 1029 ) {
  13086. drawBuffers[ 0 ] = 1029;
  13087. needsUpdate = true;
  13088. }
  13089. }
  13090. if ( needsUpdate ) {
  13091. if ( capabilities.isWebGL2 ) {
  13092. gl.drawBuffers( drawBuffers );
  13093. } else {
  13094. extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers );
  13095. }
  13096. }
  13097. }
  13098. function useProgram( program ) {
  13099. if ( currentProgram !== program ) {
  13100. gl.useProgram( program );
  13101. currentProgram = program;
  13102. return true;
  13103. }
  13104. return false;
  13105. }
  13106. const equationToGL = {
  13107. [ AddEquation ]: 32774,
  13108. [ SubtractEquation ]: 32778,
  13109. [ ReverseSubtractEquation ]: 32779
  13110. };
  13111. if ( isWebGL2 ) {
  13112. equationToGL[ MinEquation ] = 32775;
  13113. equationToGL[ MaxEquation ] = 32776;
  13114. } else {
  13115. const extension = extensions.get( 'EXT_blend_minmax' );
  13116. if ( extension !== null ) {
  13117. equationToGL[ MinEquation ] = extension.MIN_EXT;
  13118. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  13119. }
  13120. }
  13121. const factorToGL = {
  13122. [ ZeroFactor ]: 0,
  13123. [ OneFactor ]: 1,
  13124. [ SrcColorFactor ]: 768,
  13125. [ SrcAlphaFactor ]: 770,
  13126. [ SrcAlphaSaturateFactor ]: 776,
  13127. [ DstColorFactor ]: 774,
  13128. [ DstAlphaFactor ]: 772,
  13129. [ OneMinusSrcColorFactor ]: 769,
  13130. [ OneMinusSrcAlphaFactor ]: 771,
  13131. [ OneMinusDstColorFactor ]: 775,
  13132. [ OneMinusDstAlphaFactor ]: 773
  13133. };
  13134. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  13135. if ( blending === NoBlending ) {
  13136. if ( currentBlendingEnabled === true ) {
  13137. disable( 3042 );
  13138. currentBlendingEnabled = false;
  13139. }
  13140. return;
  13141. }
  13142. if ( currentBlendingEnabled === false ) {
  13143. enable( 3042 );
  13144. currentBlendingEnabled = true;
  13145. }
  13146. if ( blending !== CustomBlending ) {
  13147. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  13148. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  13149. gl.blendEquation( 32774 );
  13150. currentBlendEquation = AddEquation;
  13151. currentBlendEquationAlpha = AddEquation;
  13152. }
  13153. if ( premultipliedAlpha ) {
  13154. switch ( blending ) {
  13155. case NormalBlending:
  13156. gl.blendFuncSeparate( 1, 771, 1, 771 );
  13157. break;
  13158. case AdditiveBlending:
  13159. gl.blendFunc( 1, 1 );
  13160. break;
  13161. case SubtractiveBlending:
  13162. gl.blendFuncSeparate( 0, 769, 0, 1 );
  13163. break;
  13164. case MultiplyBlending:
  13165. gl.blendFuncSeparate( 0, 768, 0, 770 );
  13166. break;
  13167. default:
  13168. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13169. break;
  13170. }
  13171. } else {
  13172. switch ( blending ) {
  13173. case NormalBlending:
  13174. gl.blendFuncSeparate( 770, 771, 1, 771 );
  13175. break;
  13176. case AdditiveBlending:
  13177. gl.blendFunc( 770, 1 );
  13178. break;
  13179. case SubtractiveBlending:
  13180. gl.blendFuncSeparate( 0, 769, 0, 1 );
  13181. break;
  13182. case MultiplyBlending:
  13183. gl.blendFunc( 0, 768 );
  13184. break;
  13185. default:
  13186. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13187. break;
  13188. }
  13189. }
  13190. currentBlendSrc = null;
  13191. currentBlendDst = null;
  13192. currentBlendSrcAlpha = null;
  13193. currentBlendDstAlpha = null;
  13194. currentBlending = blending;
  13195. currentPremultipledAlpha = premultipliedAlpha;
  13196. }
  13197. return;
  13198. }
  13199. // custom blending
  13200. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13201. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13202. blendDstAlpha = blendDstAlpha || blendDst;
  13203. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  13204. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  13205. currentBlendEquation = blendEquation;
  13206. currentBlendEquationAlpha = blendEquationAlpha;
  13207. }
  13208. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  13209. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  13210. currentBlendSrc = blendSrc;
  13211. currentBlendDst = blendDst;
  13212. currentBlendSrcAlpha = blendSrcAlpha;
  13213. currentBlendDstAlpha = blendDstAlpha;
  13214. }
  13215. currentBlending = blending;
  13216. currentPremultipledAlpha = false;
  13217. }
  13218. function setMaterial( material, frontFaceCW ) {
  13219. material.side === DoubleSide
  13220. ? disable( 2884 )
  13221. : enable( 2884 );
  13222. let flipSided = ( material.side === BackSide );
  13223. if ( frontFaceCW ) flipSided = ! flipSided;
  13224. setFlipSided( flipSided );
  13225. ( material.blending === NormalBlending && material.transparent === false )
  13226. ? setBlending( NoBlending )
  13227. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  13228. depthBuffer.setFunc( material.depthFunc );
  13229. depthBuffer.setTest( material.depthTest );
  13230. depthBuffer.setMask( material.depthWrite );
  13231. colorBuffer.setMask( material.colorWrite );
  13232. const stencilWrite = material.stencilWrite;
  13233. stencilBuffer.setTest( stencilWrite );
  13234. if ( stencilWrite ) {
  13235. stencilBuffer.setMask( material.stencilWriteMask );
  13236. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  13237. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  13238. }
  13239. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13240. material.alphaToCoverage === true
  13241. ? enable( 32926 )
  13242. : disable( 32926 );
  13243. }
  13244. //
  13245. function setFlipSided( flipSided ) {
  13246. if ( currentFlipSided !== flipSided ) {
  13247. if ( flipSided ) {
  13248. gl.frontFace( 2304 );
  13249. } else {
  13250. gl.frontFace( 2305 );
  13251. }
  13252. currentFlipSided = flipSided;
  13253. }
  13254. }
  13255. function setCullFace( cullFace ) {
  13256. if ( cullFace !== CullFaceNone ) {
  13257. enable( 2884 );
  13258. if ( cullFace !== currentCullFace ) {
  13259. if ( cullFace === CullFaceBack ) {
  13260. gl.cullFace( 1029 );
  13261. } else if ( cullFace === CullFaceFront ) {
  13262. gl.cullFace( 1028 );
  13263. } else {
  13264. gl.cullFace( 1032 );
  13265. }
  13266. }
  13267. } else {
  13268. disable( 2884 );
  13269. }
  13270. currentCullFace = cullFace;
  13271. }
  13272. function setLineWidth( width ) {
  13273. if ( width !== currentLineWidth ) {
  13274. if ( lineWidthAvailable ) gl.lineWidth( width );
  13275. currentLineWidth = width;
  13276. }
  13277. }
  13278. function setPolygonOffset( polygonOffset, factor, units ) {
  13279. if ( polygonOffset ) {
  13280. enable( 32823 );
  13281. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  13282. gl.polygonOffset( factor, units );
  13283. currentPolygonOffsetFactor = factor;
  13284. currentPolygonOffsetUnits = units;
  13285. }
  13286. } else {
  13287. disable( 32823 );
  13288. }
  13289. }
  13290. function setScissorTest( scissorTest ) {
  13291. if ( scissorTest ) {
  13292. enable( 3089 );
  13293. } else {
  13294. disable( 3089 );
  13295. }
  13296. }
  13297. // texture
  13298. function activeTexture( webglSlot ) {
  13299. if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1;
  13300. if ( currentTextureSlot !== webglSlot ) {
  13301. gl.activeTexture( webglSlot );
  13302. currentTextureSlot = webglSlot;
  13303. }
  13304. }
  13305. function bindTexture( webglType, webglTexture, webglSlot ) {
  13306. if ( webglSlot === undefined ) {
  13307. if ( currentTextureSlot === null ) {
  13308. webglSlot = 33984 + maxTextures - 1;
  13309. } else {
  13310. webglSlot = currentTextureSlot;
  13311. }
  13312. }
  13313. let boundTexture = currentBoundTextures[ webglSlot ];
  13314. if ( boundTexture === undefined ) {
  13315. boundTexture = { type: undefined, texture: undefined };
  13316. currentBoundTextures[ webglSlot ] = boundTexture;
  13317. }
  13318. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  13319. if ( currentTextureSlot !== webglSlot ) {
  13320. gl.activeTexture( webglSlot );
  13321. currentTextureSlot = webglSlot;
  13322. }
  13323. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  13324. boundTexture.type = webglType;
  13325. boundTexture.texture = webglTexture;
  13326. }
  13327. }
  13328. function unbindTexture() {
  13329. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  13330. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  13331. gl.bindTexture( boundTexture.type, null );
  13332. boundTexture.type = undefined;
  13333. boundTexture.texture = undefined;
  13334. }
  13335. }
  13336. function compressedTexImage2D() {
  13337. try {
  13338. gl.compressedTexImage2D.apply( gl, arguments );
  13339. } catch ( error ) {
  13340. console.error( 'THREE.WebGLState:', error );
  13341. }
  13342. }
  13343. function compressedTexImage3D() {
  13344. try {
  13345. gl.compressedTexImage3D.apply( gl, arguments );
  13346. } catch ( error ) {
  13347. console.error( 'THREE.WebGLState:', error );
  13348. }
  13349. }
  13350. function texSubImage2D() {
  13351. try {
  13352. gl.texSubImage2D.apply( gl, arguments );
  13353. } catch ( error ) {
  13354. console.error( 'THREE.WebGLState:', error );
  13355. }
  13356. }
  13357. function texSubImage3D() {
  13358. try {
  13359. gl.texSubImage3D.apply( gl, arguments );
  13360. } catch ( error ) {
  13361. console.error( 'THREE.WebGLState:', error );
  13362. }
  13363. }
  13364. function compressedTexSubImage2D() {
  13365. try {
  13366. gl.compressedTexSubImage2D.apply( gl, arguments );
  13367. } catch ( error ) {
  13368. console.error( 'THREE.WebGLState:', error );
  13369. }
  13370. }
  13371. function compressedTexSubImage3D() {
  13372. try {
  13373. gl.compressedTexSubImage3D.apply( gl, arguments );
  13374. } catch ( error ) {
  13375. console.error( 'THREE.WebGLState:', error );
  13376. }
  13377. }
  13378. function texStorage2D() {
  13379. try {
  13380. gl.texStorage2D.apply( gl, arguments );
  13381. } catch ( error ) {
  13382. console.error( 'THREE.WebGLState:', error );
  13383. }
  13384. }
  13385. function texStorage3D() {
  13386. try {
  13387. gl.texStorage3D.apply( gl, arguments );
  13388. } catch ( error ) {
  13389. console.error( 'THREE.WebGLState:', error );
  13390. }
  13391. }
  13392. function texImage2D() {
  13393. try {
  13394. gl.texImage2D.apply( gl, arguments );
  13395. } catch ( error ) {
  13396. console.error( 'THREE.WebGLState:', error );
  13397. }
  13398. }
  13399. function texImage3D() {
  13400. try {
  13401. gl.texImage3D.apply( gl, arguments );
  13402. } catch ( error ) {
  13403. console.error( 'THREE.WebGLState:', error );
  13404. }
  13405. }
  13406. //
  13407. function scissor( scissor ) {
  13408. if ( currentScissor.equals( scissor ) === false ) {
  13409. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  13410. currentScissor.copy( scissor );
  13411. }
  13412. }
  13413. function viewport( viewport ) {
  13414. if ( currentViewport.equals( viewport ) === false ) {
  13415. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  13416. currentViewport.copy( viewport );
  13417. }
  13418. }
  13419. function updateUBOMapping( uniformsGroup, program ) {
  13420. let mapping = uboProgramMap.get( program );
  13421. if ( mapping === undefined ) {
  13422. mapping = new WeakMap();
  13423. uboProgramMap.set( program, mapping );
  13424. }
  13425. let blockIndex = mapping.get( uniformsGroup );
  13426. if ( blockIndex === undefined ) {
  13427. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  13428. mapping.set( uniformsGroup, blockIndex );
  13429. }
  13430. }
  13431. function uniformBlockBinding( uniformsGroup, program ) {
  13432. const mapping = uboProgramMap.get( program );
  13433. const blockIndex = mapping.get( uniformsGroup );
  13434. if ( uboBindings.get( program ) !== blockIndex ) {
  13435. // bind shader specific block index to global block point
  13436. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  13437. uboBindings.set( program, blockIndex );
  13438. }
  13439. }
  13440. //
  13441. function reset() {
  13442. // reset state
  13443. gl.disable( 3042 );
  13444. gl.disable( 2884 );
  13445. gl.disable( 2929 );
  13446. gl.disable( 32823 );
  13447. gl.disable( 3089 );
  13448. gl.disable( 2960 );
  13449. gl.disable( 32926 );
  13450. gl.blendEquation( 32774 );
  13451. gl.blendFunc( 1, 0 );
  13452. gl.blendFuncSeparate( 1, 0, 1, 0 );
  13453. gl.colorMask( true, true, true, true );
  13454. gl.clearColor( 0, 0, 0, 0 );
  13455. gl.depthMask( true );
  13456. gl.depthFunc( 513 );
  13457. gl.clearDepth( 1 );
  13458. gl.stencilMask( 0xffffffff );
  13459. gl.stencilFunc( 519, 0, 0xffffffff );
  13460. gl.stencilOp( 7680, 7680, 7680 );
  13461. gl.clearStencil( 0 );
  13462. gl.cullFace( 1029 );
  13463. gl.frontFace( 2305 );
  13464. gl.polygonOffset( 0, 0 );
  13465. gl.activeTexture( 33984 );
  13466. gl.bindFramebuffer( 36160, null );
  13467. if ( isWebGL2 === true ) {
  13468. gl.bindFramebuffer( 36009, null );
  13469. gl.bindFramebuffer( 36008, null );
  13470. }
  13471. gl.useProgram( null );
  13472. gl.lineWidth( 1 );
  13473. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  13474. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  13475. // reset internals
  13476. enabledCapabilities = {};
  13477. currentTextureSlot = null;
  13478. currentBoundTextures = {};
  13479. currentBoundFramebuffers = {};
  13480. currentDrawbuffers = new WeakMap();
  13481. defaultDrawbuffers = [];
  13482. currentProgram = null;
  13483. currentBlendingEnabled = false;
  13484. currentBlending = null;
  13485. currentBlendEquation = null;
  13486. currentBlendSrc = null;
  13487. currentBlendDst = null;
  13488. currentBlendEquationAlpha = null;
  13489. currentBlendSrcAlpha = null;
  13490. currentBlendDstAlpha = null;
  13491. currentPremultipledAlpha = false;
  13492. currentFlipSided = null;
  13493. currentCullFace = null;
  13494. currentLineWidth = null;
  13495. currentPolygonOffsetFactor = null;
  13496. currentPolygonOffsetUnits = null;
  13497. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13498. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13499. colorBuffer.reset();
  13500. depthBuffer.reset();
  13501. stencilBuffer.reset();
  13502. }
  13503. return {
  13504. buffers: {
  13505. color: colorBuffer,
  13506. depth: depthBuffer,
  13507. stencil: stencilBuffer
  13508. },
  13509. enable: enable,
  13510. disable: disable,
  13511. bindFramebuffer: bindFramebuffer,
  13512. drawBuffers: drawBuffers,
  13513. useProgram: useProgram,
  13514. setBlending: setBlending,
  13515. setMaterial: setMaterial,
  13516. setFlipSided: setFlipSided,
  13517. setCullFace: setCullFace,
  13518. setLineWidth: setLineWidth,
  13519. setPolygonOffset: setPolygonOffset,
  13520. setScissorTest: setScissorTest,
  13521. activeTexture: activeTexture,
  13522. bindTexture: bindTexture,
  13523. unbindTexture: unbindTexture,
  13524. compressedTexImage2D: compressedTexImage2D,
  13525. compressedTexImage3D: compressedTexImage3D,
  13526. texImage2D: texImage2D,
  13527. texImage3D: texImage3D,
  13528. updateUBOMapping: updateUBOMapping,
  13529. uniformBlockBinding: uniformBlockBinding,
  13530. texStorage2D: texStorage2D,
  13531. texStorage3D: texStorage3D,
  13532. texSubImage2D: texSubImage2D,
  13533. texSubImage3D: texSubImage3D,
  13534. compressedTexSubImage2D: compressedTexSubImage2D,
  13535. compressedTexSubImage3D: compressedTexSubImage3D,
  13536. scissor: scissor,
  13537. viewport: viewport,
  13538. reset: reset
  13539. };
  13540. }
  13541. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  13542. const isWebGL2 = capabilities.isWebGL2;
  13543. const maxTextures = capabilities.maxTextures;
  13544. const maxCubemapSize = capabilities.maxCubemapSize;
  13545. const maxTextureSize = capabilities.maxTextureSize;
  13546. const maxSamples = capabilities.maxSamples;
  13547. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  13548. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  13549. const _videoTextures = new WeakMap();
  13550. let _canvas;
  13551. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  13552. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13553. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13554. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13555. let useOffscreenCanvas = false;
  13556. try {
  13557. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  13558. // eslint-disable-next-line compat/compat
  13559. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  13560. } catch ( err ) {
  13561. // Ignore any errors
  13562. }
  13563. function createCanvas( width, height ) {
  13564. // Use OffscreenCanvas when available. Specially needed in web workers
  13565. return useOffscreenCanvas ?
  13566. // eslint-disable-next-line compat/compat
  13567. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  13568. }
  13569. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  13570. let scale = 1;
  13571. // handle case if texture exceeds max size
  13572. if ( image.width > maxSize || image.height > maxSize ) {
  13573. scale = maxSize / Math.max( image.width, image.height );
  13574. }
  13575. // only perform resize if necessary
  13576. if ( scale < 1 || needsPowerOfTwo === true ) {
  13577. // only perform resize for certain image types
  13578. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  13579. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  13580. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  13581. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13582. const width = floor( scale * image.width );
  13583. const height = floor( scale * image.height );
  13584. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  13585. // cube textures can't reuse the same canvas
  13586. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  13587. canvas.width = width;
  13588. canvas.height = height;
  13589. const context = canvas.getContext( '2d' );
  13590. context.drawImage( image, 0, 0, width, height );
  13591. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  13592. return canvas;
  13593. } else {
  13594. if ( 'data' in image ) {
  13595. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  13596. }
  13597. return image;
  13598. }
  13599. }
  13600. return image;
  13601. }
  13602. function isPowerOfTwo$1( image ) {
  13603. return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height );
  13604. }
  13605. function textureNeedsPowerOfTwo( texture ) {
  13606. if ( isWebGL2 ) return false;
  13607. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  13608. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  13609. }
  13610. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  13611. return texture.generateMipmaps && supportsMips &&
  13612. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13613. }
  13614. function generateMipmap( target ) {
  13615. _gl.generateMipmap( target );
  13616. }
  13617. function getInternalFormat( internalFormatName, glFormat, glType, encoding, forceLinearEncoding = false ) {
  13618. if ( isWebGL2 === false ) return glFormat;
  13619. if ( internalFormatName !== null ) {
  13620. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  13621. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  13622. }
  13623. let internalFormat = glFormat;
  13624. if ( glFormat === 6403 ) {
  13625. if ( glType === 5126 ) internalFormat = 33326;
  13626. if ( glType === 5131 ) internalFormat = 33325;
  13627. if ( glType === 5121 ) internalFormat = 33321;
  13628. }
  13629. if ( glFormat === 33319 ) {
  13630. if ( glType === 5126 ) internalFormat = 33328;
  13631. if ( glType === 5131 ) internalFormat = 33327;
  13632. if ( glType === 5121 ) internalFormat = 33323;
  13633. }
  13634. if ( glFormat === 6408 ) {
  13635. if ( glType === 5126 ) internalFormat = 34836;
  13636. if ( glType === 5131 ) internalFormat = 34842;
  13637. if ( glType === 5121 ) internalFormat = ( encoding === sRGBEncoding && forceLinearEncoding === false ) ? 35907 : 32856;
  13638. if ( glType === 32819 ) internalFormat = 32854;
  13639. if ( glType === 32820 ) internalFormat = 32855;
  13640. }
  13641. if ( internalFormat === 33325 || internalFormat === 33326 ||
  13642. internalFormat === 33327 || internalFormat === 33328 ||
  13643. internalFormat === 34842 || internalFormat === 34836 ) {
  13644. extensions.get( 'EXT_color_buffer_float' );
  13645. }
  13646. return internalFormat;
  13647. }
  13648. function getMipLevels( texture, image, supportsMips ) {
  13649. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  13650. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  13651. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  13652. // user-defined mipmaps
  13653. return texture.mipmaps.length;
  13654. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  13655. return image.mipmaps.length;
  13656. } else {
  13657. // texture without mipmaps (only base level)
  13658. return 1;
  13659. }
  13660. }
  13661. // Fallback filters for non-power-of-2 textures
  13662. function filterFallback( f ) {
  13663. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  13664. return 9728;
  13665. }
  13666. return 9729;
  13667. }
  13668. //
  13669. function onTextureDispose( event ) {
  13670. const texture = event.target;
  13671. texture.removeEventListener( 'dispose', onTextureDispose );
  13672. deallocateTexture( texture );
  13673. if ( texture.isVideoTexture ) {
  13674. _videoTextures.delete( texture );
  13675. }
  13676. }
  13677. function onRenderTargetDispose( event ) {
  13678. const renderTarget = event.target;
  13679. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  13680. deallocateRenderTarget( renderTarget );
  13681. }
  13682. //
  13683. function deallocateTexture( texture ) {
  13684. const textureProperties = properties.get( texture );
  13685. if ( textureProperties.__webglInit === undefined ) return;
  13686. // check if it's necessary to remove the WebGLTexture object
  13687. const source = texture.source;
  13688. const webglTextures = _sources.get( source );
  13689. if ( webglTextures ) {
  13690. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  13691. webglTexture.usedTimes --;
  13692. // the WebGLTexture object is not used anymore, remove it
  13693. if ( webglTexture.usedTimes === 0 ) {
  13694. deleteTexture( texture );
  13695. }
  13696. // remove the weak map entry if no WebGLTexture uses the source anymore
  13697. if ( Object.keys( webglTextures ).length === 0 ) {
  13698. _sources.delete( source );
  13699. }
  13700. }
  13701. properties.remove( texture );
  13702. }
  13703. function deleteTexture( texture ) {
  13704. const textureProperties = properties.get( texture );
  13705. _gl.deleteTexture( textureProperties.__webglTexture );
  13706. const source = texture.source;
  13707. const webglTextures = _sources.get( source );
  13708. delete webglTextures[ textureProperties.__cacheKey ];
  13709. info.memory.textures --;
  13710. }
  13711. function deallocateRenderTarget( renderTarget ) {
  13712. const texture = renderTarget.texture;
  13713. const renderTargetProperties = properties.get( renderTarget );
  13714. const textureProperties = properties.get( texture );
  13715. if ( textureProperties.__webglTexture !== undefined ) {
  13716. _gl.deleteTexture( textureProperties.__webglTexture );
  13717. info.memory.textures --;
  13718. }
  13719. if ( renderTarget.depthTexture ) {
  13720. renderTarget.depthTexture.dispose();
  13721. }
  13722. if ( renderTarget.isWebGLCubeRenderTarget ) {
  13723. for ( let i = 0; i < 6; i ++ ) {
  13724. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  13725. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  13726. }
  13727. } else {
  13728. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  13729. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  13730. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  13731. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  13732. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  13733. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  13734. }
  13735. }
  13736. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  13737. }
  13738. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13739. for ( let i = 0, il = texture.length; i < il; i ++ ) {
  13740. const attachmentProperties = properties.get( texture[ i ] );
  13741. if ( attachmentProperties.__webglTexture ) {
  13742. _gl.deleteTexture( attachmentProperties.__webglTexture );
  13743. info.memory.textures --;
  13744. }
  13745. properties.remove( texture[ i ] );
  13746. }
  13747. }
  13748. properties.remove( texture );
  13749. properties.remove( renderTarget );
  13750. }
  13751. //
  13752. let textureUnits = 0;
  13753. function resetTextureUnits() {
  13754. textureUnits = 0;
  13755. }
  13756. function allocateTextureUnit() {
  13757. const textureUnit = textureUnits;
  13758. if ( textureUnit >= maxTextures ) {
  13759. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  13760. }
  13761. textureUnits += 1;
  13762. return textureUnit;
  13763. }
  13764. function getTextureCacheKey( texture ) {
  13765. const array = [];
  13766. array.push( texture.wrapS );
  13767. array.push( texture.wrapT );
  13768. array.push( texture.wrapR || 0 );
  13769. array.push( texture.magFilter );
  13770. array.push( texture.minFilter );
  13771. array.push( texture.anisotropy );
  13772. array.push( texture.internalFormat );
  13773. array.push( texture.format );
  13774. array.push( texture.type );
  13775. array.push( texture.generateMipmaps );
  13776. array.push( texture.premultiplyAlpha );
  13777. array.push( texture.flipY );
  13778. array.push( texture.unpackAlignment );
  13779. array.push( texture.encoding );
  13780. return array.join();
  13781. }
  13782. //
  13783. function setTexture2D( texture, slot ) {
  13784. const textureProperties = properties.get( texture );
  13785. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  13786. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  13787. const image = texture.image;
  13788. if ( image === null ) {
  13789. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  13790. } else if ( image.complete === false ) {
  13791. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  13792. } else {
  13793. uploadTexture( textureProperties, texture, slot );
  13794. return;
  13795. }
  13796. }
  13797. state.bindTexture( 3553, textureProperties.__webglTexture, 33984 + slot );
  13798. }
  13799. function setTexture2DArray( texture, slot ) {
  13800. const textureProperties = properties.get( texture );
  13801. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13802. uploadTexture( textureProperties, texture, slot );
  13803. return;
  13804. }
  13805. state.bindTexture( 35866, textureProperties.__webglTexture, 33984 + slot );
  13806. }
  13807. function setTexture3D( texture, slot ) {
  13808. const textureProperties = properties.get( texture );
  13809. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13810. uploadTexture( textureProperties, texture, slot );
  13811. return;
  13812. }
  13813. state.bindTexture( 32879, textureProperties.__webglTexture, 33984 + slot );
  13814. }
  13815. function setTextureCube( texture, slot ) {
  13816. const textureProperties = properties.get( texture );
  13817. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13818. uploadCubeTexture( textureProperties, texture, slot );
  13819. return;
  13820. }
  13821. state.bindTexture( 34067, textureProperties.__webglTexture, 33984 + slot );
  13822. }
  13823. const wrappingToGL = {
  13824. [ RepeatWrapping ]: 10497,
  13825. [ ClampToEdgeWrapping ]: 33071,
  13826. [ MirroredRepeatWrapping ]: 33648
  13827. };
  13828. const filterToGL = {
  13829. [ NearestFilter ]: 9728,
  13830. [ NearestMipmapNearestFilter ]: 9984,
  13831. [ NearestMipmapLinearFilter ]: 9986,
  13832. [ LinearFilter ]: 9729,
  13833. [ LinearMipmapNearestFilter ]: 9985,
  13834. [ LinearMipmapLinearFilter ]: 9987
  13835. };
  13836. function setTextureParameters( textureType, texture, supportsMips ) {
  13837. if ( supportsMips ) {
  13838. _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] );
  13839. _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] );
  13840. if ( textureType === 32879 || textureType === 35866 ) {
  13841. _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] );
  13842. }
  13843. _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] );
  13844. _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] );
  13845. } else {
  13846. _gl.texParameteri( textureType, 10242, 33071 );
  13847. _gl.texParameteri( textureType, 10243, 33071 );
  13848. if ( textureType === 32879 || textureType === 35866 ) {
  13849. _gl.texParameteri( textureType, 32882, 33071 );
  13850. }
  13851. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  13852. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  13853. }
  13854. _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
  13855. _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
  13856. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  13857. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  13858. }
  13859. }
  13860. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  13861. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  13862. if ( texture.magFilter === NearestFilter ) return;
  13863. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  13864. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  13865. if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only
  13866. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  13867. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  13868. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  13869. }
  13870. }
  13871. }
  13872. function initTexture( textureProperties, texture ) {
  13873. let forceUpload = false;
  13874. if ( textureProperties.__webglInit === undefined ) {
  13875. textureProperties.__webglInit = true;
  13876. texture.addEventListener( 'dispose', onTextureDispose );
  13877. }
  13878. // create Source <-> WebGLTextures mapping if necessary
  13879. const source = texture.source;
  13880. let webglTextures = _sources.get( source );
  13881. if ( webglTextures === undefined ) {
  13882. webglTextures = {};
  13883. _sources.set( source, webglTextures );
  13884. }
  13885. // check if there is already a WebGLTexture object for the given texture parameters
  13886. const textureCacheKey = getTextureCacheKey( texture );
  13887. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  13888. // if not, create a new instance of WebGLTexture
  13889. if ( webglTextures[ textureCacheKey ] === undefined ) {
  13890. // create new entry
  13891. webglTextures[ textureCacheKey ] = {
  13892. texture: _gl.createTexture(),
  13893. usedTimes: 0
  13894. };
  13895. info.memory.textures ++;
  13896. // when a new instance of WebGLTexture was created, a texture upload is required
  13897. // even if the image contents are identical
  13898. forceUpload = true;
  13899. }
  13900. webglTextures[ textureCacheKey ].usedTimes ++;
  13901. // every time the texture cache key changes, it's necessary to check if an instance of
  13902. // WebGLTexture can be deleted in order to avoid a memory leak.
  13903. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  13904. if ( webglTexture !== undefined ) {
  13905. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  13906. if ( webglTexture.usedTimes === 0 ) {
  13907. deleteTexture( texture );
  13908. }
  13909. }
  13910. // store references to cache key and WebGLTexture object
  13911. textureProperties.__cacheKey = textureCacheKey;
  13912. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  13913. }
  13914. return forceUpload;
  13915. }
  13916. function uploadTexture( textureProperties, texture, slot ) {
  13917. let textureType = 3553;
  13918. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = 35866;
  13919. if ( texture.isData3DTexture ) textureType = 32879;
  13920. const forceUpload = initTexture( textureProperties, texture );
  13921. const source = texture.source;
  13922. state.bindTexture( textureType, textureProperties.__webglTexture, 33984 + slot );
  13923. const sourceProperties = properties.get( source );
  13924. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  13925. state.activeTexture( 33984 + slot );
  13926. _gl.pixelStorei( 37440, texture.flipY );
  13927. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  13928. _gl.pixelStorei( 3317, texture.unpackAlignment );
  13929. _gl.pixelStorei( 37443, 0 );
  13930. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false;
  13931. let image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  13932. image = verifyColorSpace( texture, image );
  13933. const supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  13934. glFormat = utils.convert( texture.format, texture.encoding );
  13935. let glType = utils.convert( texture.type ),
  13936. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture );
  13937. setTextureParameters( textureType, texture, supportsMips );
  13938. let mipmap;
  13939. const mipmaps = texture.mipmaps;
  13940. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  13941. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  13942. const levels = getMipLevels( texture, image, supportsMips );
  13943. if ( texture.isDepthTexture ) {
  13944. // populate depth texture with dummy data
  13945. glInternalFormat = 6402;
  13946. if ( isWebGL2 ) {
  13947. if ( texture.type === FloatType ) {
  13948. glInternalFormat = 36012;
  13949. } else if ( texture.type === UnsignedIntType ) {
  13950. glInternalFormat = 33190;
  13951. } else if ( texture.type === UnsignedInt248Type ) {
  13952. glInternalFormat = 35056;
  13953. } else {
  13954. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  13955. }
  13956. } else {
  13957. if ( texture.type === FloatType ) {
  13958. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  13959. }
  13960. }
  13961. // validation checks for WebGL 1
  13962. if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
  13963. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13964. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13965. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13966. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  13967. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  13968. texture.type = UnsignedIntType;
  13969. glType = utils.convert( texture.type );
  13970. }
  13971. }
  13972. if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) {
  13973. // Depth stencil textures need the DEPTH_STENCIL internal format
  13974. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13975. glInternalFormat = 34041;
  13976. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13977. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13978. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13979. if ( texture.type !== UnsignedInt248Type ) {
  13980. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  13981. texture.type = UnsignedInt248Type;
  13982. glType = utils.convert( texture.type );
  13983. }
  13984. }
  13985. //
  13986. if ( allocateMemory ) {
  13987. if ( useTexStorage ) {
  13988. state.texStorage2D( 3553, 1, glInternalFormat, image.width, image.height );
  13989. } else {
  13990. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  13991. }
  13992. }
  13993. } else if ( texture.isDataTexture ) {
  13994. // use manually created mipmaps if available
  13995. // if there are no manual mipmaps
  13996. // set 0 level mipmap and then use GL to generate other mipmap levels
  13997. if ( mipmaps.length > 0 && supportsMips ) {
  13998. if ( useTexStorage && allocateMemory ) {
  13999. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14000. }
  14001. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14002. mipmap = mipmaps[ i ];
  14003. if ( useTexStorage ) {
  14004. state.texSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14005. } else {
  14006. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14007. }
  14008. }
  14009. texture.generateMipmaps = false;
  14010. } else {
  14011. if ( useTexStorage ) {
  14012. if ( allocateMemory ) {
  14013. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  14014. }
  14015. state.texSubImage2D( 3553, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  14016. } else {
  14017. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14018. }
  14019. }
  14020. } else if ( texture.isCompressedTexture ) {
  14021. if ( texture.isCompressedArrayTexture ) {
  14022. if ( useTexStorage && allocateMemory ) {
  14023. state.texStorage3D( 35866, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  14024. }
  14025. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14026. mipmap = mipmaps[ i ];
  14027. if ( texture.format !== RGBAFormat ) {
  14028. if ( glFormat !== null ) {
  14029. if ( useTexStorage ) {
  14030. state.compressedTexSubImage3D( 35866, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  14031. } else {
  14032. state.compressedTexImage3D( 35866, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  14033. }
  14034. } else {
  14035. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14036. }
  14037. } else {
  14038. if ( useTexStorage ) {
  14039. state.texSubImage3D( 35866, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  14040. } else {
  14041. state.texImage3D( 35866, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  14042. }
  14043. }
  14044. }
  14045. } else {
  14046. if ( useTexStorage && allocateMemory ) {
  14047. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14048. }
  14049. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14050. mipmap = mipmaps[ i ];
  14051. if ( texture.format !== RGBAFormat ) {
  14052. if ( glFormat !== null ) {
  14053. if ( useTexStorage ) {
  14054. state.compressedTexSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14055. } else {
  14056. state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14057. }
  14058. } else {
  14059. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14060. }
  14061. } else {
  14062. if ( useTexStorage ) {
  14063. state.texSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14064. } else {
  14065. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14066. }
  14067. }
  14068. }
  14069. }
  14070. } else if ( texture.isDataArrayTexture ) {
  14071. if ( useTexStorage ) {
  14072. if ( allocateMemory ) {
  14073. state.texStorage3D( 35866, levels, glInternalFormat, image.width, image.height, image.depth );
  14074. }
  14075. state.texSubImage3D( 35866, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14076. } else {
  14077. state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14078. }
  14079. } else if ( texture.isData3DTexture ) {
  14080. if ( useTexStorage ) {
  14081. if ( allocateMemory ) {
  14082. state.texStorage3D( 32879, levels, glInternalFormat, image.width, image.height, image.depth );
  14083. }
  14084. state.texSubImage3D( 32879, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14085. } else {
  14086. state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14087. }
  14088. } else if ( texture.isFramebufferTexture ) {
  14089. if ( allocateMemory ) {
  14090. if ( useTexStorage ) {
  14091. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  14092. } else {
  14093. let width = image.width, height = image.height;
  14094. for ( let i = 0; i < levels; i ++ ) {
  14095. state.texImage2D( 3553, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  14096. width >>= 1;
  14097. height >>= 1;
  14098. }
  14099. }
  14100. }
  14101. } else {
  14102. // regular Texture (image, video, canvas)
  14103. // use manually created mipmaps if available
  14104. // if there are no manual mipmaps
  14105. // set 0 level mipmap and then use GL to generate other mipmap levels
  14106. if ( mipmaps.length > 0 && supportsMips ) {
  14107. if ( useTexStorage && allocateMemory ) {
  14108. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14109. }
  14110. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14111. mipmap = mipmaps[ i ];
  14112. if ( useTexStorage ) {
  14113. state.texSubImage2D( 3553, i, 0, 0, glFormat, glType, mipmap );
  14114. } else {
  14115. state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );
  14116. }
  14117. }
  14118. texture.generateMipmaps = false;
  14119. } else {
  14120. if ( useTexStorage ) {
  14121. if ( allocateMemory ) {
  14122. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  14123. }
  14124. state.texSubImage2D( 3553, 0, 0, 0, glFormat, glType, image );
  14125. } else {
  14126. state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
  14127. }
  14128. }
  14129. }
  14130. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14131. generateMipmap( textureType );
  14132. }
  14133. sourceProperties.__version = source.version;
  14134. if ( texture.onUpdate ) texture.onUpdate( texture );
  14135. }
  14136. textureProperties.__version = texture.version;
  14137. }
  14138. function uploadCubeTexture( textureProperties, texture, slot ) {
  14139. if ( texture.image.length !== 6 ) return;
  14140. const forceUpload = initTexture( textureProperties, texture );
  14141. const source = texture.source;
  14142. state.bindTexture( 34067, textureProperties.__webglTexture, 33984 + slot );
  14143. const sourceProperties = properties.get( source );
  14144. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14145. state.activeTexture( 33984 + slot );
  14146. _gl.pixelStorei( 37440, texture.flipY );
  14147. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  14148. _gl.pixelStorei( 3317, texture.unpackAlignment );
  14149. _gl.pixelStorei( 37443, 0 );
  14150. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  14151. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  14152. const cubeImage = [];
  14153. for ( let i = 0; i < 6; i ++ ) {
  14154. if ( ! isCompressed && ! isDataTexture ) {
  14155. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  14156. } else {
  14157. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  14158. }
  14159. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  14160. }
  14161. const image = cubeImage[ 0 ],
  14162. supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14163. glFormat = utils.convert( texture.format, texture.encoding ),
  14164. glType = utils.convert( texture.type ),
  14165. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14166. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  14167. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14168. let levels = getMipLevels( texture, image, supportsMips );
  14169. setTextureParameters( 34067, texture, supportsMips );
  14170. let mipmaps;
  14171. if ( isCompressed ) {
  14172. if ( useTexStorage && allocateMemory ) {
  14173. state.texStorage2D( 34067, levels, glInternalFormat, image.width, image.height );
  14174. }
  14175. for ( let i = 0; i < 6; i ++ ) {
  14176. mipmaps = cubeImage[ i ].mipmaps;
  14177. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14178. const mipmap = mipmaps[ j ];
  14179. if ( texture.format !== RGBAFormat ) {
  14180. if ( glFormat !== null ) {
  14181. if ( useTexStorage ) {
  14182. state.compressedTexSubImage2D( 34069 + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14183. } else {
  14184. state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14185. }
  14186. } else {
  14187. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  14188. }
  14189. } else {
  14190. if ( useTexStorage ) {
  14191. state.texSubImage2D( 34069 + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14192. } else {
  14193. state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14194. }
  14195. }
  14196. }
  14197. }
  14198. } else {
  14199. mipmaps = texture.mipmaps;
  14200. if ( useTexStorage && allocateMemory ) {
  14201. // TODO: Uniformly handle mipmap definitions
  14202. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  14203. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  14204. if ( mipmaps.length > 0 ) levels ++;
  14205. state.texStorage2D( 34067, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height );
  14206. }
  14207. for ( let i = 0; i < 6; i ++ ) {
  14208. if ( isDataTexture ) {
  14209. if ( useTexStorage ) {
  14210. state.texSubImage2D( 34069 + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  14211. } else {
  14212. state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  14213. }
  14214. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14215. const mipmap = mipmaps[ j ];
  14216. const mipmapImage = mipmap.image[ i ].image;
  14217. if ( useTexStorage ) {
  14218. state.texSubImage2D( 34069 + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  14219. } else {
  14220. state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  14221. }
  14222. }
  14223. } else {
  14224. if ( useTexStorage ) {
  14225. state.texSubImage2D( 34069 + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  14226. } else {
  14227. state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  14228. }
  14229. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14230. const mipmap = mipmaps[ j ];
  14231. if ( useTexStorage ) {
  14232. state.texSubImage2D( 34069 + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  14233. } else {
  14234. state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  14235. }
  14236. }
  14237. }
  14238. }
  14239. }
  14240. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14241. // We assume images for cube map have the same size.
  14242. generateMipmap( 34067 );
  14243. }
  14244. sourceProperties.__version = source.version;
  14245. if ( texture.onUpdate ) texture.onUpdate( texture );
  14246. }
  14247. textureProperties.__version = texture.version;
  14248. }
  14249. // Render targets
  14250. // Setup storage for target texture and bind it to correct framebuffer
  14251. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) {
  14252. const glFormat = utils.convert( texture.format, texture.encoding );
  14253. const glType = utils.convert( texture.type );
  14254. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14255. const renderTargetProperties = properties.get( renderTarget );
  14256. if ( ! renderTargetProperties.__hasExternalTextures ) {
  14257. if ( textureTarget === 32879 || textureTarget === 35866 ) {
  14258. state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null );
  14259. } else {
  14260. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14261. }
  14262. }
  14263. state.bindFramebuffer( 36160, framebuffer );
  14264. if ( useMultisampledRTT( renderTarget ) ) {
  14265. multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  14266. } else if ( textureTarget === 3553 || ( textureTarget >= 34069 && textureTarget <= 34074 ) ) { // see #24753
  14267. _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 );
  14268. }
  14269. state.bindFramebuffer( 36160, null );
  14270. }
  14271. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14272. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  14273. _gl.bindRenderbuffer( 36161, renderbuffer );
  14274. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14275. let glInternalFormat = 33189;
  14276. if ( isMultisample || useMultisampledRTT( renderTarget ) ) {
  14277. const depthTexture = renderTarget.depthTexture;
  14278. if ( depthTexture && depthTexture.isDepthTexture ) {
  14279. if ( depthTexture.type === FloatType ) {
  14280. glInternalFormat = 36012;
  14281. } else if ( depthTexture.type === UnsignedIntType ) {
  14282. glInternalFormat = 33190;
  14283. }
  14284. }
  14285. const samples = getRenderTargetSamples( renderTarget );
  14286. if ( useMultisampledRTT( renderTarget ) ) {
  14287. multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14288. } else {
  14289. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14290. }
  14291. } else {
  14292. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  14293. }
  14294. _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
  14295. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14296. const samples = getRenderTargetSamples( renderTarget );
  14297. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14298. _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  14299. } else if ( useMultisampledRTT( renderTarget ) ) {
  14300. multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  14301. } else {
  14302. _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
  14303. }
  14304. _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
  14305. } else {
  14306. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14307. for ( let i = 0; i < textures.length; i ++ ) {
  14308. const texture = textures[ i ];
  14309. const glFormat = utils.convert( texture.format, texture.encoding );
  14310. const glType = utils.convert( texture.type );
  14311. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14312. const samples = getRenderTargetSamples( renderTarget );
  14313. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14314. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14315. } else if ( useMultisampledRTT( renderTarget ) ) {
  14316. multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14317. } else {
  14318. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  14319. }
  14320. }
  14321. }
  14322. _gl.bindRenderbuffer( 36161, null );
  14323. }
  14324. // Setup resources for a Depth Texture for a FBO (needs an extension)
  14325. function setupDepthTexture( framebuffer, renderTarget ) {
  14326. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  14327. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  14328. state.bindFramebuffer( 36160, framebuffer );
  14329. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  14330. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  14331. }
  14332. // upload an empty depth texture with framebuffer size
  14333. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  14334. renderTarget.depthTexture.image.width !== renderTarget.width ||
  14335. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  14336. renderTarget.depthTexture.image.width = renderTarget.width;
  14337. renderTarget.depthTexture.image.height = renderTarget.height;
  14338. renderTarget.depthTexture.needsUpdate = true;
  14339. }
  14340. setTexture2D( renderTarget.depthTexture, 0 );
  14341. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  14342. const samples = getRenderTargetSamples( renderTarget );
  14343. if ( renderTarget.depthTexture.format === DepthFormat ) {
  14344. if ( useMultisampledRTT( renderTarget ) ) {
  14345. multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, 36096, 3553, webglDepthTexture, 0, samples );
  14346. } else {
  14347. _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
  14348. }
  14349. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  14350. if ( useMultisampledRTT( renderTarget ) ) {
  14351. multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, 33306, 3553, webglDepthTexture, 0, samples );
  14352. } else {
  14353. _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
  14354. }
  14355. } else {
  14356. throw new Error( 'Unknown depthTexture format' );
  14357. }
  14358. }
  14359. // Setup GL resources for a non-texture depth buffer
  14360. function setupDepthRenderbuffer( renderTarget ) {
  14361. const renderTargetProperties = properties.get( renderTarget );
  14362. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14363. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  14364. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  14365. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  14366. } else {
  14367. if ( isCube ) {
  14368. renderTargetProperties.__webglDepthbuffer = [];
  14369. for ( let i = 0; i < 6; i ++ ) {
  14370. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
  14371. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  14372. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  14373. }
  14374. } else {
  14375. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  14376. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14377. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  14378. }
  14379. }
  14380. state.bindFramebuffer( 36160, null );
  14381. }
  14382. // rebind framebuffer with external textures
  14383. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  14384. const renderTargetProperties = properties.get( renderTarget );
  14385. if ( colorTexture !== undefined ) {
  14386. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, 36064, 3553 );
  14387. }
  14388. if ( depthTexture !== undefined ) {
  14389. setupDepthRenderbuffer( renderTarget );
  14390. }
  14391. }
  14392. // Set up GL resources for the render target
  14393. function setupRenderTarget( renderTarget ) {
  14394. const texture = renderTarget.texture;
  14395. const renderTargetProperties = properties.get( renderTarget );
  14396. const textureProperties = properties.get( texture );
  14397. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14398. if ( renderTarget.isWebGLMultipleRenderTargets !== true ) {
  14399. if ( textureProperties.__webglTexture === undefined ) {
  14400. textureProperties.__webglTexture = _gl.createTexture();
  14401. }
  14402. textureProperties.__version = texture.version;
  14403. info.memory.textures ++;
  14404. }
  14405. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14406. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14407. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14408. // Setup framebuffer
  14409. if ( isCube ) {
  14410. renderTargetProperties.__webglFramebuffer = [];
  14411. for ( let i = 0; i < 6; i ++ ) {
  14412. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14413. }
  14414. } else {
  14415. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14416. if ( isMultipleRenderTargets ) {
  14417. if ( capabilities.drawBuffers ) {
  14418. const textures = renderTarget.texture;
  14419. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14420. const attachmentProperties = properties.get( textures[ i ] );
  14421. if ( attachmentProperties.__webglTexture === undefined ) {
  14422. attachmentProperties.__webglTexture = _gl.createTexture();
  14423. info.memory.textures ++;
  14424. }
  14425. }
  14426. } else {
  14427. console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' );
  14428. }
  14429. }
  14430. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  14431. const textures = isMultipleRenderTargets ? texture : [ texture ];
  14432. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14433. renderTargetProperties.__webglColorRenderbuffer = [];
  14434. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  14435. for ( let i = 0; i < textures.length; i ++ ) {
  14436. const texture = textures[ i ];
  14437. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  14438. _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14439. const glFormat = utils.convert( texture.format, texture.encoding );
  14440. const glType = utils.convert( texture.type );
  14441. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, renderTarget.isXRRenderTarget === true );
  14442. const samples = getRenderTargetSamples( renderTarget );
  14443. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14444. _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14445. }
  14446. _gl.bindRenderbuffer( 36161, null );
  14447. if ( renderTarget.depthBuffer ) {
  14448. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14449. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  14450. }
  14451. state.bindFramebuffer( 36160, null );
  14452. }
  14453. }
  14454. // Setup color buffer
  14455. if ( isCube ) {
  14456. state.bindTexture( 34067, textureProperties.__webglTexture );
  14457. setTextureParameters( 34067, texture, supportsMips );
  14458. for ( let i = 0; i < 6; i ++ ) {
  14459. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, 36064, 34069 + i );
  14460. }
  14461. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14462. generateMipmap( 34067 );
  14463. }
  14464. state.unbindTexture();
  14465. } else if ( isMultipleRenderTargets ) {
  14466. const textures = renderTarget.texture;
  14467. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14468. const attachment = textures[ i ];
  14469. const attachmentProperties = properties.get( attachment );
  14470. state.bindTexture( 3553, attachmentProperties.__webglTexture );
  14471. setTextureParameters( 3553, attachment, supportsMips );
  14472. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, 36064 + i, 3553 );
  14473. if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) {
  14474. generateMipmap( 3553 );
  14475. }
  14476. }
  14477. state.unbindTexture();
  14478. } else {
  14479. let glTextureType = 3553;
  14480. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  14481. if ( isWebGL2 ) {
  14482. glTextureType = renderTarget.isWebGL3DRenderTarget ? 32879 : 35866;
  14483. } else {
  14484. console.error( 'THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.' );
  14485. }
  14486. }
  14487. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  14488. setTextureParameters( glTextureType, texture, supportsMips );
  14489. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, 36064, glTextureType );
  14490. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14491. generateMipmap( glTextureType );
  14492. }
  14493. state.unbindTexture();
  14494. }
  14495. // Setup depth and stencil buffers
  14496. if ( renderTarget.depthBuffer ) {
  14497. setupDepthRenderbuffer( renderTarget );
  14498. }
  14499. }
  14500. function updateRenderTargetMipmap( renderTarget ) {
  14501. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14502. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14503. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14504. const texture = textures[ i ];
  14505. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14506. const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  14507. const webglTexture = properties.get( texture ).__webglTexture;
  14508. state.bindTexture( target, webglTexture );
  14509. generateMipmap( target );
  14510. state.unbindTexture();
  14511. }
  14512. }
  14513. }
  14514. function updateMultisampleRenderTarget( renderTarget ) {
  14515. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  14516. const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [ renderTarget.texture ];
  14517. const width = renderTarget.width;
  14518. const height = renderTarget.height;
  14519. let mask = 16384;
  14520. const invalidationArray = [];
  14521. const depthStyle = renderTarget.stencilBuffer ? 33306 : 36096;
  14522. const renderTargetProperties = properties.get( renderTarget );
  14523. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14524. // If MRT we need to remove FBO attachments
  14525. if ( isMultipleRenderTargets ) {
  14526. for ( let i = 0; i < textures.length; i ++ ) {
  14527. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  14528. _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, null );
  14529. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  14530. _gl.framebufferTexture2D( 36009, 36064 + i, 3553, null, 0 );
  14531. }
  14532. }
  14533. state.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
  14534. state.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );
  14535. for ( let i = 0; i < textures.length; i ++ ) {
  14536. invalidationArray.push( 36064 + i );
  14537. if ( renderTarget.depthBuffer ) {
  14538. invalidationArray.push( depthStyle );
  14539. }
  14540. const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false;
  14541. if ( ignoreDepthValues === false ) {
  14542. if ( renderTarget.depthBuffer ) mask |= 256;
  14543. if ( renderTarget.stencilBuffer ) mask |= 1024;
  14544. }
  14545. if ( isMultipleRenderTargets ) {
  14546. _gl.framebufferRenderbuffer( 36008, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14547. }
  14548. if ( ignoreDepthValues === true ) {
  14549. _gl.invalidateFramebuffer( 36008, [ depthStyle ] );
  14550. _gl.invalidateFramebuffer( 36009, [ depthStyle ] );
  14551. }
  14552. if ( isMultipleRenderTargets ) {
  14553. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  14554. _gl.framebufferTexture2D( 36009, 36064, 3553, webglTexture, 0 );
  14555. }
  14556. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );
  14557. if ( supportsInvalidateFramebuffer ) {
  14558. _gl.invalidateFramebuffer( 36008, invalidationArray );
  14559. }
  14560. }
  14561. state.bindFramebuffer( 36008, null );
  14562. state.bindFramebuffer( 36009, null );
  14563. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  14564. if ( isMultipleRenderTargets ) {
  14565. for ( let i = 0; i < textures.length; i ++ ) {
  14566. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  14567. _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14568. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  14569. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  14570. _gl.framebufferTexture2D( 36009, 36064 + i, 3553, webglTexture, 0 );
  14571. }
  14572. }
  14573. state.bindFramebuffer( 36009, renderTargetProperties.__webglMultisampledFramebuffer );
  14574. }
  14575. }
  14576. function getRenderTargetSamples( renderTarget ) {
  14577. return Math.min( maxSamples, renderTarget.samples );
  14578. }
  14579. function useMultisampledRTT( renderTarget ) {
  14580. const renderTargetProperties = properties.get( renderTarget );
  14581. return isWebGL2 && renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  14582. }
  14583. function updateVideoTexture( texture ) {
  14584. const frame = info.render.frame;
  14585. // Check the last frame we updated the VideoTexture
  14586. if ( _videoTextures.get( texture ) !== frame ) {
  14587. _videoTextures.set( texture, frame );
  14588. texture.update();
  14589. }
  14590. }
  14591. function verifyColorSpace( texture, image ) {
  14592. const encoding = texture.encoding;
  14593. const format = texture.format;
  14594. const type = texture.type;
  14595. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat ) return image;
  14596. if ( encoding !== LinearEncoding ) {
  14597. // sRGB
  14598. if ( encoding === sRGBEncoding ) {
  14599. if ( isWebGL2 === false ) {
  14600. // in WebGL 1, try to use EXT_sRGB extension and unsized formats
  14601. if ( extensions.has( 'EXT_sRGB' ) === true && format === RGBAFormat ) {
  14602. texture.format = _SRGBAFormat;
  14603. // it's not possible to generate mips in WebGL 1 with this extension
  14604. texture.minFilter = LinearFilter;
  14605. texture.generateMipmaps = false;
  14606. } else {
  14607. // slow fallback (CPU decode)
  14608. image = ImageUtils.sRGBToLinear( image );
  14609. }
  14610. } else {
  14611. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  14612. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  14613. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  14614. }
  14615. }
  14616. } else {
  14617. console.error( 'THREE.WebGLTextures: Unsupported texture encoding:', encoding );
  14618. }
  14619. }
  14620. return image;
  14621. }
  14622. //
  14623. this.allocateTextureUnit = allocateTextureUnit;
  14624. this.resetTextureUnits = resetTextureUnits;
  14625. this.setTexture2D = setTexture2D;
  14626. this.setTexture2DArray = setTexture2DArray;
  14627. this.setTexture3D = setTexture3D;
  14628. this.setTextureCube = setTextureCube;
  14629. this.rebindTextures = rebindTextures;
  14630. this.setupRenderTarget = setupRenderTarget;
  14631. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14632. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14633. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  14634. this.setupFrameBufferTexture = setupFrameBufferTexture;
  14635. this.useMultisampledRTT = useMultisampledRTT;
  14636. }
  14637. function WebGLUtils( gl, extensions, capabilities ) {
  14638. const isWebGL2 = capabilities.isWebGL2;
  14639. function convert( p, encoding = null ) {
  14640. let extension;
  14641. if ( p === UnsignedByteType ) return 5121;
  14642. if ( p === UnsignedShort4444Type ) return 32819;
  14643. if ( p === UnsignedShort5551Type ) return 32820;
  14644. if ( p === ByteType ) return 5120;
  14645. if ( p === ShortType ) return 5122;
  14646. if ( p === UnsignedShortType ) return 5123;
  14647. if ( p === IntType ) return 5124;
  14648. if ( p === UnsignedIntType ) return 5125;
  14649. if ( p === FloatType ) return 5126;
  14650. if ( p === HalfFloatType ) {
  14651. if ( isWebGL2 ) return 5131;
  14652. extension = extensions.get( 'OES_texture_half_float' );
  14653. if ( extension !== null ) {
  14654. return extension.HALF_FLOAT_OES;
  14655. } else {
  14656. return null;
  14657. }
  14658. }
  14659. if ( p === AlphaFormat ) return 6406;
  14660. if ( p === RGBAFormat ) return 6408;
  14661. if ( p === LuminanceFormat ) return 6409;
  14662. if ( p === LuminanceAlphaFormat ) return 6410;
  14663. if ( p === DepthFormat ) return 6402;
  14664. if ( p === DepthStencilFormat ) return 34041;
  14665. // WebGL 1 sRGB fallback
  14666. if ( p === _SRGBAFormat ) {
  14667. extension = extensions.get( 'EXT_sRGB' );
  14668. if ( extension !== null ) {
  14669. return extension.SRGB_ALPHA_EXT;
  14670. } else {
  14671. return null;
  14672. }
  14673. }
  14674. // WebGL2 formats.
  14675. if ( p === RedFormat ) return 6403;
  14676. if ( p === RedIntegerFormat ) return 36244;
  14677. if ( p === RGFormat ) return 33319;
  14678. if ( p === RGIntegerFormat ) return 33320;
  14679. if ( p === RGBAIntegerFormat ) return 36249;
  14680. // S3TC
  14681. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  14682. if ( encoding === sRGBEncoding ) {
  14683. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  14684. if ( extension !== null ) {
  14685. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  14686. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  14687. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  14688. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  14689. } else {
  14690. return null;
  14691. }
  14692. } else {
  14693. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  14694. if ( extension !== null ) {
  14695. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14696. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14697. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14698. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14699. } else {
  14700. return null;
  14701. }
  14702. }
  14703. }
  14704. // PVRTC
  14705. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  14706. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  14707. if ( extension !== null ) {
  14708. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14709. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14710. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14711. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14712. } else {
  14713. return null;
  14714. }
  14715. }
  14716. // ETC1
  14717. if ( p === RGB_ETC1_Format ) {
  14718. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  14719. if ( extension !== null ) {
  14720. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14721. } else {
  14722. return null;
  14723. }
  14724. }
  14725. // ETC2
  14726. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  14727. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  14728. if ( extension !== null ) {
  14729. if ( p === RGB_ETC2_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  14730. if ( p === RGBA_ETC2_EAC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  14731. } else {
  14732. return null;
  14733. }
  14734. }
  14735. // ASTC
  14736. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  14737. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  14738. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  14739. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  14740. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  14741. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  14742. if ( extension !== null ) {
  14743. if ( p === RGBA_ASTC_4x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  14744. if ( p === RGBA_ASTC_5x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  14745. if ( p === RGBA_ASTC_5x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  14746. if ( p === RGBA_ASTC_6x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  14747. if ( p === RGBA_ASTC_6x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  14748. if ( p === RGBA_ASTC_8x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  14749. if ( p === RGBA_ASTC_8x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  14750. if ( p === RGBA_ASTC_8x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  14751. if ( p === RGBA_ASTC_10x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  14752. if ( p === RGBA_ASTC_10x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  14753. if ( p === RGBA_ASTC_10x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  14754. if ( p === RGBA_ASTC_10x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  14755. if ( p === RGBA_ASTC_12x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  14756. if ( p === RGBA_ASTC_12x12_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  14757. } else {
  14758. return null;
  14759. }
  14760. }
  14761. // BPTC
  14762. if ( p === RGBA_BPTC_Format ) {
  14763. extension = extensions.get( 'EXT_texture_compression_bptc' );
  14764. if ( extension !== null ) {
  14765. if ( p === RGBA_BPTC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  14766. } else {
  14767. return null;
  14768. }
  14769. }
  14770. // RGTC
  14771. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  14772. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  14773. if ( extension !== null ) {
  14774. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  14775. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  14776. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  14777. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  14778. } else {
  14779. return null;
  14780. }
  14781. }
  14782. //
  14783. if ( p === UnsignedInt248Type ) {
  14784. if ( isWebGL2 ) return 34042;
  14785. extension = extensions.get( 'WEBGL_depth_texture' );
  14786. if ( extension !== null ) {
  14787. return extension.UNSIGNED_INT_24_8_WEBGL;
  14788. } else {
  14789. return null;
  14790. }
  14791. }
  14792. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  14793. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  14794. }
  14795. return { convert: convert };
  14796. }
  14797. class ArrayCamera extends PerspectiveCamera {
  14798. constructor( array = [] ) {
  14799. super();
  14800. this.isArrayCamera = true;
  14801. this.cameras = array;
  14802. }
  14803. }
  14804. class Group extends Object3D {
  14805. constructor() {
  14806. super();
  14807. this.isGroup = true;
  14808. this.type = 'Group';
  14809. }
  14810. }
  14811. const _moveEvent = { type: 'move' };
  14812. class WebXRController {
  14813. constructor() {
  14814. this._targetRay = null;
  14815. this._grip = null;
  14816. this._hand = null;
  14817. }
  14818. getHandSpace() {
  14819. if ( this._hand === null ) {
  14820. this._hand = new Group();
  14821. this._hand.matrixAutoUpdate = false;
  14822. this._hand.visible = false;
  14823. this._hand.joints = {};
  14824. this._hand.inputState = { pinching: false };
  14825. }
  14826. return this._hand;
  14827. }
  14828. getTargetRaySpace() {
  14829. if ( this._targetRay === null ) {
  14830. this._targetRay = new Group();
  14831. this._targetRay.matrixAutoUpdate = false;
  14832. this._targetRay.visible = false;
  14833. this._targetRay.hasLinearVelocity = false;
  14834. this._targetRay.linearVelocity = new Vector3();
  14835. this._targetRay.hasAngularVelocity = false;
  14836. this._targetRay.angularVelocity = new Vector3();
  14837. }
  14838. return this._targetRay;
  14839. }
  14840. getGripSpace() {
  14841. if ( this._grip === null ) {
  14842. this._grip = new Group();
  14843. this._grip.matrixAutoUpdate = false;
  14844. this._grip.visible = false;
  14845. this._grip.hasLinearVelocity = false;
  14846. this._grip.linearVelocity = new Vector3();
  14847. this._grip.hasAngularVelocity = false;
  14848. this._grip.angularVelocity = new Vector3();
  14849. }
  14850. return this._grip;
  14851. }
  14852. dispatchEvent( event ) {
  14853. if ( this._targetRay !== null ) {
  14854. this._targetRay.dispatchEvent( event );
  14855. }
  14856. if ( this._grip !== null ) {
  14857. this._grip.dispatchEvent( event );
  14858. }
  14859. if ( this._hand !== null ) {
  14860. this._hand.dispatchEvent( event );
  14861. }
  14862. return this;
  14863. }
  14864. connect( inputSource ) {
  14865. if ( inputSource && inputSource.hand ) {
  14866. const hand = this._hand;
  14867. if ( hand ) {
  14868. for ( const inputjoint of inputSource.hand.values() ) {
  14869. // Initialize hand with joints when connected
  14870. this._getHandJoint( hand, inputjoint );
  14871. }
  14872. }
  14873. }
  14874. this.dispatchEvent( { type: 'connected', data: inputSource } );
  14875. return this;
  14876. }
  14877. disconnect( inputSource ) {
  14878. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  14879. if ( this._targetRay !== null ) {
  14880. this._targetRay.visible = false;
  14881. }
  14882. if ( this._grip !== null ) {
  14883. this._grip.visible = false;
  14884. }
  14885. if ( this._hand !== null ) {
  14886. this._hand.visible = false;
  14887. }
  14888. return this;
  14889. }
  14890. update( inputSource, frame, referenceSpace ) {
  14891. let inputPose = null;
  14892. let gripPose = null;
  14893. let handPose = null;
  14894. const targetRay = this._targetRay;
  14895. const grip = this._grip;
  14896. const hand = this._hand;
  14897. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  14898. if ( hand && inputSource.hand ) {
  14899. handPose = true;
  14900. for ( const inputjoint of inputSource.hand.values() ) {
  14901. // Update the joints groups with the XRJoint poses
  14902. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  14903. // The transform of this joint will be updated with the joint pose on each frame
  14904. const joint = this._getHandJoint( hand, inputjoint );
  14905. if ( jointPose !== null ) {
  14906. joint.matrix.fromArray( jointPose.transform.matrix );
  14907. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  14908. joint.jointRadius = jointPose.radius;
  14909. }
  14910. joint.visible = jointPose !== null;
  14911. }
  14912. // Custom events
  14913. // Check pinchz
  14914. const indexTip = hand.joints[ 'index-finger-tip' ];
  14915. const thumbTip = hand.joints[ 'thumb-tip' ];
  14916. const distance = indexTip.position.distanceTo( thumbTip.position );
  14917. const distanceToPinch = 0.02;
  14918. const threshold = 0.005;
  14919. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  14920. hand.inputState.pinching = false;
  14921. this.dispatchEvent( {
  14922. type: 'pinchend',
  14923. handedness: inputSource.handedness,
  14924. target: this
  14925. } );
  14926. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  14927. hand.inputState.pinching = true;
  14928. this.dispatchEvent( {
  14929. type: 'pinchstart',
  14930. handedness: inputSource.handedness,
  14931. target: this
  14932. } );
  14933. }
  14934. } else {
  14935. if ( grip !== null && inputSource.gripSpace ) {
  14936. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  14937. if ( gripPose !== null ) {
  14938. grip.matrix.fromArray( gripPose.transform.matrix );
  14939. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  14940. if ( gripPose.linearVelocity ) {
  14941. grip.hasLinearVelocity = true;
  14942. grip.linearVelocity.copy( gripPose.linearVelocity );
  14943. } else {
  14944. grip.hasLinearVelocity = false;
  14945. }
  14946. if ( gripPose.angularVelocity ) {
  14947. grip.hasAngularVelocity = true;
  14948. grip.angularVelocity.copy( gripPose.angularVelocity );
  14949. } else {
  14950. grip.hasAngularVelocity = false;
  14951. }
  14952. }
  14953. }
  14954. }
  14955. if ( targetRay !== null ) {
  14956. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  14957. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  14958. if ( inputPose === null && gripPose !== null ) {
  14959. inputPose = gripPose;
  14960. }
  14961. if ( inputPose !== null ) {
  14962. targetRay.matrix.fromArray( inputPose.transform.matrix );
  14963. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  14964. if ( inputPose.linearVelocity ) {
  14965. targetRay.hasLinearVelocity = true;
  14966. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  14967. } else {
  14968. targetRay.hasLinearVelocity = false;
  14969. }
  14970. if ( inputPose.angularVelocity ) {
  14971. targetRay.hasAngularVelocity = true;
  14972. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  14973. } else {
  14974. targetRay.hasAngularVelocity = false;
  14975. }
  14976. this.dispatchEvent( _moveEvent );
  14977. }
  14978. }
  14979. }
  14980. if ( targetRay !== null ) {
  14981. targetRay.visible = ( inputPose !== null );
  14982. }
  14983. if ( grip !== null ) {
  14984. grip.visible = ( gripPose !== null );
  14985. }
  14986. if ( hand !== null ) {
  14987. hand.visible = ( handPose !== null );
  14988. }
  14989. return this;
  14990. }
  14991. // private method
  14992. _getHandJoint( hand, inputjoint ) {
  14993. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  14994. const joint = new Group();
  14995. joint.matrixAutoUpdate = false;
  14996. joint.visible = false;
  14997. hand.joints[ inputjoint.jointName ] = joint;
  14998. hand.add( joint );
  14999. }
  15000. return hand.joints[ inputjoint.jointName ];
  15001. }
  15002. }
  15003. class DepthTexture extends Texture {
  15004. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  15005. format = format !== undefined ? format : DepthFormat;
  15006. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  15007. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  15008. }
  15009. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  15010. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  15011. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  15012. this.isDepthTexture = true;
  15013. this.image = { width: width, height: height };
  15014. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  15015. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  15016. this.flipY = false;
  15017. this.generateMipmaps = false;
  15018. }
  15019. }
  15020. class WebXRManager extends EventDispatcher {
  15021. constructor( renderer, gl ) {
  15022. super();
  15023. const scope = this;
  15024. let session = null;
  15025. let framebufferScaleFactor = 1.0;
  15026. let referenceSpace = null;
  15027. let referenceSpaceType = 'local-floor';
  15028. // Set default foveation to maximum.
  15029. let foveation = 1.0;
  15030. let customReferenceSpace = null;
  15031. let pose = null;
  15032. let glBinding = null;
  15033. let glProjLayer = null;
  15034. let glBaseLayer = null;
  15035. let xrFrame = null;
  15036. const attributes = gl.getContextAttributes();
  15037. let initialRenderTarget = null;
  15038. let newRenderTarget = null;
  15039. const controllers = [];
  15040. const controllerInputSources = [];
  15041. const planes = new Set();
  15042. const planesLastChangedTimes = new Map();
  15043. //
  15044. const cameraL = new PerspectiveCamera();
  15045. cameraL.layers.enable( 1 );
  15046. cameraL.viewport = new Vector4();
  15047. const cameraR = new PerspectiveCamera();
  15048. cameraR.layers.enable( 2 );
  15049. cameraR.viewport = new Vector4();
  15050. const cameras = [ cameraL, cameraR ];
  15051. const cameraVR = new ArrayCamera();
  15052. cameraVR.layers.enable( 1 );
  15053. cameraVR.layers.enable( 2 );
  15054. let _currentDepthNear = null;
  15055. let _currentDepthFar = null;
  15056. //
  15057. this.cameraAutoUpdate = true;
  15058. this.enabled = false;
  15059. this.isPresenting = false;
  15060. this.getController = function ( index ) {
  15061. let controller = controllers[ index ];
  15062. if ( controller === undefined ) {
  15063. controller = new WebXRController();
  15064. controllers[ index ] = controller;
  15065. }
  15066. return controller.getTargetRaySpace();
  15067. };
  15068. this.getControllerGrip = function ( index ) {
  15069. let controller = controllers[ index ];
  15070. if ( controller === undefined ) {
  15071. controller = new WebXRController();
  15072. controllers[ index ] = controller;
  15073. }
  15074. return controller.getGripSpace();
  15075. };
  15076. this.getHand = function ( index ) {
  15077. let controller = controllers[ index ];
  15078. if ( controller === undefined ) {
  15079. controller = new WebXRController();
  15080. controllers[ index ] = controller;
  15081. }
  15082. return controller.getHandSpace();
  15083. };
  15084. //
  15085. function onSessionEvent( event ) {
  15086. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  15087. if ( controllerIndex === - 1 ) {
  15088. return;
  15089. }
  15090. const controller = controllers[ controllerIndex ];
  15091. if ( controller !== undefined ) {
  15092. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  15093. }
  15094. }
  15095. function onSessionEnd() {
  15096. session.removeEventListener( 'select', onSessionEvent );
  15097. session.removeEventListener( 'selectstart', onSessionEvent );
  15098. session.removeEventListener( 'selectend', onSessionEvent );
  15099. session.removeEventListener( 'squeeze', onSessionEvent );
  15100. session.removeEventListener( 'squeezestart', onSessionEvent );
  15101. session.removeEventListener( 'squeezeend', onSessionEvent );
  15102. session.removeEventListener( 'end', onSessionEnd );
  15103. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  15104. for ( let i = 0; i < controllers.length; i ++ ) {
  15105. const inputSource = controllerInputSources[ i ];
  15106. if ( inputSource === null ) continue;
  15107. controllerInputSources[ i ] = null;
  15108. controllers[ i ].disconnect( inputSource );
  15109. }
  15110. _currentDepthNear = null;
  15111. _currentDepthFar = null;
  15112. // restore framebuffer/rendering state
  15113. renderer.setRenderTarget( initialRenderTarget );
  15114. glBaseLayer = null;
  15115. glProjLayer = null;
  15116. glBinding = null;
  15117. session = null;
  15118. newRenderTarget = null;
  15119. //
  15120. animation.stop();
  15121. scope.isPresenting = false;
  15122. scope.dispatchEvent( { type: 'sessionend' } );
  15123. }
  15124. this.setFramebufferScaleFactor = function ( value ) {
  15125. framebufferScaleFactor = value;
  15126. if ( scope.isPresenting === true ) {
  15127. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  15128. }
  15129. };
  15130. this.setReferenceSpaceType = function ( value ) {
  15131. referenceSpaceType = value;
  15132. if ( scope.isPresenting === true ) {
  15133. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  15134. }
  15135. };
  15136. this.getReferenceSpace = function () {
  15137. return customReferenceSpace || referenceSpace;
  15138. };
  15139. this.setReferenceSpace = function ( space ) {
  15140. customReferenceSpace = space;
  15141. };
  15142. this.getBaseLayer = function () {
  15143. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  15144. };
  15145. this.getBinding = function () {
  15146. return glBinding;
  15147. };
  15148. this.getFrame = function () {
  15149. return xrFrame;
  15150. };
  15151. this.getSession = function () {
  15152. return session;
  15153. };
  15154. this.setSession = async function ( value ) {
  15155. session = value;
  15156. if ( session !== null ) {
  15157. initialRenderTarget = renderer.getRenderTarget();
  15158. session.addEventListener( 'select', onSessionEvent );
  15159. session.addEventListener( 'selectstart', onSessionEvent );
  15160. session.addEventListener( 'selectend', onSessionEvent );
  15161. session.addEventListener( 'squeeze', onSessionEvent );
  15162. session.addEventListener( 'squeezestart', onSessionEvent );
  15163. session.addEventListener( 'squeezeend', onSessionEvent );
  15164. session.addEventListener( 'end', onSessionEnd );
  15165. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  15166. if ( attributes.xrCompatible !== true ) {
  15167. await gl.makeXRCompatible();
  15168. }
  15169. if ( ( session.renderState.layers === undefined ) || ( renderer.capabilities.isWebGL2 === false ) ) {
  15170. const layerInit = {
  15171. antialias: ( session.renderState.layers === undefined ) ? attributes.antialias : true,
  15172. alpha: attributes.alpha,
  15173. depth: attributes.depth,
  15174. stencil: attributes.stencil,
  15175. framebufferScaleFactor: framebufferScaleFactor
  15176. };
  15177. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  15178. session.updateRenderState( { baseLayer: glBaseLayer } );
  15179. newRenderTarget = new WebGLRenderTarget(
  15180. glBaseLayer.framebufferWidth,
  15181. glBaseLayer.framebufferHeight,
  15182. {
  15183. format: RGBAFormat,
  15184. type: UnsignedByteType,
  15185. encoding: renderer.outputEncoding,
  15186. stencilBuffer: attributes.stencil
  15187. }
  15188. );
  15189. } else {
  15190. let depthFormat = null;
  15191. let depthType = null;
  15192. let glDepthFormat = null;
  15193. if ( attributes.depth ) {
  15194. glDepthFormat = attributes.stencil ? 35056 : 33190;
  15195. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  15196. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  15197. }
  15198. const projectionlayerInit = {
  15199. colorFormat: 32856,
  15200. depthFormat: glDepthFormat,
  15201. scaleFactor: framebufferScaleFactor
  15202. };
  15203. glBinding = new XRWebGLBinding( session, gl );
  15204. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  15205. session.updateRenderState( { layers: [ glProjLayer ] } );
  15206. newRenderTarget = new WebGLRenderTarget(
  15207. glProjLayer.textureWidth,
  15208. glProjLayer.textureHeight,
  15209. {
  15210. format: RGBAFormat,
  15211. type: UnsignedByteType,
  15212. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  15213. stencilBuffer: attributes.stencil,
  15214. encoding: renderer.outputEncoding,
  15215. samples: attributes.antialias ? 4 : 0
  15216. } );
  15217. const renderTargetProperties = renderer.properties.get( newRenderTarget );
  15218. renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues;
  15219. }
  15220. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  15221. this.setFoveation( foveation );
  15222. customReferenceSpace = null;
  15223. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  15224. animation.setContext( session );
  15225. animation.start();
  15226. scope.isPresenting = true;
  15227. scope.dispatchEvent( { type: 'sessionstart' } );
  15228. }
  15229. };
  15230. function onInputSourcesChange( event ) {
  15231. // Notify disconnected
  15232. for ( let i = 0; i < event.removed.length; i ++ ) {
  15233. const inputSource = event.removed[ i ];
  15234. const index = controllerInputSources.indexOf( inputSource );
  15235. if ( index >= 0 ) {
  15236. controllerInputSources[ index ] = null;
  15237. controllers[ index ].disconnect( inputSource );
  15238. }
  15239. }
  15240. // Notify connected
  15241. for ( let i = 0; i < event.added.length; i ++ ) {
  15242. const inputSource = event.added[ i ];
  15243. let controllerIndex = controllerInputSources.indexOf( inputSource );
  15244. if ( controllerIndex === - 1 ) {
  15245. // Assign input source a controller that currently has no input source
  15246. for ( let i = 0; i < controllers.length; i ++ ) {
  15247. if ( i >= controllerInputSources.length ) {
  15248. controllerInputSources.push( inputSource );
  15249. controllerIndex = i;
  15250. break;
  15251. } else if ( controllerInputSources[ i ] === null ) {
  15252. controllerInputSources[ i ] = inputSource;
  15253. controllerIndex = i;
  15254. break;
  15255. }
  15256. }
  15257. // If all controllers do currently receive input we ignore new ones
  15258. if ( controllerIndex === - 1 ) break;
  15259. }
  15260. const controller = controllers[ controllerIndex ];
  15261. if ( controller ) {
  15262. controller.connect( inputSource );
  15263. }
  15264. }
  15265. }
  15266. //
  15267. const cameraLPos = new Vector3();
  15268. const cameraRPos = new Vector3();
  15269. /**
  15270. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15271. * the cameras' projection and world matrices have already been set.
  15272. * And that near and far planes are identical for both cameras.
  15273. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15274. */
  15275. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  15276. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  15277. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  15278. const ipd = cameraLPos.distanceTo( cameraRPos );
  15279. const projL = cameraL.projectionMatrix.elements;
  15280. const projR = cameraR.projectionMatrix.elements;
  15281. // VR systems will have identical far and near planes, and
  15282. // most likely identical top and bottom frustum extents.
  15283. // Use the left camera for these values.
  15284. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  15285. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  15286. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  15287. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  15288. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  15289. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  15290. const left = near * leftFov;
  15291. const right = near * rightFov;
  15292. // Calculate the new camera's position offset from the
  15293. // left camera. xOffset should be roughly half `ipd`.
  15294. const zOffset = ipd / ( - leftFov + rightFov );
  15295. const xOffset = zOffset * - leftFov;
  15296. // TODO: Better way to apply this offset?
  15297. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  15298. camera.translateX( xOffset );
  15299. camera.translateZ( zOffset );
  15300. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  15301. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15302. // Find the union of the frustum values of the cameras and scale
  15303. // the values so that the near plane's position does not change in world space,
  15304. // although must now be relative to the new union camera.
  15305. const near2 = near + zOffset;
  15306. const far2 = far + zOffset;
  15307. const left2 = left - xOffset;
  15308. const right2 = right + ( ipd - xOffset );
  15309. const top2 = topFov * far / far2 * near2;
  15310. const bottom2 = bottomFov * far / far2 * near2;
  15311. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  15312. }
  15313. function updateCamera( camera, parent ) {
  15314. if ( parent === null ) {
  15315. camera.matrixWorld.copy( camera.matrix );
  15316. } else {
  15317. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  15318. }
  15319. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15320. }
  15321. this.updateCamera = function ( camera ) {
  15322. if ( session === null ) return;
  15323. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  15324. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  15325. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  15326. // Note that the new renderState won't apply until the next frame. See #18320
  15327. session.updateRenderState( {
  15328. depthNear: cameraVR.near,
  15329. depthFar: cameraVR.far
  15330. } );
  15331. _currentDepthNear = cameraVR.near;
  15332. _currentDepthFar = cameraVR.far;
  15333. }
  15334. const parent = camera.parent;
  15335. const cameras = cameraVR.cameras;
  15336. updateCamera( cameraVR, parent );
  15337. for ( let i = 0; i < cameras.length; i ++ ) {
  15338. updateCamera( cameras[ i ], parent );
  15339. }
  15340. cameraVR.matrixWorld.decompose( cameraVR.position, cameraVR.quaternion, cameraVR.scale );
  15341. // update user camera and its children
  15342. camera.matrix.copy( cameraVR.matrix );
  15343. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  15344. const children = camera.children;
  15345. for ( let i = 0, l = children.length; i < l; i ++ ) {
  15346. children[ i ].updateMatrixWorld( true );
  15347. }
  15348. // update projection matrix for proper view frustum culling
  15349. if ( cameras.length === 2 ) {
  15350. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  15351. } else {
  15352. // assume single camera setup (AR)
  15353. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  15354. }
  15355. };
  15356. this.getCamera = function () {
  15357. return cameraVR;
  15358. };
  15359. this.getFoveation = function () {
  15360. if ( glProjLayer === null && glBaseLayer === null ) {
  15361. return undefined;
  15362. }
  15363. return foveation;
  15364. };
  15365. this.setFoveation = function ( value ) {
  15366. // 0 = no foveation = full resolution
  15367. // 1 = maximum foveation = the edges render at lower resolution
  15368. foveation = value;
  15369. if ( glProjLayer !== null ) {
  15370. glProjLayer.fixedFoveation = value;
  15371. }
  15372. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  15373. glBaseLayer.fixedFoveation = value;
  15374. }
  15375. };
  15376. this.getPlanes = function () {
  15377. return planes;
  15378. };
  15379. // Animation Loop
  15380. let onAnimationFrameCallback = null;
  15381. function onAnimationFrame( time, frame ) {
  15382. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  15383. xrFrame = frame;
  15384. if ( pose !== null ) {
  15385. const views = pose.views;
  15386. if ( glBaseLayer !== null ) {
  15387. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  15388. renderer.setRenderTarget( newRenderTarget );
  15389. }
  15390. let cameraVRNeedsUpdate = false;
  15391. // check if it's necessary to rebuild cameraVR's camera list
  15392. if ( views.length !== cameraVR.cameras.length ) {
  15393. cameraVR.cameras.length = 0;
  15394. cameraVRNeedsUpdate = true;
  15395. }
  15396. for ( let i = 0; i < views.length; i ++ ) {
  15397. const view = views[ i ];
  15398. let viewport = null;
  15399. if ( glBaseLayer !== null ) {
  15400. viewport = glBaseLayer.getViewport( view );
  15401. } else {
  15402. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  15403. viewport = glSubImage.viewport;
  15404. // For side-by-side projection, we only produce a single texture for both eyes.
  15405. if ( i === 0 ) {
  15406. renderer.setRenderTargetTextures(
  15407. newRenderTarget,
  15408. glSubImage.colorTexture,
  15409. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  15410. renderer.setRenderTarget( newRenderTarget );
  15411. }
  15412. }
  15413. let camera = cameras[ i ];
  15414. if ( camera === undefined ) {
  15415. camera = new PerspectiveCamera();
  15416. camera.layers.enable( i );
  15417. camera.viewport = new Vector4();
  15418. cameras[ i ] = camera;
  15419. }
  15420. camera.matrix.fromArray( view.transform.matrix );
  15421. camera.projectionMatrix.fromArray( view.projectionMatrix );
  15422. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  15423. if ( i === 0 ) {
  15424. cameraVR.matrix.copy( camera.matrix );
  15425. }
  15426. if ( cameraVRNeedsUpdate === true ) {
  15427. cameraVR.cameras.push( camera );
  15428. }
  15429. }
  15430. }
  15431. //
  15432. for ( let i = 0; i < controllers.length; i ++ ) {
  15433. const inputSource = controllerInputSources[ i ];
  15434. const controller = controllers[ i ];
  15435. if ( inputSource !== null && controller !== undefined ) {
  15436. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  15437. }
  15438. }
  15439. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  15440. if ( frame.detectedPlanes ) {
  15441. scope.dispatchEvent( { type: 'planesdetected', data: frame.detectedPlanes } );
  15442. let planesToRemove = null;
  15443. for ( const plane of planes ) {
  15444. if ( ! frame.detectedPlanes.has( plane ) ) {
  15445. if ( planesToRemove === null ) {
  15446. planesToRemove = [];
  15447. }
  15448. planesToRemove.push( plane );
  15449. }
  15450. }
  15451. if ( planesToRemove !== null ) {
  15452. for ( const plane of planesToRemove ) {
  15453. planes.delete( plane );
  15454. planesLastChangedTimes.delete( plane );
  15455. scope.dispatchEvent( { type: 'planeremoved', data: plane } );
  15456. }
  15457. }
  15458. for ( const plane of frame.detectedPlanes ) {
  15459. if ( ! planes.has( plane ) ) {
  15460. planes.add( plane );
  15461. planesLastChangedTimes.set( plane, frame.lastChangedTime );
  15462. scope.dispatchEvent( { type: 'planeadded', data: plane } );
  15463. } else {
  15464. const lastKnownTime = planesLastChangedTimes.get( plane );
  15465. if ( plane.lastChangedTime > lastKnownTime ) {
  15466. planesLastChangedTimes.set( plane, plane.lastChangedTime );
  15467. scope.dispatchEvent( { type: 'planechanged', data: plane } );
  15468. }
  15469. }
  15470. }
  15471. }
  15472. xrFrame = null;
  15473. }
  15474. const animation = new WebGLAnimation();
  15475. animation.setAnimationLoop( onAnimationFrame );
  15476. this.setAnimationLoop = function ( callback ) {
  15477. onAnimationFrameCallback = callback;
  15478. };
  15479. this.dispose = function () {};
  15480. }
  15481. }
  15482. function WebGLMaterials( renderer, properties ) {
  15483. function refreshFogUniforms( uniforms, fog ) {
  15484. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  15485. if ( fog.isFog ) {
  15486. uniforms.fogNear.value = fog.near;
  15487. uniforms.fogFar.value = fog.far;
  15488. } else if ( fog.isFogExp2 ) {
  15489. uniforms.fogDensity.value = fog.density;
  15490. }
  15491. }
  15492. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  15493. if ( material.isMeshBasicMaterial ) {
  15494. refreshUniformsCommon( uniforms, material );
  15495. } else if ( material.isMeshLambertMaterial ) {
  15496. refreshUniformsCommon( uniforms, material );
  15497. } else if ( material.isMeshToonMaterial ) {
  15498. refreshUniformsCommon( uniforms, material );
  15499. refreshUniformsToon( uniforms, material );
  15500. } else if ( material.isMeshPhongMaterial ) {
  15501. refreshUniformsCommon( uniforms, material );
  15502. refreshUniformsPhong( uniforms, material );
  15503. } else if ( material.isMeshStandardMaterial ) {
  15504. refreshUniformsCommon( uniforms, material );
  15505. refreshUniformsStandard( uniforms, material );
  15506. if ( material.isMeshPhysicalMaterial ) {
  15507. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  15508. }
  15509. } else if ( material.isMeshMatcapMaterial ) {
  15510. refreshUniformsCommon( uniforms, material );
  15511. refreshUniformsMatcap( uniforms, material );
  15512. } else if ( material.isMeshDepthMaterial ) {
  15513. refreshUniformsCommon( uniforms, material );
  15514. } else if ( material.isMeshDistanceMaterial ) {
  15515. refreshUniformsCommon( uniforms, material );
  15516. refreshUniformsDistance( uniforms, material );
  15517. } else if ( material.isMeshNormalMaterial ) {
  15518. refreshUniformsCommon( uniforms, material );
  15519. } else if ( material.isLineBasicMaterial ) {
  15520. refreshUniformsLine( uniforms, material );
  15521. if ( material.isLineDashedMaterial ) {
  15522. refreshUniformsDash( uniforms, material );
  15523. }
  15524. } else if ( material.isPointsMaterial ) {
  15525. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  15526. } else if ( material.isSpriteMaterial ) {
  15527. refreshUniformsSprites( uniforms, material );
  15528. } else if ( material.isShadowMaterial ) {
  15529. uniforms.color.value.copy( material.color );
  15530. uniforms.opacity.value = material.opacity;
  15531. } else if ( material.isShaderMaterial ) {
  15532. material.uniformsNeedUpdate = false; // #15581
  15533. }
  15534. }
  15535. function refreshUniformsCommon( uniforms, material ) {
  15536. uniforms.opacity.value = material.opacity;
  15537. if ( material.color ) {
  15538. uniforms.diffuse.value.copy( material.color );
  15539. }
  15540. if ( material.emissive ) {
  15541. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  15542. }
  15543. if ( material.map ) {
  15544. uniforms.map.value = material.map;
  15545. }
  15546. if ( material.alphaMap ) {
  15547. uniforms.alphaMap.value = material.alphaMap;
  15548. }
  15549. if ( material.bumpMap ) {
  15550. uniforms.bumpMap.value = material.bumpMap;
  15551. uniforms.bumpScale.value = material.bumpScale;
  15552. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  15553. }
  15554. if ( material.displacementMap ) {
  15555. uniforms.displacementMap.value = material.displacementMap;
  15556. uniforms.displacementScale.value = material.displacementScale;
  15557. uniforms.displacementBias.value = material.displacementBias;
  15558. }
  15559. if ( material.emissiveMap ) {
  15560. uniforms.emissiveMap.value = material.emissiveMap;
  15561. }
  15562. if ( material.normalMap ) {
  15563. uniforms.normalMap.value = material.normalMap;
  15564. uniforms.normalScale.value.copy( material.normalScale );
  15565. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  15566. }
  15567. if ( material.specularMap ) {
  15568. uniforms.specularMap.value = material.specularMap;
  15569. }
  15570. if ( material.alphaTest > 0 ) {
  15571. uniforms.alphaTest.value = material.alphaTest;
  15572. }
  15573. const envMap = properties.get( material ).envMap;
  15574. if ( envMap ) {
  15575. uniforms.envMap.value = envMap;
  15576. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  15577. uniforms.reflectivity.value = material.reflectivity;
  15578. uniforms.ior.value = material.ior;
  15579. uniforms.refractionRatio.value = material.refractionRatio;
  15580. }
  15581. if ( material.lightMap ) {
  15582. uniforms.lightMap.value = material.lightMap;
  15583. // artist-friendly light intensity scaling factor
  15584. const scaleFactor = ( renderer.physicallyCorrectLights !== true ) ? Math.PI : 1;
  15585. uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor;
  15586. }
  15587. if ( material.aoMap ) {
  15588. uniforms.aoMap.value = material.aoMap;
  15589. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15590. }
  15591. // uv repeat and offset setting priorities
  15592. // 1. color map
  15593. // 2. specular map
  15594. // 3. displacementMap map
  15595. // 4. normal map
  15596. // 5. bump map
  15597. // 6. roughnessMap map
  15598. // 7. metalnessMap map
  15599. // 8. alphaMap map
  15600. // 9. emissiveMap map
  15601. // 10. clearcoat map
  15602. // 11. clearcoat normal map
  15603. // 12. clearcoat roughnessMap map
  15604. // 13. iridescence map
  15605. // 14. iridescence thickness map
  15606. // 15. specular intensity map
  15607. // 16. specular tint map
  15608. // 17. transmission map
  15609. // 18. thickness map
  15610. let uvScaleMap;
  15611. if ( material.map ) {
  15612. uvScaleMap = material.map;
  15613. } else if ( material.specularMap ) {
  15614. uvScaleMap = material.specularMap;
  15615. } else if ( material.displacementMap ) {
  15616. uvScaleMap = material.displacementMap;
  15617. } else if ( material.normalMap ) {
  15618. uvScaleMap = material.normalMap;
  15619. } else if ( material.bumpMap ) {
  15620. uvScaleMap = material.bumpMap;
  15621. } else if ( material.roughnessMap ) {
  15622. uvScaleMap = material.roughnessMap;
  15623. } else if ( material.metalnessMap ) {
  15624. uvScaleMap = material.metalnessMap;
  15625. } else if ( material.alphaMap ) {
  15626. uvScaleMap = material.alphaMap;
  15627. } else if ( material.emissiveMap ) {
  15628. uvScaleMap = material.emissiveMap;
  15629. } else if ( material.clearcoatMap ) {
  15630. uvScaleMap = material.clearcoatMap;
  15631. } else if ( material.clearcoatNormalMap ) {
  15632. uvScaleMap = material.clearcoatNormalMap;
  15633. } else if ( material.clearcoatRoughnessMap ) {
  15634. uvScaleMap = material.clearcoatRoughnessMap;
  15635. } else if ( material.iridescenceMap ) {
  15636. uvScaleMap = material.iridescenceMap;
  15637. } else if ( material.iridescenceThicknessMap ) {
  15638. uvScaleMap = material.iridescenceThicknessMap;
  15639. } else if ( material.specularIntensityMap ) {
  15640. uvScaleMap = material.specularIntensityMap;
  15641. } else if ( material.specularColorMap ) {
  15642. uvScaleMap = material.specularColorMap;
  15643. } else if ( material.transmissionMap ) {
  15644. uvScaleMap = material.transmissionMap;
  15645. } else if ( material.thicknessMap ) {
  15646. uvScaleMap = material.thicknessMap;
  15647. } else if ( material.sheenColorMap ) {
  15648. uvScaleMap = material.sheenColorMap;
  15649. } else if ( material.sheenRoughnessMap ) {
  15650. uvScaleMap = material.sheenRoughnessMap;
  15651. }
  15652. if ( uvScaleMap !== undefined ) {
  15653. // backwards compatibility
  15654. if ( uvScaleMap.isWebGLRenderTarget ) {
  15655. uvScaleMap = uvScaleMap.texture;
  15656. }
  15657. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15658. uvScaleMap.updateMatrix();
  15659. }
  15660. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15661. }
  15662. // uv repeat and offset setting priorities for uv2
  15663. // 1. ao map
  15664. // 2. light map
  15665. let uv2ScaleMap;
  15666. if ( material.aoMap ) {
  15667. uv2ScaleMap = material.aoMap;
  15668. } else if ( material.lightMap ) {
  15669. uv2ScaleMap = material.lightMap;
  15670. }
  15671. if ( uv2ScaleMap !== undefined ) {
  15672. // backwards compatibility
  15673. if ( uv2ScaleMap.isWebGLRenderTarget ) {
  15674. uv2ScaleMap = uv2ScaleMap.texture;
  15675. }
  15676. if ( uv2ScaleMap.matrixAutoUpdate === true ) {
  15677. uv2ScaleMap.updateMatrix();
  15678. }
  15679. uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );
  15680. }
  15681. }
  15682. function refreshUniformsLine( uniforms, material ) {
  15683. uniforms.diffuse.value.copy( material.color );
  15684. uniforms.opacity.value = material.opacity;
  15685. }
  15686. function refreshUniformsDash( uniforms, material ) {
  15687. uniforms.dashSize.value = material.dashSize;
  15688. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15689. uniforms.scale.value = material.scale;
  15690. }
  15691. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  15692. uniforms.diffuse.value.copy( material.color );
  15693. uniforms.opacity.value = material.opacity;
  15694. uniforms.size.value = material.size * pixelRatio;
  15695. uniforms.scale.value = height * 0.5;
  15696. if ( material.map ) {
  15697. uniforms.map.value = material.map;
  15698. }
  15699. if ( material.alphaMap ) {
  15700. uniforms.alphaMap.value = material.alphaMap;
  15701. }
  15702. if ( material.alphaTest > 0 ) {
  15703. uniforms.alphaTest.value = material.alphaTest;
  15704. }
  15705. // uv repeat and offset setting priorities
  15706. // 1. color map
  15707. // 2. alpha map
  15708. let uvScaleMap;
  15709. if ( material.map ) {
  15710. uvScaleMap = material.map;
  15711. } else if ( material.alphaMap ) {
  15712. uvScaleMap = material.alphaMap;
  15713. }
  15714. if ( uvScaleMap !== undefined ) {
  15715. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15716. uvScaleMap.updateMatrix();
  15717. }
  15718. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15719. }
  15720. }
  15721. function refreshUniformsSprites( uniforms, material ) {
  15722. uniforms.diffuse.value.copy( material.color );
  15723. uniforms.opacity.value = material.opacity;
  15724. uniforms.rotation.value = material.rotation;
  15725. if ( material.map ) {
  15726. uniforms.map.value = material.map;
  15727. }
  15728. if ( material.alphaMap ) {
  15729. uniforms.alphaMap.value = material.alphaMap;
  15730. }
  15731. if ( material.alphaTest > 0 ) {
  15732. uniforms.alphaTest.value = material.alphaTest;
  15733. }
  15734. // uv repeat and offset setting priorities
  15735. // 1. color map
  15736. // 2. alpha map
  15737. let uvScaleMap;
  15738. if ( material.map ) {
  15739. uvScaleMap = material.map;
  15740. } else if ( material.alphaMap ) {
  15741. uvScaleMap = material.alphaMap;
  15742. }
  15743. if ( uvScaleMap !== undefined ) {
  15744. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15745. uvScaleMap.updateMatrix();
  15746. }
  15747. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15748. }
  15749. }
  15750. function refreshUniformsPhong( uniforms, material ) {
  15751. uniforms.specular.value.copy( material.specular );
  15752. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15753. }
  15754. function refreshUniformsToon( uniforms, material ) {
  15755. if ( material.gradientMap ) {
  15756. uniforms.gradientMap.value = material.gradientMap;
  15757. }
  15758. }
  15759. function refreshUniformsStandard( uniforms, material ) {
  15760. uniforms.roughness.value = material.roughness;
  15761. uniforms.metalness.value = material.metalness;
  15762. if ( material.roughnessMap ) {
  15763. uniforms.roughnessMap.value = material.roughnessMap;
  15764. }
  15765. if ( material.metalnessMap ) {
  15766. uniforms.metalnessMap.value = material.metalnessMap;
  15767. }
  15768. const envMap = properties.get( material ).envMap;
  15769. if ( envMap ) {
  15770. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15771. uniforms.envMapIntensity.value = material.envMapIntensity;
  15772. }
  15773. }
  15774. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  15775. uniforms.ior.value = material.ior; // also part of uniforms common
  15776. if ( material.sheen > 0 ) {
  15777. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  15778. uniforms.sheenRoughness.value = material.sheenRoughness;
  15779. if ( material.sheenColorMap ) {
  15780. uniforms.sheenColorMap.value = material.sheenColorMap;
  15781. }
  15782. if ( material.sheenRoughnessMap ) {
  15783. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  15784. }
  15785. }
  15786. if ( material.clearcoat > 0 ) {
  15787. uniforms.clearcoat.value = material.clearcoat;
  15788. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  15789. if ( material.clearcoatMap ) {
  15790. uniforms.clearcoatMap.value = material.clearcoatMap;
  15791. }
  15792. if ( material.clearcoatRoughnessMap ) {
  15793. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  15794. }
  15795. if ( material.clearcoatNormalMap ) {
  15796. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  15797. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  15798. if ( material.side === BackSide ) {
  15799. uniforms.clearcoatNormalScale.value.negate();
  15800. }
  15801. }
  15802. }
  15803. if ( material.iridescence > 0 ) {
  15804. uniforms.iridescence.value = material.iridescence;
  15805. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  15806. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  15807. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  15808. if ( material.iridescenceMap ) {
  15809. uniforms.iridescenceMap.value = material.iridescenceMap;
  15810. }
  15811. if ( material.iridescenceThicknessMap ) {
  15812. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  15813. }
  15814. }
  15815. if ( material.transmission > 0 ) {
  15816. uniforms.transmission.value = material.transmission;
  15817. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  15818. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  15819. if ( material.transmissionMap ) {
  15820. uniforms.transmissionMap.value = material.transmissionMap;
  15821. }
  15822. uniforms.thickness.value = material.thickness;
  15823. if ( material.thicknessMap ) {
  15824. uniforms.thicknessMap.value = material.thicknessMap;
  15825. }
  15826. uniforms.attenuationDistance.value = material.attenuationDistance;
  15827. uniforms.attenuationColor.value.copy( material.attenuationColor );
  15828. }
  15829. uniforms.specularIntensity.value = material.specularIntensity;
  15830. uniforms.specularColor.value.copy( material.specularColor );
  15831. if ( material.specularIntensityMap ) {
  15832. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  15833. }
  15834. if ( material.specularColorMap ) {
  15835. uniforms.specularColorMap.value = material.specularColorMap;
  15836. }
  15837. }
  15838. function refreshUniformsMatcap( uniforms, material ) {
  15839. if ( material.matcap ) {
  15840. uniforms.matcap.value = material.matcap;
  15841. }
  15842. }
  15843. function refreshUniformsDistance( uniforms, material ) {
  15844. uniforms.referencePosition.value.copy( material.referencePosition );
  15845. uniforms.nearDistance.value = material.nearDistance;
  15846. uniforms.farDistance.value = material.farDistance;
  15847. }
  15848. return {
  15849. refreshFogUniforms: refreshFogUniforms,
  15850. refreshMaterialUniforms: refreshMaterialUniforms
  15851. };
  15852. }
  15853. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  15854. let buffers = {};
  15855. let updateList = {};
  15856. let allocatedBindingPoints = [];
  15857. const maxBindingPoints = ( capabilities.isWebGL2 ) ? gl.getParameter( 35375 ) : 0; // binding points are global whereas block indices are per shader program
  15858. function bind( uniformsGroup, program ) {
  15859. const webglProgram = program.program;
  15860. state.uniformBlockBinding( uniformsGroup, webglProgram );
  15861. }
  15862. function update( uniformsGroup, program ) {
  15863. let buffer = buffers[ uniformsGroup.id ];
  15864. if ( buffer === undefined ) {
  15865. prepareUniformsGroup( uniformsGroup );
  15866. buffer = createBuffer( uniformsGroup );
  15867. buffers[ uniformsGroup.id ] = buffer;
  15868. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  15869. }
  15870. // ensure to update the binding points/block indices mapping for this program
  15871. const webglProgram = program.program;
  15872. state.updateUBOMapping( uniformsGroup, webglProgram );
  15873. // update UBO once per frame
  15874. const frame = info.render.frame;
  15875. if ( updateList[ uniformsGroup.id ] !== frame ) {
  15876. updateBufferData( uniformsGroup );
  15877. updateList[ uniformsGroup.id ] = frame;
  15878. }
  15879. }
  15880. function createBuffer( uniformsGroup ) {
  15881. // the setup of an UBO is independent of a particular shader program but global
  15882. const bindingPointIndex = allocateBindingPointIndex();
  15883. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  15884. const buffer = gl.createBuffer();
  15885. const size = uniformsGroup.__size;
  15886. const usage = uniformsGroup.usage;
  15887. gl.bindBuffer( 35345, buffer );
  15888. gl.bufferData( 35345, size, usage );
  15889. gl.bindBuffer( 35345, null );
  15890. gl.bindBufferBase( 35345, bindingPointIndex, buffer );
  15891. return buffer;
  15892. }
  15893. function allocateBindingPointIndex() {
  15894. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  15895. if ( allocatedBindingPoints.indexOf( i ) === - 1 ) {
  15896. allocatedBindingPoints.push( i );
  15897. return i;
  15898. }
  15899. }
  15900. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  15901. return 0;
  15902. }
  15903. function updateBufferData( uniformsGroup ) {
  15904. const buffer = buffers[ uniformsGroup.id ];
  15905. const uniforms = uniformsGroup.uniforms;
  15906. const cache = uniformsGroup.__cache;
  15907. gl.bindBuffer( 35345, buffer );
  15908. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  15909. const uniform = uniforms[ i ];
  15910. // partly update the buffer if necessary
  15911. if ( hasUniformChanged( uniform, i, cache ) === true ) {
  15912. const offset = uniform.__offset;
  15913. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  15914. let arrayOffset = 0;
  15915. for ( let i = 0; i < values.length; i ++ ) {
  15916. const value = values[ i ];
  15917. const info = getUniformSize( value );
  15918. if ( typeof value === 'number' ) {
  15919. uniform.__data[ 0 ] = value;
  15920. gl.bufferSubData( 35345, offset + arrayOffset, uniform.__data );
  15921. } else if ( value.isMatrix3 ) {
  15922. // manually converting 3x3 to 3x4
  15923. uniform.__data[ 0 ] = value.elements[ 0 ];
  15924. uniform.__data[ 1 ] = value.elements[ 1 ];
  15925. uniform.__data[ 2 ] = value.elements[ 2 ];
  15926. uniform.__data[ 3 ] = value.elements[ 0 ];
  15927. uniform.__data[ 4 ] = value.elements[ 3 ];
  15928. uniform.__data[ 5 ] = value.elements[ 4 ];
  15929. uniform.__data[ 6 ] = value.elements[ 5 ];
  15930. uniform.__data[ 7 ] = value.elements[ 0 ];
  15931. uniform.__data[ 8 ] = value.elements[ 6 ];
  15932. uniform.__data[ 9 ] = value.elements[ 7 ];
  15933. uniform.__data[ 10 ] = value.elements[ 8 ];
  15934. uniform.__data[ 11 ] = value.elements[ 0 ];
  15935. } else {
  15936. value.toArray( uniform.__data, arrayOffset );
  15937. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  15938. }
  15939. }
  15940. gl.bufferSubData( 35345, offset, uniform.__data );
  15941. }
  15942. }
  15943. gl.bindBuffer( 35345, null );
  15944. }
  15945. function hasUniformChanged( uniform, index, cache ) {
  15946. const value = uniform.value;
  15947. if ( cache[ index ] === undefined ) {
  15948. // cache entry does not exist so far
  15949. if ( typeof value === 'number' ) {
  15950. cache[ index ] = value;
  15951. } else {
  15952. const values = Array.isArray( value ) ? value : [ value ];
  15953. const tempValues = [];
  15954. for ( let i = 0; i < values.length; i ++ ) {
  15955. tempValues.push( values[ i ].clone() );
  15956. }
  15957. cache[ index ] = tempValues;
  15958. }
  15959. return true;
  15960. } else {
  15961. // compare current value with cached entry
  15962. if ( typeof value === 'number' ) {
  15963. if ( cache[ index ] !== value ) {
  15964. cache[ index ] = value;
  15965. return true;
  15966. }
  15967. } else {
  15968. const cachedObjects = Array.isArray( cache[ index ] ) ? cache[ index ] : [ cache[ index ] ];
  15969. const values = Array.isArray( value ) ? value : [ value ];
  15970. for ( let i = 0; i < cachedObjects.length; i ++ ) {
  15971. const cachedObject = cachedObjects[ i ];
  15972. if ( cachedObject.equals( values[ i ] ) === false ) {
  15973. cachedObject.copy( values[ i ] );
  15974. return true;
  15975. }
  15976. }
  15977. }
  15978. }
  15979. return false;
  15980. }
  15981. function prepareUniformsGroup( uniformsGroup ) {
  15982. // determine total buffer size according to the STD140 layout
  15983. // Hint: STD140 is the only supported layout in WebGL 2
  15984. const uniforms = uniformsGroup.uniforms;
  15985. let offset = 0; // global buffer offset in bytes
  15986. const chunkSize = 16; // size of a chunk in bytes
  15987. let chunkOffset = 0; // offset within a single chunk in bytes
  15988. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  15989. const uniform = uniforms[ i ];
  15990. const infos = {
  15991. boundary: 0, // bytes
  15992. storage: 0 // bytes
  15993. };
  15994. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  15995. for ( let j = 0, jl = values.length; j < jl; j ++ ) {
  15996. const value = values[ j ];
  15997. const info = getUniformSize( value );
  15998. infos.boundary += info.boundary;
  15999. infos.storage += info.storage;
  16000. }
  16001. // the following two properties will be used for partial buffer updates
  16002. uniform.__data = new Float32Array( infos.storage / Float32Array.BYTES_PER_ELEMENT );
  16003. uniform.__offset = offset;
  16004. //
  16005. if ( i > 0 ) {
  16006. chunkOffset = offset % chunkSize;
  16007. const remainingSizeInChunk = chunkSize - chunkOffset;
  16008. // check for chunk overflow
  16009. if ( chunkOffset !== 0 && ( remainingSizeInChunk - infos.boundary ) < 0 ) {
  16010. // add padding and adjust offset
  16011. offset += ( chunkSize - chunkOffset );
  16012. uniform.__offset = offset;
  16013. }
  16014. }
  16015. offset += infos.storage;
  16016. }
  16017. // ensure correct final padding
  16018. chunkOffset = offset % chunkSize;
  16019. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  16020. //
  16021. uniformsGroup.__size = offset;
  16022. uniformsGroup.__cache = {};
  16023. return this;
  16024. }
  16025. function getUniformSize( value ) {
  16026. const info = {
  16027. boundary: 0, // bytes
  16028. storage: 0 // bytes
  16029. };
  16030. // determine sizes according to STD140
  16031. if ( typeof value === 'number' ) {
  16032. // float/int
  16033. info.boundary = 4;
  16034. info.storage = 4;
  16035. } else if ( value.isVector2 ) {
  16036. // vec2
  16037. info.boundary = 8;
  16038. info.storage = 8;
  16039. } else if ( value.isVector3 || value.isColor ) {
  16040. // vec3
  16041. info.boundary = 16;
  16042. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  16043. } else if ( value.isVector4 ) {
  16044. // vec4
  16045. info.boundary = 16;
  16046. info.storage = 16;
  16047. } else if ( value.isMatrix3 ) {
  16048. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  16049. info.boundary = 48;
  16050. info.storage = 48;
  16051. } else if ( value.isMatrix4 ) {
  16052. // mat4
  16053. info.boundary = 64;
  16054. info.storage = 64;
  16055. } else if ( value.isTexture ) {
  16056. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  16057. } else {
  16058. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  16059. }
  16060. return info;
  16061. }
  16062. function onUniformsGroupsDispose( event ) {
  16063. const uniformsGroup = event.target;
  16064. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  16065. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  16066. allocatedBindingPoints.splice( index, 1 );
  16067. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  16068. delete buffers[ uniformsGroup.id ];
  16069. delete updateList[ uniformsGroup.id ];
  16070. }
  16071. function dispose() {
  16072. for ( const id in buffers ) {
  16073. gl.deleteBuffer( buffers[ id ] );
  16074. }
  16075. allocatedBindingPoints = [];
  16076. buffers = {};
  16077. updateList = {};
  16078. }
  16079. return {
  16080. bind: bind,
  16081. update: update,
  16082. dispose: dispose
  16083. };
  16084. }
  16085. function createCanvasElement() {
  16086. const canvas = createElementNS( 'canvas' );
  16087. canvas.style.display = 'block';
  16088. return canvas;
  16089. }
  16090. function WebGLRenderer( parameters = {} ) {
  16091. this.isWebGLRenderer = true;
  16092. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  16093. _context = parameters.context !== undefined ? parameters.context : null,
  16094. _depth = parameters.depth !== undefined ? parameters.depth : true,
  16095. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  16096. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  16097. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  16098. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  16099. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  16100. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  16101. let _alpha;
  16102. if ( _context !== null ) {
  16103. _alpha = _context.getContextAttributes().alpha;
  16104. } else {
  16105. _alpha = parameters.alpha !== undefined ? parameters.alpha : false;
  16106. }
  16107. let currentRenderList = null;
  16108. let currentRenderState = null;
  16109. // render() can be called from within a callback triggered by another render.
  16110. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  16111. const renderListStack = [];
  16112. const renderStateStack = [];
  16113. // public properties
  16114. this.domElement = _canvas;
  16115. // Debug configuration container
  16116. this.debug = {
  16117. /**
  16118. * Enables error checking and reporting when shader programs are being compiled
  16119. * @type {boolean}
  16120. */
  16121. checkShaderErrors: true
  16122. };
  16123. // clearing
  16124. this.autoClear = true;
  16125. this.autoClearColor = true;
  16126. this.autoClearDepth = true;
  16127. this.autoClearStencil = true;
  16128. // scene graph
  16129. this.sortObjects = true;
  16130. // user-defined clipping
  16131. this.clippingPlanes = [];
  16132. this.localClippingEnabled = false;
  16133. // physically based shading
  16134. this.outputEncoding = LinearEncoding;
  16135. // physical lights
  16136. this.physicallyCorrectLights = false;
  16137. // tone mapping
  16138. this.toneMapping = NoToneMapping;
  16139. this.toneMappingExposure = 1.0;
  16140. // internal properties
  16141. const _this = this;
  16142. let _isContextLost = false;
  16143. // internal state cache
  16144. let _currentActiveCubeFace = 0;
  16145. let _currentActiveMipmapLevel = 0;
  16146. let _currentRenderTarget = null;
  16147. let _currentMaterialId = - 1;
  16148. let _currentCamera = null;
  16149. const _currentViewport = new Vector4();
  16150. const _currentScissor = new Vector4();
  16151. let _currentScissorTest = null;
  16152. //
  16153. let _width = _canvas.width;
  16154. let _height = _canvas.height;
  16155. let _pixelRatio = 1;
  16156. let _opaqueSort = null;
  16157. let _transparentSort = null;
  16158. const _viewport = new Vector4( 0, 0, _width, _height );
  16159. const _scissor = new Vector4( 0, 0, _width, _height );
  16160. let _scissorTest = false;
  16161. // frustum
  16162. const _frustum = new Frustum();
  16163. // clipping
  16164. let _clippingEnabled = false;
  16165. let _localClippingEnabled = false;
  16166. // transmission
  16167. let _transmissionRenderTarget = null;
  16168. // camera matrices cache
  16169. const _projScreenMatrix = new Matrix4();
  16170. const _vector2 = new Vector2();
  16171. const _vector3 = new Vector3();
  16172. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  16173. function getTargetPixelRatio() {
  16174. return _currentRenderTarget === null ? _pixelRatio : 1;
  16175. }
  16176. // initialize
  16177. let _gl = _context;
  16178. function getContext( contextNames, contextAttributes ) {
  16179. for ( let i = 0; i < contextNames.length; i ++ ) {
  16180. const contextName = contextNames[ i ];
  16181. const context = _canvas.getContext( contextName, contextAttributes );
  16182. if ( context !== null ) return context;
  16183. }
  16184. return null;
  16185. }
  16186. try {
  16187. const contextAttributes = {
  16188. alpha: true,
  16189. depth: _depth,
  16190. stencil: _stencil,
  16191. antialias: _antialias,
  16192. premultipliedAlpha: _premultipliedAlpha,
  16193. preserveDrawingBuffer: _preserveDrawingBuffer,
  16194. powerPreference: _powerPreference,
  16195. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  16196. };
  16197. // OffscreenCanvas does not have setAttribute, see #22811
  16198. if ( 'setAttribute' in _canvas ) _canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  16199. // event listeners must be registered before WebGL context is created, see #12753
  16200. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  16201. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  16202. _canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16203. if ( _gl === null ) {
  16204. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  16205. if ( _this.isWebGL1Renderer === true ) {
  16206. contextNames.shift();
  16207. }
  16208. _gl = getContext( contextNames, contextAttributes );
  16209. if ( _gl === null ) {
  16210. if ( getContext( contextNames ) ) {
  16211. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  16212. } else {
  16213. throw new Error( 'Error creating WebGL context.' );
  16214. }
  16215. }
  16216. }
  16217. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  16218. if ( _gl.getShaderPrecisionFormat === undefined ) {
  16219. _gl.getShaderPrecisionFormat = function () {
  16220. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  16221. };
  16222. }
  16223. } catch ( error ) {
  16224. console.error( 'THREE.WebGLRenderer: ' + error.message );
  16225. throw error;
  16226. }
  16227. let extensions, capabilities, state, info;
  16228. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  16229. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  16230. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  16231. let utils, bindingStates, uniformsGroups;
  16232. function initGLContext() {
  16233. extensions = new WebGLExtensions( _gl );
  16234. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  16235. extensions.init( capabilities );
  16236. utils = new WebGLUtils( _gl, extensions, capabilities );
  16237. state = new WebGLState( _gl, extensions, capabilities );
  16238. info = new WebGLInfo();
  16239. properties = new WebGLProperties();
  16240. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  16241. cubemaps = new WebGLCubeMaps( _this );
  16242. cubeuvmaps = new WebGLCubeUVMaps( _this );
  16243. attributes = new WebGLAttributes( _gl, capabilities );
  16244. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  16245. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  16246. objects = new WebGLObjects( _gl, geometries, attributes, info );
  16247. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  16248. clipping = new WebGLClipping( properties );
  16249. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  16250. materials = new WebGLMaterials( _this, properties );
  16251. renderLists = new WebGLRenderLists();
  16252. renderStates = new WebGLRenderStates( extensions, capabilities );
  16253. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, _premultipliedAlpha );
  16254. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  16255. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  16256. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  16257. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  16258. info.programs = programCache.programs;
  16259. _this.capabilities = capabilities;
  16260. _this.extensions = extensions;
  16261. _this.properties = properties;
  16262. _this.renderLists = renderLists;
  16263. _this.shadowMap = shadowMap;
  16264. _this.state = state;
  16265. _this.info = info;
  16266. }
  16267. initGLContext();
  16268. // xr
  16269. const xr = new WebXRManager( _this, _gl );
  16270. this.xr = xr;
  16271. // API
  16272. this.getContext = function () {
  16273. return _gl;
  16274. };
  16275. this.getContextAttributes = function () {
  16276. return _gl.getContextAttributes();
  16277. };
  16278. this.forceContextLoss = function () {
  16279. const extension = extensions.get( 'WEBGL_lose_context' );
  16280. if ( extension ) extension.loseContext();
  16281. };
  16282. this.forceContextRestore = function () {
  16283. const extension = extensions.get( 'WEBGL_lose_context' );
  16284. if ( extension ) extension.restoreContext();
  16285. };
  16286. this.getPixelRatio = function () {
  16287. return _pixelRatio;
  16288. };
  16289. this.setPixelRatio = function ( value ) {
  16290. if ( value === undefined ) return;
  16291. _pixelRatio = value;
  16292. this.setSize( _width, _height, false );
  16293. };
  16294. this.getSize = function ( target ) {
  16295. return target.set( _width, _height );
  16296. };
  16297. this.setSize = function ( width, height, updateStyle ) {
  16298. if ( xr.isPresenting ) {
  16299. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  16300. return;
  16301. }
  16302. _width = width;
  16303. _height = height;
  16304. _canvas.width = Math.floor( width * _pixelRatio );
  16305. _canvas.height = Math.floor( height * _pixelRatio );
  16306. if ( updateStyle !== false ) {
  16307. _canvas.style.width = width + 'px';
  16308. _canvas.style.height = height + 'px';
  16309. }
  16310. this.setViewport( 0, 0, width, height );
  16311. };
  16312. this.getDrawingBufferSize = function ( target ) {
  16313. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  16314. };
  16315. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  16316. _width = width;
  16317. _height = height;
  16318. _pixelRatio = pixelRatio;
  16319. _canvas.width = Math.floor( width * pixelRatio );
  16320. _canvas.height = Math.floor( height * pixelRatio );
  16321. this.setViewport( 0, 0, width, height );
  16322. };
  16323. this.getCurrentViewport = function ( target ) {
  16324. return target.copy( _currentViewport );
  16325. };
  16326. this.getViewport = function ( target ) {
  16327. return target.copy( _viewport );
  16328. };
  16329. this.setViewport = function ( x, y, width, height ) {
  16330. if ( x.isVector4 ) {
  16331. _viewport.set( x.x, x.y, x.z, x.w );
  16332. } else {
  16333. _viewport.set( x, y, width, height );
  16334. }
  16335. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  16336. };
  16337. this.getScissor = function ( target ) {
  16338. return target.copy( _scissor );
  16339. };
  16340. this.setScissor = function ( x, y, width, height ) {
  16341. if ( x.isVector4 ) {
  16342. _scissor.set( x.x, x.y, x.z, x.w );
  16343. } else {
  16344. _scissor.set( x, y, width, height );
  16345. }
  16346. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  16347. };
  16348. this.getScissorTest = function () {
  16349. return _scissorTest;
  16350. };
  16351. this.setScissorTest = function ( boolean ) {
  16352. state.setScissorTest( _scissorTest = boolean );
  16353. };
  16354. this.setOpaqueSort = function ( method ) {
  16355. _opaqueSort = method;
  16356. };
  16357. this.setTransparentSort = function ( method ) {
  16358. _transparentSort = method;
  16359. };
  16360. // Clearing
  16361. this.getClearColor = function ( target ) {
  16362. return target.copy( background.getClearColor() );
  16363. };
  16364. this.setClearColor = function () {
  16365. background.setClearColor.apply( background, arguments );
  16366. };
  16367. this.getClearAlpha = function () {
  16368. return background.getClearAlpha();
  16369. };
  16370. this.setClearAlpha = function () {
  16371. background.setClearAlpha.apply( background, arguments );
  16372. };
  16373. this.clear = function ( color = true, depth = true, stencil = true ) {
  16374. let bits = 0;
  16375. if ( color ) bits |= 16384;
  16376. if ( depth ) bits |= 256;
  16377. if ( stencil ) bits |= 1024;
  16378. _gl.clear( bits );
  16379. };
  16380. this.clearColor = function () {
  16381. this.clear( true, false, false );
  16382. };
  16383. this.clearDepth = function () {
  16384. this.clear( false, true, false );
  16385. };
  16386. this.clearStencil = function () {
  16387. this.clear( false, false, true );
  16388. };
  16389. //
  16390. this.dispose = function () {
  16391. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  16392. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  16393. _canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16394. renderLists.dispose();
  16395. renderStates.dispose();
  16396. properties.dispose();
  16397. cubemaps.dispose();
  16398. cubeuvmaps.dispose();
  16399. objects.dispose();
  16400. bindingStates.dispose();
  16401. uniformsGroups.dispose();
  16402. programCache.dispose();
  16403. xr.dispose();
  16404. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  16405. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  16406. if ( _transmissionRenderTarget ) {
  16407. _transmissionRenderTarget.dispose();
  16408. _transmissionRenderTarget = null;
  16409. }
  16410. animation.stop();
  16411. };
  16412. // Events
  16413. function onContextLost( event ) {
  16414. event.preventDefault();
  16415. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  16416. _isContextLost = true;
  16417. }
  16418. function onContextRestore( /* event */ ) {
  16419. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  16420. _isContextLost = false;
  16421. const infoAutoReset = info.autoReset;
  16422. const shadowMapEnabled = shadowMap.enabled;
  16423. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  16424. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  16425. const shadowMapType = shadowMap.type;
  16426. initGLContext();
  16427. info.autoReset = infoAutoReset;
  16428. shadowMap.enabled = shadowMapEnabled;
  16429. shadowMap.autoUpdate = shadowMapAutoUpdate;
  16430. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  16431. shadowMap.type = shadowMapType;
  16432. }
  16433. function onContextCreationError( event ) {
  16434. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  16435. }
  16436. function onMaterialDispose( event ) {
  16437. const material = event.target;
  16438. material.removeEventListener( 'dispose', onMaterialDispose );
  16439. deallocateMaterial( material );
  16440. }
  16441. // Buffer deallocation
  16442. function deallocateMaterial( material ) {
  16443. releaseMaterialProgramReferences( material );
  16444. properties.remove( material );
  16445. }
  16446. function releaseMaterialProgramReferences( material ) {
  16447. const programs = properties.get( material ).programs;
  16448. if ( programs !== undefined ) {
  16449. programs.forEach( function ( program ) {
  16450. programCache.releaseProgram( program );
  16451. } );
  16452. if ( material.isShaderMaterial ) {
  16453. programCache.releaseShaderCache( material );
  16454. }
  16455. }
  16456. }
  16457. // Buffer rendering
  16458. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  16459. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  16460. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  16461. const program = setProgram( camera, scene, geometry, material, object );
  16462. state.setMaterial( material, frontFaceCW );
  16463. //
  16464. let index = geometry.index;
  16465. let rangeFactor = 1;
  16466. if ( material.wireframe === true ) {
  16467. index = geometries.getWireframeAttribute( geometry );
  16468. rangeFactor = 2;
  16469. }
  16470. //
  16471. const drawRange = geometry.drawRange;
  16472. const position = geometry.attributes.position;
  16473. let drawStart = drawRange.start * rangeFactor;
  16474. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  16475. if ( group !== null ) {
  16476. drawStart = Math.max( drawStart, group.start * rangeFactor );
  16477. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  16478. }
  16479. if ( index !== null ) {
  16480. drawStart = Math.max( drawStart, 0 );
  16481. drawEnd = Math.min( drawEnd, index.count );
  16482. } else if ( position !== undefined && position !== null ) {
  16483. drawStart = Math.max( drawStart, 0 );
  16484. drawEnd = Math.min( drawEnd, position.count );
  16485. }
  16486. const drawCount = drawEnd - drawStart;
  16487. if ( drawCount < 0 || drawCount === Infinity ) return;
  16488. //
  16489. bindingStates.setup( object, material, program, geometry, index );
  16490. let attribute;
  16491. let renderer = bufferRenderer;
  16492. if ( index !== null ) {
  16493. attribute = attributes.get( index );
  16494. renderer = indexedBufferRenderer;
  16495. renderer.setIndex( attribute );
  16496. }
  16497. //
  16498. if ( object.isMesh ) {
  16499. if ( material.wireframe === true ) {
  16500. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  16501. renderer.setMode( 1 );
  16502. } else {
  16503. renderer.setMode( 4 );
  16504. }
  16505. } else if ( object.isLine ) {
  16506. let lineWidth = material.linewidth;
  16507. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  16508. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  16509. if ( object.isLineSegments ) {
  16510. renderer.setMode( 1 );
  16511. } else if ( object.isLineLoop ) {
  16512. renderer.setMode( 2 );
  16513. } else {
  16514. renderer.setMode( 3 );
  16515. }
  16516. } else if ( object.isPoints ) {
  16517. renderer.setMode( 0 );
  16518. } else if ( object.isSprite ) {
  16519. renderer.setMode( 4 );
  16520. }
  16521. if ( object.isInstancedMesh ) {
  16522. renderer.renderInstances( drawStart, drawCount, object.count );
  16523. } else if ( geometry.isInstancedBufferGeometry ) {
  16524. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  16525. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  16526. renderer.renderInstances( drawStart, drawCount, instanceCount );
  16527. } else {
  16528. renderer.render( drawStart, drawCount );
  16529. }
  16530. };
  16531. // Compile
  16532. this.compile = function ( scene, camera ) {
  16533. function prepare( material, scene, object ) {
  16534. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  16535. material.side = BackSide;
  16536. material.needsUpdate = true;
  16537. getProgram( material, scene, object );
  16538. material.side = FrontSide;
  16539. material.needsUpdate = true;
  16540. getProgram( material, scene, object );
  16541. material.side = DoubleSide;
  16542. } else {
  16543. getProgram( material, scene, object );
  16544. }
  16545. }
  16546. currentRenderState = renderStates.get( scene );
  16547. currentRenderState.init();
  16548. renderStateStack.push( currentRenderState );
  16549. scene.traverseVisible( function ( object ) {
  16550. if ( object.isLight && object.layers.test( camera.layers ) ) {
  16551. currentRenderState.pushLight( object );
  16552. if ( object.castShadow ) {
  16553. currentRenderState.pushShadow( object );
  16554. }
  16555. }
  16556. } );
  16557. currentRenderState.setupLights( _this.physicallyCorrectLights );
  16558. scene.traverse( function ( object ) {
  16559. const material = object.material;
  16560. if ( material ) {
  16561. if ( Array.isArray( material ) ) {
  16562. for ( let i = 0; i < material.length; i ++ ) {
  16563. const material2 = material[ i ];
  16564. prepare( material2, scene, object );
  16565. }
  16566. } else {
  16567. prepare( material, scene, object );
  16568. }
  16569. }
  16570. } );
  16571. renderStateStack.pop();
  16572. currentRenderState = null;
  16573. };
  16574. // Animation Loop
  16575. let onAnimationFrameCallback = null;
  16576. function onAnimationFrame( time ) {
  16577. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  16578. }
  16579. function onXRSessionStart() {
  16580. animation.stop();
  16581. }
  16582. function onXRSessionEnd() {
  16583. animation.start();
  16584. }
  16585. const animation = new WebGLAnimation();
  16586. animation.setAnimationLoop( onAnimationFrame );
  16587. if ( typeof self !== 'undefined' ) animation.setContext( self );
  16588. this.setAnimationLoop = function ( callback ) {
  16589. onAnimationFrameCallback = callback;
  16590. xr.setAnimationLoop( callback );
  16591. ( callback === null ) ? animation.stop() : animation.start();
  16592. };
  16593. xr.addEventListener( 'sessionstart', onXRSessionStart );
  16594. xr.addEventListener( 'sessionend', onXRSessionEnd );
  16595. // Rendering
  16596. this.render = function ( scene, camera ) {
  16597. if ( camera !== undefined && camera.isCamera !== true ) {
  16598. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  16599. return;
  16600. }
  16601. if ( _isContextLost === true ) return;
  16602. // update scene graph
  16603. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  16604. // update camera matrices and frustum
  16605. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  16606. if ( xr.enabled === true && xr.isPresenting === true ) {
  16607. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  16608. camera = xr.getCamera(); // use XR camera for rendering
  16609. }
  16610. //
  16611. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  16612. currentRenderState = renderStates.get( scene, renderStateStack.length );
  16613. currentRenderState.init();
  16614. renderStateStack.push( currentRenderState );
  16615. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16616. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  16617. _localClippingEnabled = this.localClippingEnabled;
  16618. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  16619. currentRenderList = renderLists.get( scene, renderListStack.length );
  16620. currentRenderList.init();
  16621. renderListStack.push( currentRenderList );
  16622. projectObject( scene, camera, 0, _this.sortObjects );
  16623. currentRenderList.finish();
  16624. if ( _this.sortObjects === true ) {
  16625. currentRenderList.sort( _opaqueSort, _transparentSort );
  16626. }
  16627. //
  16628. if ( _clippingEnabled === true ) clipping.beginShadows();
  16629. const shadowsArray = currentRenderState.state.shadowsArray;
  16630. shadowMap.render( shadowsArray, scene, camera );
  16631. if ( _clippingEnabled === true ) clipping.endShadows();
  16632. //
  16633. if ( this.info.autoReset === true ) this.info.reset();
  16634. //
  16635. background.render( currentRenderList, scene );
  16636. // render scene
  16637. currentRenderState.setupLights( _this.physicallyCorrectLights );
  16638. if ( camera.isArrayCamera ) {
  16639. const cameras = camera.cameras;
  16640. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  16641. const camera2 = cameras[ i ];
  16642. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  16643. }
  16644. } else {
  16645. renderScene( currentRenderList, scene, camera );
  16646. }
  16647. //
  16648. if ( _currentRenderTarget !== null ) {
  16649. // resolve multisample renderbuffers to a single-sample texture if necessary
  16650. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  16651. // Generate mipmap if we're using any kind of mipmap filtering
  16652. textures.updateRenderTargetMipmap( _currentRenderTarget );
  16653. }
  16654. //
  16655. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  16656. // _gl.finish();
  16657. bindingStates.resetDefaultState();
  16658. _currentMaterialId = - 1;
  16659. _currentCamera = null;
  16660. renderStateStack.pop();
  16661. if ( renderStateStack.length > 0 ) {
  16662. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  16663. } else {
  16664. currentRenderState = null;
  16665. }
  16666. renderListStack.pop();
  16667. if ( renderListStack.length > 0 ) {
  16668. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  16669. } else {
  16670. currentRenderList = null;
  16671. }
  16672. };
  16673. function projectObject( object, camera, groupOrder, sortObjects ) {
  16674. if ( object.visible === false ) return;
  16675. const visible = object.layers.test( camera.layers );
  16676. if ( visible ) {
  16677. if ( object.isGroup ) {
  16678. groupOrder = object.renderOrder;
  16679. } else if ( object.isLOD ) {
  16680. if ( object.autoUpdate === true ) object.update( camera );
  16681. } else if ( object.isLight ) {
  16682. currentRenderState.pushLight( object );
  16683. if ( object.castShadow ) {
  16684. currentRenderState.pushShadow( object );
  16685. }
  16686. } else if ( object.isSprite ) {
  16687. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  16688. if ( sortObjects ) {
  16689. _vector3.setFromMatrixPosition( object.matrixWorld )
  16690. .applyMatrix4( _projScreenMatrix );
  16691. }
  16692. const geometry = objects.update( object );
  16693. const material = object.material;
  16694. if ( material.visible ) {
  16695. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  16696. }
  16697. }
  16698. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  16699. if ( object.isSkinnedMesh ) {
  16700. // update skeleton only once in a frame
  16701. if ( object.skeleton.frame !== info.render.frame ) {
  16702. object.skeleton.update();
  16703. object.skeleton.frame = info.render.frame;
  16704. }
  16705. }
  16706. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  16707. if ( sortObjects ) {
  16708. _vector3.setFromMatrixPosition( object.matrixWorld )
  16709. .applyMatrix4( _projScreenMatrix );
  16710. }
  16711. const geometry = objects.update( object );
  16712. const material = object.material;
  16713. if ( Array.isArray( material ) ) {
  16714. const groups = geometry.groups;
  16715. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  16716. const group = groups[ i ];
  16717. const groupMaterial = material[ group.materialIndex ];
  16718. if ( groupMaterial && groupMaterial.visible ) {
  16719. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  16720. }
  16721. }
  16722. } else if ( material.visible ) {
  16723. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  16724. }
  16725. }
  16726. }
  16727. }
  16728. const children = object.children;
  16729. for ( let i = 0, l = children.length; i < l; i ++ ) {
  16730. projectObject( children[ i ], camera, groupOrder, sortObjects );
  16731. }
  16732. }
  16733. function renderScene( currentRenderList, scene, camera, viewport ) {
  16734. const opaqueObjects = currentRenderList.opaque;
  16735. const transmissiveObjects = currentRenderList.transmissive;
  16736. const transparentObjects = currentRenderList.transparent;
  16737. currentRenderState.setupLightsView( camera );
  16738. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  16739. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, scene, camera );
  16740. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  16741. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  16742. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  16743. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  16744. // Ensure depth buffer writing is enabled so it can be cleared on next render
  16745. state.buffers.depth.setTest( true );
  16746. state.buffers.depth.setMask( true );
  16747. state.buffers.color.setMask( true );
  16748. state.setPolygonOffset( false );
  16749. }
  16750. function renderTransmissionPass( opaqueObjects, scene, camera ) {
  16751. const isWebGL2 = capabilities.isWebGL2;
  16752. if ( _transmissionRenderTarget === null ) {
  16753. _transmissionRenderTarget = new WebGLRenderTarget( 1, 1, {
  16754. generateMipmaps: true,
  16755. type: extensions.has( 'EXT_color_buffer_half_float' ) ? HalfFloatType : UnsignedByteType,
  16756. minFilter: LinearMipmapLinearFilter,
  16757. samples: ( isWebGL2 && _antialias === true ) ? 4 : 0
  16758. } );
  16759. }
  16760. _this.getDrawingBufferSize( _vector2 );
  16761. if ( isWebGL2 ) {
  16762. _transmissionRenderTarget.setSize( _vector2.x, _vector2.y );
  16763. } else {
  16764. _transmissionRenderTarget.setSize( floorPowerOfTwo( _vector2.x ), floorPowerOfTwo( _vector2.y ) );
  16765. }
  16766. //
  16767. const currentRenderTarget = _this.getRenderTarget();
  16768. _this.setRenderTarget( _transmissionRenderTarget );
  16769. _this.clear();
  16770. // Turn off the features which can affect the frag color for opaque objects pass.
  16771. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  16772. const currentToneMapping = _this.toneMapping;
  16773. _this.toneMapping = NoToneMapping;
  16774. renderObjects( opaqueObjects, scene, camera );
  16775. _this.toneMapping = currentToneMapping;
  16776. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  16777. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  16778. _this.setRenderTarget( currentRenderTarget );
  16779. }
  16780. function renderObjects( renderList, scene, camera ) {
  16781. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  16782. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  16783. const renderItem = renderList[ i ];
  16784. const object = renderItem.object;
  16785. const geometry = renderItem.geometry;
  16786. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  16787. const group = renderItem.group;
  16788. if ( object.layers.test( camera.layers ) ) {
  16789. renderObject( object, scene, camera, geometry, material, group );
  16790. }
  16791. }
  16792. }
  16793. function renderObject( object, scene, camera, geometry, material, group ) {
  16794. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  16795. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  16796. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  16797. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  16798. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  16799. material.side = BackSide;
  16800. material.needsUpdate = true;
  16801. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16802. material.side = FrontSide;
  16803. material.needsUpdate = true;
  16804. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16805. material.side = DoubleSide;
  16806. } else {
  16807. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16808. }
  16809. object.onAfterRender( _this, scene, camera, geometry, material, group );
  16810. }
  16811. function getProgram( material, scene, object ) {
  16812. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16813. const materialProperties = properties.get( material );
  16814. const lights = currentRenderState.state.lights;
  16815. const shadowsArray = currentRenderState.state.shadowsArray;
  16816. const lightsStateVersion = lights.state.version;
  16817. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  16818. const programCacheKey = programCache.getProgramCacheKey( parameters );
  16819. let programs = materialProperties.programs;
  16820. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  16821. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  16822. materialProperties.fog = scene.fog;
  16823. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  16824. if ( programs === undefined ) {
  16825. // new material
  16826. material.addEventListener( 'dispose', onMaterialDispose );
  16827. programs = new Map();
  16828. materialProperties.programs = programs;
  16829. }
  16830. let program = programs.get( programCacheKey );
  16831. if ( program !== undefined ) {
  16832. // early out if program and light state is identical
  16833. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  16834. updateCommonMaterialProperties( material, parameters );
  16835. return program;
  16836. }
  16837. } else {
  16838. parameters.uniforms = programCache.getUniforms( material );
  16839. material.onBuild( object, parameters, _this );
  16840. material.onBeforeCompile( parameters, _this );
  16841. program = programCache.acquireProgram( parameters, programCacheKey );
  16842. programs.set( programCacheKey, program );
  16843. materialProperties.uniforms = parameters.uniforms;
  16844. }
  16845. const uniforms = materialProperties.uniforms;
  16846. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  16847. uniforms.clippingPlanes = clipping.uniform;
  16848. }
  16849. updateCommonMaterialProperties( material, parameters );
  16850. // store the light setup it was created for
  16851. materialProperties.needsLights = materialNeedsLights( material );
  16852. materialProperties.lightsStateVersion = lightsStateVersion;
  16853. if ( materialProperties.needsLights ) {
  16854. // wire up the material to this renderer's lighting state
  16855. uniforms.ambientLightColor.value = lights.state.ambient;
  16856. uniforms.lightProbe.value = lights.state.probe;
  16857. uniforms.directionalLights.value = lights.state.directional;
  16858. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  16859. uniforms.spotLights.value = lights.state.spot;
  16860. uniforms.spotLightShadows.value = lights.state.spotShadow;
  16861. uniforms.rectAreaLights.value = lights.state.rectArea;
  16862. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  16863. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  16864. uniforms.pointLights.value = lights.state.point;
  16865. uniforms.pointLightShadows.value = lights.state.pointShadow;
  16866. uniforms.hemisphereLights.value = lights.state.hemi;
  16867. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  16868. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  16869. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  16870. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  16871. uniforms.spotLightMap.value = lights.state.spotLightMap;
  16872. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  16873. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  16874. // TODO (abelnation): add area lights shadow info to uniforms
  16875. }
  16876. const progUniforms = program.getUniforms();
  16877. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  16878. materialProperties.currentProgram = program;
  16879. materialProperties.uniformsList = uniformsList;
  16880. return program;
  16881. }
  16882. function updateCommonMaterialProperties( material, parameters ) {
  16883. const materialProperties = properties.get( material );
  16884. materialProperties.outputEncoding = parameters.outputEncoding;
  16885. materialProperties.instancing = parameters.instancing;
  16886. materialProperties.skinning = parameters.skinning;
  16887. materialProperties.morphTargets = parameters.morphTargets;
  16888. materialProperties.morphNormals = parameters.morphNormals;
  16889. materialProperties.morphColors = parameters.morphColors;
  16890. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  16891. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  16892. materialProperties.numIntersection = parameters.numClipIntersection;
  16893. materialProperties.vertexAlphas = parameters.vertexAlphas;
  16894. materialProperties.vertexTangents = parameters.vertexTangents;
  16895. materialProperties.toneMapping = parameters.toneMapping;
  16896. }
  16897. function setProgram( camera, scene, geometry, material, object ) {
  16898. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16899. textures.resetTextureUnits();
  16900. const fog = scene.fog;
  16901. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  16902. const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding );
  16903. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  16904. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  16905. const vertexTangents = !! material.normalMap && !! geometry.attributes.tangent;
  16906. const morphTargets = !! geometry.morphAttributes.position;
  16907. const morphNormals = !! geometry.morphAttributes.normal;
  16908. const morphColors = !! geometry.morphAttributes.color;
  16909. const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping;
  16910. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  16911. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  16912. const materialProperties = properties.get( material );
  16913. const lights = currentRenderState.state.lights;
  16914. if ( _clippingEnabled === true ) {
  16915. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  16916. const useCache =
  16917. camera === _currentCamera &&
  16918. material.id === _currentMaterialId;
  16919. // we might want to call this function with some ClippingGroup
  16920. // object instead of the material, once it becomes feasible
  16921. // (#8465, #8379)
  16922. clipping.setState( material, camera, useCache );
  16923. }
  16924. }
  16925. //
  16926. let needsProgramChange = false;
  16927. if ( material.version === materialProperties.__version ) {
  16928. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  16929. needsProgramChange = true;
  16930. } else if ( materialProperties.outputEncoding !== encoding ) {
  16931. needsProgramChange = true;
  16932. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  16933. needsProgramChange = true;
  16934. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  16935. needsProgramChange = true;
  16936. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  16937. needsProgramChange = true;
  16938. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  16939. needsProgramChange = true;
  16940. } else if ( materialProperties.envMap !== envMap ) {
  16941. needsProgramChange = true;
  16942. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  16943. needsProgramChange = true;
  16944. } else if ( materialProperties.numClippingPlanes !== undefined &&
  16945. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  16946. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  16947. needsProgramChange = true;
  16948. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  16949. needsProgramChange = true;
  16950. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  16951. needsProgramChange = true;
  16952. } else if ( materialProperties.morphTargets !== morphTargets ) {
  16953. needsProgramChange = true;
  16954. } else if ( materialProperties.morphNormals !== morphNormals ) {
  16955. needsProgramChange = true;
  16956. } else if ( materialProperties.morphColors !== morphColors ) {
  16957. needsProgramChange = true;
  16958. } else if ( materialProperties.toneMapping !== toneMapping ) {
  16959. needsProgramChange = true;
  16960. } else if ( capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount ) {
  16961. needsProgramChange = true;
  16962. }
  16963. } else {
  16964. needsProgramChange = true;
  16965. materialProperties.__version = material.version;
  16966. }
  16967. //
  16968. let program = materialProperties.currentProgram;
  16969. if ( needsProgramChange === true ) {
  16970. program = getProgram( material, scene, object );
  16971. }
  16972. let refreshProgram = false;
  16973. let refreshMaterial = false;
  16974. let refreshLights = false;
  16975. const p_uniforms = program.getUniforms(),
  16976. m_uniforms = materialProperties.uniforms;
  16977. if ( state.useProgram( program.program ) ) {
  16978. refreshProgram = true;
  16979. refreshMaterial = true;
  16980. refreshLights = true;
  16981. }
  16982. if ( material.id !== _currentMaterialId ) {
  16983. _currentMaterialId = material.id;
  16984. refreshMaterial = true;
  16985. }
  16986. if ( refreshProgram || _currentCamera !== camera ) {
  16987. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  16988. if ( capabilities.logarithmicDepthBuffer ) {
  16989. p_uniforms.setValue( _gl, 'logDepthBufFC',
  16990. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  16991. }
  16992. if ( _currentCamera !== camera ) {
  16993. _currentCamera = camera;
  16994. // lighting uniforms depend on the camera so enforce an update
  16995. // now, in case this material supports lights - or later, when
  16996. // the next material that does gets activated:
  16997. refreshMaterial = true; // set to true on material change
  16998. refreshLights = true; // remains set until update done
  16999. }
  17000. // load material specific uniforms
  17001. // (shader material also gets them for the sake of genericity)
  17002. if ( material.isShaderMaterial ||
  17003. material.isMeshPhongMaterial ||
  17004. material.isMeshToonMaterial ||
  17005. material.isMeshStandardMaterial ||
  17006. material.envMap ) {
  17007. const uCamPos = p_uniforms.map.cameraPosition;
  17008. if ( uCamPos !== undefined ) {
  17009. uCamPos.setValue( _gl,
  17010. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  17011. }
  17012. }
  17013. if ( material.isMeshPhongMaterial ||
  17014. material.isMeshToonMaterial ||
  17015. material.isMeshLambertMaterial ||
  17016. material.isMeshBasicMaterial ||
  17017. material.isMeshStandardMaterial ||
  17018. material.isShaderMaterial ) {
  17019. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  17020. }
  17021. if ( material.isMeshPhongMaterial ||
  17022. material.isMeshToonMaterial ||
  17023. material.isMeshLambertMaterial ||
  17024. material.isMeshBasicMaterial ||
  17025. material.isMeshStandardMaterial ||
  17026. material.isShaderMaterial ||
  17027. material.isShadowMaterial ||
  17028. object.isSkinnedMesh ) {
  17029. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  17030. }
  17031. }
  17032. // skinning and morph target uniforms must be set even if material didn't change
  17033. // auto-setting of texture unit for bone and morph texture must go before other textures
  17034. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  17035. if ( object.isSkinnedMesh ) {
  17036. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  17037. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  17038. const skeleton = object.skeleton;
  17039. if ( skeleton ) {
  17040. if ( capabilities.floatVertexTextures ) {
  17041. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  17042. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  17043. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  17044. } else {
  17045. console.warn( 'THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.' );
  17046. }
  17047. }
  17048. }
  17049. const morphAttributes = geometry.morphAttributes;
  17050. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined && capabilities.isWebGL2 === true ) ) {
  17051. morphtargets.update( object, geometry, material, program );
  17052. }
  17053. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  17054. materialProperties.receiveShadow = object.receiveShadow;
  17055. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  17056. }
  17057. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  17058. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  17059. m_uniforms.envMap.value = envMap;
  17060. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  17061. }
  17062. if ( refreshMaterial ) {
  17063. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  17064. if ( materialProperties.needsLights ) {
  17065. // the current material requires lighting info
  17066. // note: all lighting uniforms are always set correctly
  17067. // they simply reference the renderer's state for their
  17068. // values
  17069. //
  17070. // use the current material's .needsUpdate flags to set
  17071. // the GL state when required
  17072. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  17073. }
  17074. // refresh uniforms common to several materials
  17075. if ( fog && material.fog === true ) {
  17076. materials.refreshFogUniforms( m_uniforms, fog );
  17077. }
  17078. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget );
  17079. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17080. }
  17081. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  17082. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17083. material.uniformsNeedUpdate = false;
  17084. }
  17085. if ( material.isSpriteMaterial ) {
  17086. p_uniforms.setValue( _gl, 'center', object.center );
  17087. }
  17088. // common matrices
  17089. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  17090. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  17091. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  17092. // UBOs
  17093. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  17094. const groups = material.uniformsGroups;
  17095. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17096. if ( capabilities.isWebGL2 ) {
  17097. const group = groups[ i ];
  17098. uniformsGroups.update( group, program );
  17099. uniformsGroups.bind( group, program );
  17100. } else {
  17101. console.warn( 'THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.' );
  17102. }
  17103. }
  17104. }
  17105. return program;
  17106. }
  17107. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  17108. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  17109. uniforms.ambientLightColor.needsUpdate = value;
  17110. uniforms.lightProbe.needsUpdate = value;
  17111. uniforms.directionalLights.needsUpdate = value;
  17112. uniforms.directionalLightShadows.needsUpdate = value;
  17113. uniforms.pointLights.needsUpdate = value;
  17114. uniforms.pointLightShadows.needsUpdate = value;
  17115. uniforms.spotLights.needsUpdate = value;
  17116. uniforms.spotLightShadows.needsUpdate = value;
  17117. uniforms.rectAreaLights.needsUpdate = value;
  17118. uniforms.hemisphereLights.needsUpdate = value;
  17119. }
  17120. function materialNeedsLights( material ) {
  17121. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  17122. material.isMeshStandardMaterial || material.isShadowMaterial ||
  17123. ( material.isShaderMaterial && material.lights === true );
  17124. }
  17125. this.getActiveCubeFace = function () {
  17126. return _currentActiveCubeFace;
  17127. };
  17128. this.getActiveMipmapLevel = function () {
  17129. return _currentActiveMipmapLevel;
  17130. };
  17131. this.getRenderTarget = function () {
  17132. return _currentRenderTarget;
  17133. };
  17134. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  17135. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  17136. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  17137. const renderTargetProperties = properties.get( renderTarget );
  17138. renderTargetProperties.__hasExternalTextures = true;
  17139. if ( renderTargetProperties.__hasExternalTextures ) {
  17140. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  17141. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  17142. // The multisample_render_to_texture extension doesn't work properly if there
  17143. // are midframe flushes and an external depth buffer. Disable use of the extension.
  17144. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  17145. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  17146. renderTargetProperties.__useRenderToTexture = false;
  17147. }
  17148. }
  17149. }
  17150. };
  17151. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  17152. const renderTargetProperties = properties.get( renderTarget );
  17153. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  17154. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  17155. };
  17156. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  17157. _currentRenderTarget = renderTarget;
  17158. _currentActiveCubeFace = activeCubeFace;
  17159. _currentActiveMipmapLevel = activeMipmapLevel;
  17160. let useDefaultFramebuffer = true;
  17161. let framebuffer = null;
  17162. let isCube = false;
  17163. let isRenderTarget3D = false;
  17164. if ( renderTarget ) {
  17165. const renderTargetProperties = properties.get( renderTarget );
  17166. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  17167. // We need to make sure to rebind the framebuffer.
  17168. state.bindFramebuffer( 36160, null );
  17169. useDefaultFramebuffer = false;
  17170. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  17171. textures.setupRenderTarget( renderTarget );
  17172. } else if ( renderTargetProperties.__hasExternalTextures ) {
  17173. // Color and depth texture must be rebound in order for the swapchain to update.
  17174. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  17175. }
  17176. const texture = renderTarget.texture;
  17177. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  17178. isRenderTarget3D = true;
  17179. }
  17180. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17181. if ( renderTarget.isWebGLCubeRenderTarget ) {
  17182. framebuffer = __webglFramebuffer[ activeCubeFace ];
  17183. isCube = true;
  17184. } else if ( ( capabilities.isWebGL2 && renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  17185. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  17186. } else {
  17187. framebuffer = __webglFramebuffer;
  17188. }
  17189. _currentViewport.copy( renderTarget.viewport );
  17190. _currentScissor.copy( renderTarget.scissor );
  17191. _currentScissorTest = renderTarget.scissorTest;
  17192. } else {
  17193. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  17194. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  17195. _currentScissorTest = _scissorTest;
  17196. }
  17197. const framebufferBound = state.bindFramebuffer( 36160, framebuffer );
  17198. if ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) {
  17199. state.drawBuffers( renderTarget, framebuffer );
  17200. }
  17201. state.viewport( _currentViewport );
  17202. state.scissor( _currentScissor );
  17203. state.setScissorTest( _currentScissorTest );
  17204. if ( isCube ) {
  17205. const textureProperties = properties.get( renderTarget.texture );
  17206. _gl.framebufferTexture2D( 36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  17207. } else if ( isRenderTarget3D ) {
  17208. const textureProperties = properties.get( renderTarget.texture );
  17209. const layer = activeCubeFace || 0;
  17210. _gl.framebufferTextureLayer( 36160, 36064, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  17211. }
  17212. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  17213. };
  17214. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  17215. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  17216. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  17217. return;
  17218. }
  17219. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17220. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  17221. framebuffer = framebuffer[ activeCubeFaceIndex ];
  17222. }
  17223. if ( framebuffer ) {
  17224. state.bindFramebuffer( 36160, framebuffer );
  17225. try {
  17226. const texture = renderTarget.texture;
  17227. const textureFormat = texture.format;
  17228. const textureType = texture.type;
  17229. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
  17230. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  17231. return;
  17232. }
  17233. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) );
  17234. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // Edge and Chrome Mac < 52 (#9513)
  17235. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  17236. ! halfFloatSupportedByExt ) {
  17237. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  17238. return;
  17239. }
  17240. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  17241. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  17242. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  17243. }
  17244. } finally {
  17245. // restore framebuffer of current render target if necessary
  17246. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  17247. state.bindFramebuffer( 36160, framebuffer );
  17248. }
  17249. }
  17250. };
  17251. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  17252. const levelScale = Math.pow( 2, - level );
  17253. const width = Math.floor( texture.image.width * levelScale );
  17254. const height = Math.floor( texture.image.height * levelScale );
  17255. textures.setTexture2D( texture, 0 );
  17256. _gl.copyTexSubImage2D( 3553, level, 0, 0, position.x, position.y, width, height );
  17257. state.unbindTexture();
  17258. };
  17259. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  17260. const width = srcTexture.image.width;
  17261. const height = srcTexture.image.height;
  17262. const glFormat = utils.convert( dstTexture.format );
  17263. const glType = utils.convert( dstTexture.type );
  17264. textures.setTexture2D( dstTexture, 0 );
  17265. // As another texture upload may have changed pixelStorei
  17266. // parameters, make sure they are correct for the dstTexture
  17267. _gl.pixelStorei( 37440, dstTexture.flipY );
  17268. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  17269. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  17270. if ( srcTexture.isDataTexture ) {
  17271. _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  17272. } else {
  17273. if ( srcTexture.isCompressedTexture ) {
  17274. _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  17275. } else {
  17276. _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image );
  17277. }
  17278. }
  17279. // Generate mipmaps only when copying level 0
  17280. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 );
  17281. state.unbindTexture();
  17282. };
  17283. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  17284. if ( _this.isWebGL1Renderer ) {
  17285. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' );
  17286. return;
  17287. }
  17288. const width = sourceBox.max.x - sourceBox.min.x + 1;
  17289. const height = sourceBox.max.y - sourceBox.min.y + 1;
  17290. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  17291. const glFormat = utils.convert( dstTexture.format );
  17292. const glType = utils.convert( dstTexture.type );
  17293. let glTarget;
  17294. if ( dstTexture.isData3DTexture ) {
  17295. textures.setTexture3D( dstTexture, 0 );
  17296. glTarget = 32879;
  17297. } else if ( dstTexture.isDataArrayTexture ) {
  17298. textures.setTexture2DArray( dstTexture, 0 );
  17299. glTarget = 35866;
  17300. } else {
  17301. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  17302. return;
  17303. }
  17304. _gl.pixelStorei( 37440, dstTexture.flipY );
  17305. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  17306. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  17307. const unpackRowLen = _gl.getParameter( 3314 );
  17308. const unpackImageHeight = _gl.getParameter( 32878 );
  17309. const unpackSkipPixels = _gl.getParameter( 3316 );
  17310. const unpackSkipRows = _gl.getParameter( 3315 );
  17311. const unpackSkipImages = _gl.getParameter( 32877 );
  17312. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image;
  17313. _gl.pixelStorei( 3314, image.width );
  17314. _gl.pixelStorei( 32878, image.height );
  17315. _gl.pixelStorei( 3316, sourceBox.min.x );
  17316. _gl.pixelStorei( 3315, sourceBox.min.y );
  17317. _gl.pixelStorei( 32877, sourceBox.min.z );
  17318. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  17319. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data );
  17320. } else {
  17321. if ( srcTexture.isCompressedArrayTexture ) {
  17322. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' );
  17323. _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data );
  17324. } else {
  17325. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image );
  17326. }
  17327. }
  17328. _gl.pixelStorei( 3314, unpackRowLen );
  17329. _gl.pixelStorei( 32878, unpackImageHeight );
  17330. _gl.pixelStorei( 3316, unpackSkipPixels );
  17331. _gl.pixelStorei( 3315, unpackSkipRows );
  17332. _gl.pixelStorei( 32877, unpackSkipImages );
  17333. // Generate mipmaps only when copying level 0
  17334. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  17335. state.unbindTexture();
  17336. };
  17337. this.initTexture = function ( texture ) {
  17338. if ( texture.isCubeTexture ) {
  17339. textures.setTextureCube( texture, 0 );
  17340. } else if ( texture.isData3DTexture ) {
  17341. textures.setTexture3D( texture, 0 );
  17342. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  17343. textures.setTexture2DArray( texture, 0 );
  17344. } else {
  17345. textures.setTexture2D( texture, 0 );
  17346. }
  17347. state.unbindTexture();
  17348. };
  17349. this.resetState = function () {
  17350. _currentActiveCubeFace = 0;
  17351. _currentActiveMipmapLevel = 0;
  17352. _currentRenderTarget = null;
  17353. state.reset();
  17354. bindingStates.reset();
  17355. };
  17356. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17357. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17358. }
  17359. }
  17360. class WebGL1Renderer extends WebGLRenderer {}
  17361. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  17362. class FogExp2 {
  17363. constructor( color, density = 0.00025 ) {
  17364. this.isFogExp2 = true;
  17365. this.name = '';
  17366. this.color = new Color( color );
  17367. this.density = density;
  17368. }
  17369. clone() {
  17370. return new FogExp2( this.color, this.density );
  17371. }
  17372. toJSON( /* meta */ ) {
  17373. return {
  17374. type: 'FogExp2',
  17375. color: this.color.getHex(),
  17376. density: this.density
  17377. };
  17378. }
  17379. }
  17380. class Fog {
  17381. constructor( color, near = 1, far = 1000 ) {
  17382. this.isFog = true;
  17383. this.name = '';
  17384. this.color = new Color( color );
  17385. this.near = near;
  17386. this.far = far;
  17387. }
  17388. clone() {
  17389. return new Fog( this.color, this.near, this.far );
  17390. }
  17391. toJSON( /* meta */ ) {
  17392. return {
  17393. type: 'Fog',
  17394. color: this.color.getHex(),
  17395. near: this.near,
  17396. far: this.far
  17397. };
  17398. }
  17399. }
  17400. class Scene extends Object3D {
  17401. constructor() {
  17402. super();
  17403. this.isScene = true;
  17404. this.type = 'Scene';
  17405. this.background = null;
  17406. this.environment = null;
  17407. this.fog = null;
  17408. this.backgroundBlurriness = 0;
  17409. this.backgroundIntensity = 1;
  17410. this.overrideMaterial = null;
  17411. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17412. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17413. }
  17414. }
  17415. copy( source, recursive ) {
  17416. super.copy( source, recursive );
  17417. if ( source.background !== null ) this.background = source.background.clone();
  17418. if ( source.environment !== null ) this.environment = source.environment.clone();
  17419. if ( source.fog !== null ) this.fog = source.fog.clone();
  17420. this.backgroundBlurriness = source.backgroundBlurriness;
  17421. this.backgroundIntensity = source.backgroundIntensity;
  17422. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17423. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17424. return this;
  17425. }
  17426. toJSON( meta ) {
  17427. const data = super.toJSON( meta );
  17428. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17429. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  17430. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  17431. return data;
  17432. }
  17433. // @deprecated
  17434. get autoUpdate() {
  17435. console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' );
  17436. return this.matrixWorldAutoUpdate;
  17437. }
  17438. set autoUpdate( value ) {
  17439. console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' );
  17440. this.matrixWorldAutoUpdate = value;
  17441. }
  17442. }
  17443. class InterleavedBuffer {
  17444. constructor( array, stride ) {
  17445. this.isInterleavedBuffer = true;
  17446. this.array = array;
  17447. this.stride = stride;
  17448. this.count = array !== undefined ? array.length / stride : 0;
  17449. this.usage = StaticDrawUsage;
  17450. this.updateRange = { offset: 0, count: - 1 };
  17451. this.version = 0;
  17452. this.uuid = generateUUID();
  17453. }
  17454. onUploadCallback() {}
  17455. set needsUpdate( value ) {
  17456. if ( value === true ) this.version ++;
  17457. }
  17458. setUsage( value ) {
  17459. this.usage = value;
  17460. return this;
  17461. }
  17462. copy( source ) {
  17463. this.array = new source.array.constructor( source.array );
  17464. this.count = source.count;
  17465. this.stride = source.stride;
  17466. this.usage = source.usage;
  17467. return this;
  17468. }
  17469. copyAt( index1, attribute, index2 ) {
  17470. index1 *= this.stride;
  17471. index2 *= attribute.stride;
  17472. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17473. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  17474. }
  17475. return this;
  17476. }
  17477. set( value, offset = 0 ) {
  17478. this.array.set( value, offset );
  17479. return this;
  17480. }
  17481. clone( data ) {
  17482. if ( data.arrayBuffers === undefined ) {
  17483. data.arrayBuffers = {};
  17484. }
  17485. if ( this.array.buffer._uuid === undefined ) {
  17486. this.array.buffer._uuid = generateUUID();
  17487. }
  17488. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17489. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17490. }
  17491. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17492. const ib = new this.constructor( array, this.stride );
  17493. ib.setUsage( this.usage );
  17494. return ib;
  17495. }
  17496. onUpload( callback ) {
  17497. this.onUploadCallback = callback;
  17498. return this;
  17499. }
  17500. toJSON( data ) {
  17501. if ( data.arrayBuffers === undefined ) {
  17502. data.arrayBuffers = {};
  17503. }
  17504. // generate UUID for array buffer if necessary
  17505. if ( this.array.buffer._uuid === undefined ) {
  17506. this.array.buffer._uuid = generateUUID();
  17507. }
  17508. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17509. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17510. }
  17511. //
  17512. return {
  17513. uuid: this.uuid,
  17514. buffer: this.array.buffer._uuid,
  17515. type: this.array.constructor.name,
  17516. stride: this.stride
  17517. };
  17518. }
  17519. }
  17520. const _vector$6 = /*@__PURE__*/ new Vector3();
  17521. class InterleavedBufferAttribute {
  17522. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17523. this.isInterleavedBufferAttribute = true;
  17524. this.name = '';
  17525. this.data = interleavedBuffer;
  17526. this.itemSize = itemSize;
  17527. this.offset = offset;
  17528. this.normalized = normalized;
  17529. }
  17530. get count() {
  17531. return this.data.count;
  17532. }
  17533. get array() {
  17534. return this.data.array;
  17535. }
  17536. set needsUpdate( value ) {
  17537. this.data.needsUpdate = value;
  17538. }
  17539. applyMatrix4( m ) {
  17540. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17541. _vector$6.fromBufferAttribute( this, i );
  17542. _vector$6.applyMatrix4( m );
  17543. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17544. }
  17545. return this;
  17546. }
  17547. applyNormalMatrix( m ) {
  17548. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17549. _vector$6.fromBufferAttribute( this, i );
  17550. _vector$6.applyNormalMatrix( m );
  17551. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17552. }
  17553. return this;
  17554. }
  17555. transformDirection( m ) {
  17556. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17557. _vector$6.fromBufferAttribute( this, i );
  17558. _vector$6.transformDirection( m );
  17559. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17560. }
  17561. return this;
  17562. }
  17563. setX( index, x ) {
  17564. if ( this.normalized ) x = normalize( x, this.array );
  17565. this.data.array[ index * this.data.stride + this.offset ] = x;
  17566. return this;
  17567. }
  17568. setY( index, y ) {
  17569. if ( this.normalized ) y = normalize( y, this.array );
  17570. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17571. return this;
  17572. }
  17573. setZ( index, z ) {
  17574. if ( this.normalized ) z = normalize( z, this.array );
  17575. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17576. return this;
  17577. }
  17578. setW( index, w ) {
  17579. if ( this.normalized ) w = normalize( w, this.array );
  17580. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17581. return this;
  17582. }
  17583. getX( index ) {
  17584. let x = this.data.array[ index * this.data.stride + this.offset ];
  17585. if ( this.normalized ) x = denormalize( x, this.array );
  17586. return x;
  17587. }
  17588. getY( index ) {
  17589. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17590. if ( this.normalized ) y = denormalize( y, this.array );
  17591. return y;
  17592. }
  17593. getZ( index ) {
  17594. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17595. if ( this.normalized ) z = denormalize( z, this.array );
  17596. return z;
  17597. }
  17598. getW( index ) {
  17599. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17600. if ( this.normalized ) w = denormalize( w, this.array );
  17601. return w;
  17602. }
  17603. setXY( index, x, y ) {
  17604. index = index * this.data.stride + this.offset;
  17605. if ( this.normalized ) {
  17606. x = normalize( x, this.array );
  17607. y = normalize( y, this.array );
  17608. }
  17609. this.data.array[ index + 0 ] = x;
  17610. this.data.array[ index + 1 ] = y;
  17611. return this;
  17612. }
  17613. setXYZ( index, x, y, z ) {
  17614. index = index * this.data.stride + this.offset;
  17615. if ( this.normalized ) {
  17616. x = normalize( x, this.array );
  17617. y = normalize( y, this.array );
  17618. z = normalize( z, this.array );
  17619. }
  17620. this.data.array[ index + 0 ] = x;
  17621. this.data.array[ index + 1 ] = y;
  17622. this.data.array[ index + 2 ] = z;
  17623. return this;
  17624. }
  17625. setXYZW( index, x, y, z, w ) {
  17626. index = index * this.data.stride + this.offset;
  17627. if ( this.normalized ) {
  17628. x = normalize( x, this.array );
  17629. y = normalize( y, this.array );
  17630. z = normalize( z, this.array );
  17631. w = normalize( w, this.array );
  17632. }
  17633. this.data.array[ index + 0 ] = x;
  17634. this.data.array[ index + 1 ] = y;
  17635. this.data.array[ index + 2 ] = z;
  17636. this.data.array[ index + 3 ] = w;
  17637. return this;
  17638. }
  17639. clone( data ) {
  17640. if ( data === undefined ) {
  17641. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  17642. const array = [];
  17643. for ( let i = 0; i < this.count; i ++ ) {
  17644. const index = i * this.data.stride + this.offset;
  17645. for ( let j = 0; j < this.itemSize; j ++ ) {
  17646. array.push( this.data.array[ index + j ] );
  17647. }
  17648. }
  17649. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17650. } else {
  17651. if ( data.interleavedBuffers === undefined ) {
  17652. data.interleavedBuffers = {};
  17653. }
  17654. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17655. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17656. }
  17657. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17658. }
  17659. }
  17660. toJSON( data ) {
  17661. if ( data === undefined ) {
  17662. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  17663. const array = [];
  17664. for ( let i = 0; i < this.count; i ++ ) {
  17665. const index = i * this.data.stride + this.offset;
  17666. for ( let j = 0; j < this.itemSize; j ++ ) {
  17667. array.push( this.data.array[ index + j ] );
  17668. }
  17669. }
  17670. // de-interleave data and save it as an ordinary buffer attribute for now
  17671. return {
  17672. itemSize: this.itemSize,
  17673. type: this.array.constructor.name,
  17674. array: array,
  17675. normalized: this.normalized
  17676. };
  17677. } else {
  17678. // save as true interleaved attribute
  17679. if ( data.interleavedBuffers === undefined ) {
  17680. data.interleavedBuffers = {};
  17681. }
  17682. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17683. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17684. }
  17685. return {
  17686. isInterleavedBufferAttribute: true,
  17687. itemSize: this.itemSize,
  17688. data: this.data.uuid,
  17689. offset: this.offset,
  17690. normalized: this.normalized
  17691. };
  17692. }
  17693. }
  17694. }
  17695. class SpriteMaterial extends Material {
  17696. constructor( parameters ) {
  17697. super();
  17698. this.isSpriteMaterial = true;
  17699. this.type = 'SpriteMaterial';
  17700. this.color = new Color( 0xffffff );
  17701. this.map = null;
  17702. this.alphaMap = null;
  17703. this.rotation = 0;
  17704. this.sizeAttenuation = true;
  17705. this.transparent = true;
  17706. this.fog = true;
  17707. this.setValues( parameters );
  17708. }
  17709. copy( source ) {
  17710. super.copy( source );
  17711. this.color.copy( source.color );
  17712. this.map = source.map;
  17713. this.alphaMap = source.alphaMap;
  17714. this.rotation = source.rotation;
  17715. this.sizeAttenuation = source.sizeAttenuation;
  17716. this.fog = source.fog;
  17717. return this;
  17718. }
  17719. }
  17720. let _geometry;
  17721. const _intersectPoint = /*@__PURE__*/ new Vector3();
  17722. const _worldScale = /*@__PURE__*/ new Vector3();
  17723. const _mvPosition = /*@__PURE__*/ new Vector3();
  17724. const _alignedPosition = /*@__PURE__*/ new Vector2();
  17725. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  17726. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  17727. const _vA = /*@__PURE__*/ new Vector3();
  17728. const _vB = /*@__PURE__*/ new Vector3();
  17729. const _vC = /*@__PURE__*/ new Vector3();
  17730. const _uvA = /*@__PURE__*/ new Vector2();
  17731. const _uvB = /*@__PURE__*/ new Vector2();
  17732. const _uvC = /*@__PURE__*/ new Vector2();
  17733. class Sprite extends Object3D {
  17734. constructor( material ) {
  17735. super();
  17736. this.isSprite = true;
  17737. this.type = 'Sprite';
  17738. if ( _geometry === undefined ) {
  17739. _geometry = new BufferGeometry();
  17740. const float32Array = new Float32Array( [
  17741. - 0.5, - 0.5, 0, 0, 0,
  17742. 0.5, - 0.5, 0, 1, 0,
  17743. 0.5, 0.5, 0, 1, 1,
  17744. - 0.5, 0.5, 0, 0, 1
  17745. ] );
  17746. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  17747. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  17748. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  17749. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  17750. }
  17751. this.geometry = _geometry;
  17752. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  17753. this.center = new Vector2( 0.5, 0.5 );
  17754. }
  17755. raycast( raycaster, intersects ) {
  17756. if ( raycaster.camera === null ) {
  17757. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  17758. }
  17759. _worldScale.setFromMatrixScale( this.matrixWorld );
  17760. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  17761. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  17762. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  17763. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  17764. _worldScale.multiplyScalar( - _mvPosition.z );
  17765. }
  17766. const rotation = this.material.rotation;
  17767. let sin, cos;
  17768. if ( rotation !== 0 ) {
  17769. cos = Math.cos( rotation );
  17770. sin = Math.sin( rotation );
  17771. }
  17772. const center = this.center;
  17773. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17774. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17775. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17776. _uvA.set( 0, 0 );
  17777. _uvB.set( 1, 0 );
  17778. _uvC.set( 1, 1 );
  17779. // check first triangle
  17780. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  17781. if ( intersect === null ) {
  17782. // check second triangle
  17783. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17784. _uvB.set( 0, 1 );
  17785. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  17786. if ( intersect === null ) {
  17787. return;
  17788. }
  17789. }
  17790. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  17791. if ( distance < raycaster.near || distance > raycaster.far ) return;
  17792. intersects.push( {
  17793. distance: distance,
  17794. point: _intersectPoint.clone(),
  17795. uv: Triangle.getUV( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  17796. face: null,
  17797. object: this
  17798. } );
  17799. }
  17800. copy( source, recursive ) {
  17801. super.copy( source, recursive );
  17802. if ( source.center !== undefined ) this.center.copy( source.center );
  17803. this.material = source.material;
  17804. return this;
  17805. }
  17806. }
  17807. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  17808. // compute position in camera space
  17809. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  17810. // to check if rotation is not zero
  17811. if ( sin !== undefined ) {
  17812. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  17813. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  17814. } else {
  17815. _rotatedPosition.copy( _alignedPosition );
  17816. }
  17817. vertexPosition.copy( mvPosition );
  17818. vertexPosition.x += _rotatedPosition.x;
  17819. vertexPosition.y += _rotatedPosition.y;
  17820. // transform to world space
  17821. vertexPosition.applyMatrix4( _viewWorldMatrix );
  17822. }
  17823. const _v1$2 = /*@__PURE__*/ new Vector3();
  17824. const _v2$1 = /*@__PURE__*/ new Vector3();
  17825. class LOD extends Object3D {
  17826. constructor() {
  17827. super();
  17828. this._currentLevel = 0;
  17829. this.type = 'LOD';
  17830. Object.defineProperties( this, {
  17831. levels: {
  17832. enumerable: true,
  17833. value: []
  17834. },
  17835. isLOD: {
  17836. value: true,
  17837. }
  17838. } );
  17839. this.autoUpdate = true;
  17840. }
  17841. copy( source ) {
  17842. super.copy( source, false );
  17843. const levels = source.levels;
  17844. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  17845. const level = levels[ i ];
  17846. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  17847. }
  17848. this.autoUpdate = source.autoUpdate;
  17849. return this;
  17850. }
  17851. addLevel( object, distance = 0, hysteresis = 0 ) {
  17852. distance = Math.abs( distance );
  17853. const levels = this.levels;
  17854. let l;
  17855. for ( l = 0; l < levels.length; l ++ ) {
  17856. if ( distance < levels[ l ].distance ) {
  17857. break;
  17858. }
  17859. }
  17860. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  17861. this.add( object );
  17862. return this;
  17863. }
  17864. getCurrentLevel() {
  17865. return this._currentLevel;
  17866. }
  17867. getObjectForDistance( distance ) {
  17868. const levels = this.levels;
  17869. if ( levels.length > 0 ) {
  17870. let i, l;
  17871. for ( i = 1, l = levels.length; i < l; i ++ ) {
  17872. let levelDistance = levels[ i ].distance;
  17873. if ( levels[ i ].object.visible ) {
  17874. levelDistance -= levelDistance * levels[ i ].hysteresis;
  17875. }
  17876. if ( distance < levelDistance ) {
  17877. break;
  17878. }
  17879. }
  17880. return levels[ i - 1 ].object;
  17881. }
  17882. return null;
  17883. }
  17884. raycast( raycaster, intersects ) {
  17885. const levels = this.levels;
  17886. if ( levels.length > 0 ) {
  17887. _v1$2.setFromMatrixPosition( this.matrixWorld );
  17888. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  17889. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  17890. }
  17891. }
  17892. update( camera ) {
  17893. const levels = this.levels;
  17894. if ( levels.length > 1 ) {
  17895. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  17896. _v2$1.setFromMatrixPosition( this.matrixWorld );
  17897. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  17898. levels[ 0 ].object.visible = true;
  17899. let i, l;
  17900. for ( i = 1, l = levels.length; i < l; i ++ ) {
  17901. let levelDistance = levels[ i ].distance;
  17902. if ( levels[ i ].object.visible ) {
  17903. levelDistance -= levelDistance * levels[ i ].hysteresis;
  17904. }
  17905. if ( distance >= levelDistance ) {
  17906. levels[ i - 1 ].object.visible = false;
  17907. levels[ i ].object.visible = true;
  17908. } else {
  17909. break;
  17910. }
  17911. }
  17912. this._currentLevel = i - 1;
  17913. for ( ; i < l; i ++ ) {
  17914. levels[ i ].object.visible = false;
  17915. }
  17916. }
  17917. }
  17918. toJSON( meta ) {
  17919. const data = super.toJSON( meta );
  17920. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  17921. data.object.levels = [];
  17922. const levels = this.levels;
  17923. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  17924. const level = levels[ i ];
  17925. data.object.levels.push( {
  17926. object: level.object.uuid,
  17927. distance: level.distance,
  17928. hysteresis: level.hysteresis
  17929. } );
  17930. }
  17931. return data;
  17932. }
  17933. }
  17934. const _basePosition = /*@__PURE__*/ new Vector3();
  17935. const _skinIndex = /*@__PURE__*/ new Vector4();
  17936. const _skinWeight = /*@__PURE__*/ new Vector4();
  17937. const _vector$5 = /*@__PURE__*/ new Vector3();
  17938. const _matrix = /*@__PURE__*/ new Matrix4();
  17939. class SkinnedMesh extends Mesh {
  17940. constructor( geometry, material ) {
  17941. super( geometry, material );
  17942. this.isSkinnedMesh = true;
  17943. this.type = 'SkinnedMesh';
  17944. this.bindMode = 'attached';
  17945. this.bindMatrix = new Matrix4();
  17946. this.bindMatrixInverse = new Matrix4();
  17947. }
  17948. copy( source, recursive ) {
  17949. super.copy( source, recursive );
  17950. this.bindMode = source.bindMode;
  17951. this.bindMatrix.copy( source.bindMatrix );
  17952. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  17953. this.skeleton = source.skeleton;
  17954. return this;
  17955. }
  17956. bind( skeleton, bindMatrix ) {
  17957. this.skeleton = skeleton;
  17958. if ( bindMatrix === undefined ) {
  17959. this.updateMatrixWorld( true );
  17960. this.skeleton.calculateInverses();
  17961. bindMatrix = this.matrixWorld;
  17962. }
  17963. this.bindMatrix.copy( bindMatrix );
  17964. this.bindMatrixInverse.copy( bindMatrix ).invert();
  17965. }
  17966. pose() {
  17967. this.skeleton.pose();
  17968. }
  17969. normalizeSkinWeights() {
  17970. const vector = new Vector4();
  17971. const skinWeight = this.geometry.attributes.skinWeight;
  17972. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  17973. vector.fromBufferAttribute( skinWeight, i );
  17974. const scale = 1.0 / vector.manhattanLength();
  17975. if ( scale !== Infinity ) {
  17976. vector.multiplyScalar( scale );
  17977. } else {
  17978. vector.set( 1, 0, 0, 0 ); // do something reasonable
  17979. }
  17980. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  17981. }
  17982. }
  17983. updateMatrixWorld( force ) {
  17984. super.updateMatrixWorld( force );
  17985. if ( this.bindMode === 'attached' ) {
  17986. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  17987. } else if ( this.bindMode === 'detached' ) {
  17988. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  17989. } else {
  17990. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  17991. }
  17992. }
  17993. boneTransform( index, target ) {
  17994. const skeleton = this.skeleton;
  17995. const geometry = this.geometry;
  17996. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  17997. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  17998. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  17999. target.set( 0, 0, 0 );
  18000. for ( let i = 0; i < 4; i ++ ) {
  18001. const weight = _skinWeight.getComponent( i );
  18002. if ( weight !== 0 ) {
  18003. const boneIndex = _skinIndex.getComponent( i );
  18004. _matrix.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18005. target.addScaledVector( _vector$5.copy( _basePosition ).applyMatrix4( _matrix ), weight );
  18006. }
  18007. }
  18008. return target.applyMatrix4( this.bindMatrixInverse );
  18009. }
  18010. }
  18011. class Bone extends Object3D {
  18012. constructor() {
  18013. super();
  18014. this.isBone = true;
  18015. this.type = 'Bone';
  18016. }
  18017. }
  18018. class DataTexture extends Texture {
  18019. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding ) {
  18020. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  18021. this.isDataTexture = true;
  18022. this.image = { data: data, width: width, height: height };
  18023. this.generateMipmaps = false;
  18024. this.flipY = false;
  18025. this.unpackAlignment = 1;
  18026. }
  18027. }
  18028. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18029. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18030. class Skeleton {
  18031. constructor( bones = [], boneInverses = [] ) {
  18032. this.uuid = generateUUID();
  18033. this.bones = bones.slice( 0 );
  18034. this.boneInverses = boneInverses;
  18035. this.boneMatrices = null;
  18036. this.boneTexture = null;
  18037. this.boneTextureSize = 0;
  18038. this.frame = - 1;
  18039. this.init();
  18040. }
  18041. init() {
  18042. const bones = this.bones;
  18043. const boneInverses = this.boneInverses;
  18044. this.boneMatrices = new Float32Array( bones.length * 16 );
  18045. // calculate inverse bone matrices if necessary
  18046. if ( boneInverses.length === 0 ) {
  18047. this.calculateInverses();
  18048. } else {
  18049. // handle special case
  18050. if ( bones.length !== boneInverses.length ) {
  18051. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18052. this.boneInverses = [];
  18053. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18054. this.boneInverses.push( new Matrix4() );
  18055. }
  18056. }
  18057. }
  18058. }
  18059. calculateInverses() {
  18060. this.boneInverses.length = 0;
  18061. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18062. const inverse = new Matrix4();
  18063. if ( this.bones[ i ] ) {
  18064. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18065. }
  18066. this.boneInverses.push( inverse );
  18067. }
  18068. }
  18069. pose() {
  18070. // recover the bind-time world matrices
  18071. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18072. const bone = this.bones[ i ];
  18073. if ( bone ) {
  18074. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18075. }
  18076. }
  18077. // compute the local matrices, positions, rotations and scales
  18078. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18079. const bone = this.bones[ i ];
  18080. if ( bone ) {
  18081. if ( bone.parent && bone.parent.isBone ) {
  18082. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18083. bone.matrix.multiply( bone.matrixWorld );
  18084. } else {
  18085. bone.matrix.copy( bone.matrixWorld );
  18086. }
  18087. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18088. }
  18089. }
  18090. }
  18091. update() {
  18092. const bones = this.bones;
  18093. const boneInverses = this.boneInverses;
  18094. const boneMatrices = this.boneMatrices;
  18095. const boneTexture = this.boneTexture;
  18096. // flatten bone matrices to array
  18097. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18098. // compute the offset between the current and the original transform
  18099. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18100. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18101. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18102. }
  18103. if ( boneTexture !== null ) {
  18104. boneTexture.needsUpdate = true;
  18105. }
  18106. }
  18107. clone() {
  18108. return new Skeleton( this.bones, this.boneInverses );
  18109. }
  18110. computeBoneTexture() {
  18111. // layout (1 matrix = 4 pixels)
  18112. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18113. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18114. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18115. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18116. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18117. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18118. size = ceilPowerOfTwo( size );
  18119. size = Math.max( size, 4 );
  18120. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18121. boneMatrices.set( this.boneMatrices ); // copy current values
  18122. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18123. boneTexture.needsUpdate = true;
  18124. this.boneMatrices = boneMatrices;
  18125. this.boneTexture = boneTexture;
  18126. this.boneTextureSize = size;
  18127. return this;
  18128. }
  18129. getBoneByName( name ) {
  18130. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18131. const bone = this.bones[ i ];
  18132. if ( bone.name === name ) {
  18133. return bone;
  18134. }
  18135. }
  18136. return undefined;
  18137. }
  18138. dispose( ) {
  18139. if ( this.boneTexture !== null ) {
  18140. this.boneTexture.dispose();
  18141. this.boneTexture = null;
  18142. }
  18143. }
  18144. fromJSON( json, bones ) {
  18145. this.uuid = json.uuid;
  18146. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18147. const uuid = json.bones[ i ];
  18148. let bone = bones[ uuid ];
  18149. if ( bone === undefined ) {
  18150. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  18151. bone = new Bone();
  18152. }
  18153. this.bones.push( bone );
  18154. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18155. }
  18156. this.init();
  18157. return this;
  18158. }
  18159. toJSON() {
  18160. const data = {
  18161. metadata: {
  18162. version: 4.5,
  18163. type: 'Skeleton',
  18164. generator: 'Skeleton.toJSON'
  18165. },
  18166. bones: [],
  18167. boneInverses: []
  18168. };
  18169. data.uuid = this.uuid;
  18170. const bones = this.bones;
  18171. const boneInverses = this.boneInverses;
  18172. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18173. const bone = bones[ i ];
  18174. data.bones.push( bone.uuid );
  18175. const boneInverse = boneInverses[ i ];
  18176. data.boneInverses.push( boneInverse.toArray() );
  18177. }
  18178. return data;
  18179. }
  18180. }
  18181. class InstancedBufferAttribute extends BufferAttribute {
  18182. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18183. super( array, itemSize, normalized );
  18184. this.isInstancedBufferAttribute = true;
  18185. this.meshPerAttribute = meshPerAttribute;
  18186. }
  18187. copy( source ) {
  18188. super.copy( source );
  18189. this.meshPerAttribute = source.meshPerAttribute;
  18190. return this;
  18191. }
  18192. toJSON() {
  18193. const data = super.toJSON();
  18194. data.meshPerAttribute = this.meshPerAttribute;
  18195. data.isInstancedBufferAttribute = true;
  18196. return data;
  18197. }
  18198. }
  18199. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18200. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18201. const _instanceIntersects = [];
  18202. const _identity = /*@__PURE__*/ new Matrix4();
  18203. const _mesh = /*@__PURE__*/ new Mesh();
  18204. class InstancedMesh extends Mesh {
  18205. constructor( geometry, material, count ) {
  18206. super( geometry, material );
  18207. this.isInstancedMesh = true;
  18208. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18209. this.instanceColor = null;
  18210. this.count = count;
  18211. this.frustumCulled = false;
  18212. for ( let i = 0; i < count; i ++ ) {
  18213. this.setMatrixAt( i, _identity );
  18214. }
  18215. }
  18216. copy( source, recursive ) {
  18217. super.copy( source, recursive );
  18218. this.instanceMatrix.copy( source.instanceMatrix );
  18219. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  18220. this.count = source.count;
  18221. return this;
  18222. }
  18223. getColorAt( index, color ) {
  18224. color.fromArray( this.instanceColor.array, index * 3 );
  18225. }
  18226. getMatrixAt( index, matrix ) {
  18227. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  18228. }
  18229. raycast( raycaster, intersects ) {
  18230. const matrixWorld = this.matrixWorld;
  18231. const raycastTimes = this.count;
  18232. _mesh.geometry = this.geometry;
  18233. _mesh.material = this.material;
  18234. if ( _mesh.material === undefined ) return;
  18235. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  18236. // calculate the world matrix for each instance
  18237. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  18238. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  18239. // the mesh represents this single instance
  18240. _mesh.matrixWorld = _instanceWorldMatrix;
  18241. _mesh.raycast( raycaster, _instanceIntersects );
  18242. // process the result of raycast
  18243. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  18244. const intersect = _instanceIntersects[ i ];
  18245. intersect.instanceId = instanceId;
  18246. intersect.object = this;
  18247. intersects.push( intersect );
  18248. }
  18249. _instanceIntersects.length = 0;
  18250. }
  18251. }
  18252. setColorAt( index, color ) {
  18253. if ( this.instanceColor === null ) {
  18254. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  18255. }
  18256. color.toArray( this.instanceColor.array, index * 3 );
  18257. }
  18258. setMatrixAt( index, matrix ) {
  18259. matrix.toArray( this.instanceMatrix.array, index * 16 );
  18260. }
  18261. updateMorphTargets() {
  18262. }
  18263. dispose() {
  18264. this.dispatchEvent( { type: 'dispose' } );
  18265. }
  18266. }
  18267. class LineBasicMaterial extends Material {
  18268. constructor( parameters ) {
  18269. super();
  18270. this.isLineBasicMaterial = true;
  18271. this.type = 'LineBasicMaterial';
  18272. this.color = new Color( 0xffffff );
  18273. this.linewidth = 1;
  18274. this.linecap = 'round';
  18275. this.linejoin = 'round';
  18276. this.fog = true;
  18277. this.setValues( parameters );
  18278. }
  18279. copy( source ) {
  18280. super.copy( source );
  18281. this.color.copy( source.color );
  18282. this.linewidth = source.linewidth;
  18283. this.linecap = source.linecap;
  18284. this.linejoin = source.linejoin;
  18285. this.fog = source.fog;
  18286. return this;
  18287. }
  18288. }
  18289. const _start$1 = /*@__PURE__*/ new Vector3();
  18290. const _end$1 = /*@__PURE__*/ new Vector3();
  18291. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  18292. const _ray$1 = /*@__PURE__*/ new Ray();
  18293. const _sphere$1 = /*@__PURE__*/ new Sphere();
  18294. class Line extends Object3D {
  18295. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  18296. super();
  18297. this.isLine = true;
  18298. this.type = 'Line';
  18299. this.geometry = geometry;
  18300. this.material = material;
  18301. this.updateMorphTargets();
  18302. }
  18303. copy( source, recursive ) {
  18304. super.copy( source, recursive );
  18305. this.material = source.material;
  18306. this.geometry = source.geometry;
  18307. return this;
  18308. }
  18309. computeLineDistances() {
  18310. const geometry = this.geometry;
  18311. // we assume non-indexed geometry
  18312. if ( geometry.index === null ) {
  18313. const positionAttribute = geometry.attributes.position;
  18314. const lineDistances = [ 0 ];
  18315. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  18316. _start$1.fromBufferAttribute( positionAttribute, i - 1 );
  18317. _end$1.fromBufferAttribute( positionAttribute, i );
  18318. lineDistances[ i ] = lineDistances[ i - 1 ];
  18319. lineDistances[ i ] += _start$1.distanceTo( _end$1 );
  18320. }
  18321. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18322. } else {
  18323. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18324. }
  18325. return this;
  18326. }
  18327. raycast( raycaster, intersects ) {
  18328. const geometry = this.geometry;
  18329. const matrixWorld = this.matrixWorld;
  18330. const threshold = raycaster.params.Line.threshold;
  18331. const drawRange = geometry.drawRange;
  18332. // Checking boundingSphere distance to ray
  18333. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18334. _sphere$1.copy( geometry.boundingSphere );
  18335. _sphere$1.applyMatrix4( matrixWorld );
  18336. _sphere$1.radius += threshold;
  18337. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  18338. //
  18339. _inverseMatrix$1.copy( matrixWorld ).invert();
  18340. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  18341. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18342. const localThresholdSq = localThreshold * localThreshold;
  18343. const vStart = new Vector3();
  18344. const vEnd = new Vector3();
  18345. const interSegment = new Vector3();
  18346. const interRay = new Vector3();
  18347. const step = this.isLineSegments ? 2 : 1;
  18348. const index = geometry.index;
  18349. const attributes = geometry.attributes;
  18350. const positionAttribute = attributes.position;
  18351. if ( index !== null ) {
  18352. const start = Math.max( 0, drawRange.start );
  18353. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  18354. for ( let i = start, l = end - 1; i < l; i += step ) {
  18355. const a = index.getX( i );
  18356. const b = index.getX( i + 1 );
  18357. vStart.fromBufferAttribute( positionAttribute, a );
  18358. vEnd.fromBufferAttribute( positionAttribute, b );
  18359. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18360. if ( distSq > localThresholdSq ) continue;
  18361. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18362. const distance = raycaster.ray.origin.distanceTo( interRay );
  18363. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18364. intersects.push( {
  18365. distance: distance,
  18366. // What do we want? intersection point on the ray or on the segment??
  18367. // point: raycaster.ray.at( distance ),
  18368. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18369. index: i,
  18370. face: null,
  18371. faceIndex: null,
  18372. object: this
  18373. } );
  18374. }
  18375. } else {
  18376. const start = Math.max( 0, drawRange.start );
  18377. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  18378. for ( let i = start, l = end - 1; i < l; i += step ) {
  18379. vStart.fromBufferAttribute( positionAttribute, i );
  18380. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  18381. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18382. if ( distSq > localThresholdSq ) continue;
  18383. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18384. const distance = raycaster.ray.origin.distanceTo( interRay );
  18385. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18386. intersects.push( {
  18387. distance: distance,
  18388. // What do we want? intersection point on the ray or on the segment??
  18389. // point: raycaster.ray.at( distance ),
  18390. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18391. index: i,
  18392. face: null,
  18393. faceIndex: null,
  18394. object: this
  18395. } );
  18396. }
  18397. }
  18398. }
  18399. updateMorphTargets() {
  18400. const geometry = this.geometry;
  18401. const morphAttributes = geometry.morphAttributes;
  18402. const keys = Object.keys( morphAttributes );
  18403. if ( keys.length > 0 ) {
  18404. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  18405. if ( morphAttribute !== undefined ) {
  18406. this.morphTargetInfluences = [];
  18407. this.morphTargetDictionary = {};
  18408. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  18409. const name = morphAttribute[ m ].name || String( m );
  18410. this.morphTargetInfluences.push( 0 );
  18411. this.morphTargetDictionary[ name ] = m;
  18412. }
  18413. }
  18414. }
  18415. }
  18416. }
  18417. const _start = /*@__PURE__*/ new Vector3();
  18418. const _end = /*@__PURE__*/ new Vector3();
  18419. class LineSegments extends Line {
  18420. constructor( geometry, material ) {
  18421. super( geometry, material );
  18422. this.isLineSegments = true;
  18423. this.type = 'LineSegments';
  18424. }
  18425. computeLineDistances() {
  18426. const geometry = this.geometry;
  18427. // we assume non-indexed geometry
  18428. if ( geometry.index === null ) {
  18429. const positionAttribute = geometry.attributes.position;
  18430. const lineDistances = [];
  18431. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  18432. _start.fromBufferAttribute( positionAttribute, i );
  18433. _end.fromBufferAttribute( positionAttribute, i + 1 );
  18434. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  18435. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  18436. }
  18437. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18438. } else {
  18439. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18440. }
  18441. return this;
  18442. }
  18443. }
  18444. class LineLoop extends Line {
  18445. constructor( geometry, material ) {
  18446. super( geometry, material );
  18447. this.isLineLoop = true;
  18448. this.type = 'LineLoop';
  18449. }
  18450. }
  18451. class PointsMaterial extends Material {
  18452. constructor( parameters ) {
  18453. super();
  18454. this.isPointsMaterial = true;
  18455. this.type = 'PointsMaterial';
  18456. this.color = new Color( 0xffffff );
  18457. this.map = null;
  18458. this.alphaMap = null;
  18459. this.size = 1;
  18460. this.sizeAttenuation = true;
  18461. this.fog = true;
  18462. this.setValues( parameters );
  18463. }
  18464. copy( source ) {
  18465. super.copy( source );
  18466. this.color.copy( source.color );
  18467. this.map = source.map;
  18468. this.alphaMap = source.alphaMap;
  18469. this.size = source.size;
  18470. this.sizeAttenuation = source.sizeAttenuation;
  18471. this.fog = source.fog;
  18472. return this;
  18473. }
  18474. }
  18475. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  18476. const _ray = /*@__PURE__*/ new Ray();
  18477. const _sphere = /*@__PURE__*/ new Sphere();
  18478. const _position$2 = /*@__PURE__*/ new Vector3();
  18479. class Points extends Object3D {
  18480. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  18481. super();
  18482. this.isPoints = true;
  18483. this.type = 'Points';
  18484. this.geometry = geometry;
  18485. this.material = material;
  18486. this.updateMorphTargets();
  18487. }
  18488. copy( source, recursive ) {
  18489. super.copy( source, recursive );
  18490. this.material = source.material;
  18491. this.geometry = source.geometry;
  18492. return this;
  18493. }
  18494. raycast( raycaster, intersects ) {
  18495. const geometry = this.geometry;
  18496. const matrixWorld = this.matrixWorld;
  18497. const threshold = raycaster.params.Points.threshold;
  18498. const drawRange = geometry.drawRange;
  18499. // Checking boundingSphere distance to ray
  18500. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18501. _sphere.copy( geometry.boundingSphere );
  18502. _sphere.applyMatrix4( matrixWorld );
  18503. _sphere.radius += threshold;
  18504. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  18505. //
  18506. _inverseMatrix.copy( matrixWorld ).invert();
  18507. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  18508. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18509. const localThresholdSq = localThreshold * localThreshold;
  18510. const index = geometry.index;
  18511. const attributes = geometry.attributes;
  18512. const positionAttribute = attributes.position;
  18513. if ( index !== null ) {
  18514. const start = Math.max( 0, drawRange.start );
  18515. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  18516. for ( let i = start, il = end; i < il; i ++ ) {
  18517. const a = index.getX( i );
  18518. _position$2.fromBufferAttribute( positionAttribute, a );
  18519. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  18520. }
  18521. } else {
  18522. const start = Math.max( 0, drawRange.start );
  18523. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  18524. for ( let i = start, l = end; i < l; i ++ ) {
  18525. _position$2.fromBufferAttribute( positionAttribute, i );
  18526. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  18527. }
  18528. }
  18529. }
  18530. updateMorphTargets() {
  18531. const geometry = this.geometry;
  18532. const morphAttributes = geometry.morphAttributes;
  18533. const keys = Object.keys( morphAttributes );
  18534. if ( keys.length > 0 ) {
  18535. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  18536. if ( morphAttribute !== undefined ) {
  18537. this.morphTargetInfluences = [];
  18538. this.morphTargetDictionary = {};
  18539. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  18540. const name = morphAttribute[ m ].name || String( m );
  18541. this.morphTargetInfluences.push( 0 );
  18542. this.morphTargetDictionary[ name ] = m;
  18543. }
  18544. }
  18545. }
  18546. }
  18547. }
  18548. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  18549. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  18550. if ( rayPointDistanceSq < localThresholdSq ) {
  18551. const intersectPoint = new Vector3();
  18552. _ray.closestPointToPoint( point, intersectPoint );
  18553. intersectPoint.applyMatrix4( matrixWorld );
  18554. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  18555. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18556. intersects.push( {
  18557. distance: distance,
  18558. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  18559. point: intersectPoint,
  18560. index: index,
  18561. face: null,
  18562. object: object
  18563. } );
  18564. }
  18565. }
  18566. class VideoTexture extends Texture {
  18567. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18568. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18569. this.isVideoTexture = true;
  18570. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  18571. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  18572. this.generateMipmaps = false;
  18573. const scope = this;
  18574. function updateVideo() {
  18575. scope.needsUpdate = true;
  18576. video.requestVideoFrameCallback( updateVideo );
  18577. }
  18578. if ( 'requestVideoFrameCallback' in video ) {
  18579. video.requestVideoFrameCallback( updateVideo );
  18580. }
  18581. }
  18582. clone() {
  18583. return new this.constructor( this.image ).copy( this );
  18584. }
  18585. update() {
  18586. const video = this.image;
  18587. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  18588. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  18589. this.needsUpdate = true;
  18590. }
  18591. }
  18592. }
  18593. class FramebufferTexture extends Texture {
  18594. constructor( width, height, format ) {
  18595. super( { width, height } );
  18596. this.isFramebufferTexture = true;
  18597. this.format = format;
  18598. this.magFilter = NearestFilter;
  18599. this.minFilter = NearestFilter;
  18600. this.generateMipmaps = false;
  18601. this.needsUpdate = true;
  18602. }
  18603. }
  18604. class CompressedTexture extends Texture {
  18605. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  18606. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  18607. this.isCompressedTexture = true;
  18608. this.image = { width: width, height: height };
  18609. this.mipmaps = mipmaps;
  18610. // no flipping for cube textures
  18611. // (also flipping doesn't work for compressed textures )
  18612. this.flipY = false;
  18613. // can't generate mipmaps for compressed textures
  18614. // mips must be embedded in DDS files
  18615. this.generateMipmaps = false;
  18616. }
  18617. }
  18618. class CompressedArrayTexture extends CompressedTexture {
  18619. constructor( mipmaps, width, height, depth, format, type ) {
  18620. super( mipmaps, width, height, format, type );
  18621. this.isCompressedArrayTexture = true;
  18622. this.image.depth = depth;
  18623. this.wrapR = ClampToEdgeWrapping;
  18624. }
  18625. }
  18626. class CanvasTexture extends Texture {
  18627. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18628. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18629. this.isCanvasTexture = true;
  18630. this.needsUpdate = true;
  18631. }
  18632. }
  18633. /**
  18634. * Extensible curve object.
  18635. *
  18636. * Some common of curve methods:
  18637. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  18638. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  18639. * .getPoints(), .getSpacedPoints()
  18640. * .getLength()
  18641. * .updateArcLengths()
  18642. *
  18643. * This following curves inherit from THREE.Curve:
  18644. *
  18645. * -- 2D curves --
  18646. * THREE.ArcCurve
  18647. * THREE.CubicBezierCurve
  18648. * THREE.EllipseCurve
  18649. * THREE.LineCurve
  18650. * THREE.QuadraticBezierCurve
  18651. * THREE.SplineCurve
  18652. *
  18653. * -- 3D curves --
  18654. * THREE.CatmullRomCurve3
  18655. * THREE.CubicBezierCurve3
  18656. * THREE.LineCurve3
  18657. * THREE.QuadraticBezierCurve3
  18658. *
  18659. * A series of curves can be represented as a THREE.CurvePath.
  18660. *
  18661. **/
  18662. class Curve {
  18663. constructor() {
  18664. this.type = 'Curve';
  18665. this.arcLengthDivisions = 200;
  18666. }
  18667. // Virtual base class method to overwrite and implement in subclasses
  18668. // - t [0 .. 1]
  18669. getPoint( /* t, optionalTarget */ ) {
  18670. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  18671. return null;
  18672. }
  18673. // Get point at relative position in curve according to arc length
  18674. // - u [0 .. 1]
  18675. getPointAt( u, optionalTarget ) {
  18676. const t = this.getUtoTmapping( u );
  18677. return this.getPoint( t, optionalTarget );
  18678. }
  18679. // Get sequence of points using getPoint( t )
  18680. getPoints( divisions = 5 ) {
  18681. const points = [];
  18682. for ( let d = 0; d <= divisions; d ++ ) {
  18683. points.push( this.getPoint( d / divisions ) );
  18684. }
  18685. return points;
  18686. }
  18687. // Get sequence of points using getPointAt( u )
  18688. getSpacedPoints( divisions = 5 ) {
  18689. const points = [];
  18690. for ( let d = 0; d <= divisions; d ++ ) {
  18691. points.push( this.getPointAt( d / divisions ) );
  18692. }
  18693. return points;
  18694. }
  18695. // Get total curve arc length
  18696. getLength() {
  18697. const lengths = this.getLengths();
  18698. return lengths[ lengths.length - 1 ];
  18699. }
  18700. // Get list of cumulative segment lengths
  18701. getLengths( divisions = this.arcLengthDivisions ) {
  18702. if ( this.cacheArcLengths &&
  18703. ( this.cacheArcLengths.length === divisions + 1 ) &&
  18704. ! this.needsUpdate ) {
  18705. return this.cacheArcLengths;
  18706. }
  18707. this.needsUpdate = false;
  18708. const cache = [];
  18709. let current, last = this.getPoint( 0 );
  18710. let sum = 0;
  18711. cache.push( 0 );
  18712. for ( let p = 1; p <= divisions; p ++ ) {
  18713. current = this.getPoint( p / divisions );
  18714. sum += current.distanceTo( last );
  18715. cache.push( sum );
  18716. last = current;
  18717. }
  18718. this.cacheArcLengths = cache;
  18719. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  18720. }
  18721. updateArcLengths() {
  18722. this.needsUpdate = true;
  18723. this.getLengths();
  18724. }
  18725. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  18726. getUtoTmapping( u, distance ) {
  18727. const arcLengths = this.getLengths();
  18728. let i = 0;
  18729. const il = arcLengths.length;
  18730. let targetArcLength; // The targeted u distance value to get
  18731. if ( distance ) {
  18732. targetArcLength = distance;
  18733. } else {
  18734. targetArcLength = u * arcLengths[ il - 1 ];
  18735. }
  18736. // binary search for the index with largest value smaller than target u distance
  18737. let low = 0, high = il - 1, comparison;
  18738. while ( low <= high ) {
  18739. 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
  18740. comparison = arcLengths[ i ] - targetArcLength;
  18741. if ( comparison < 0 ) {
  18742. low = i + 1;
  18743. } else if ( comparison > 0 ) {
  18744. high = i - 1;
  18745. } else {
  18746. high = i;
  18747. break;
  18748. // DONE
  18749. }
  18750. }
  18751. i = high;
  18752. if ( arcLengths[ i ] === targetArcLength ) {
  18753. return i / ( il - 1 );
  18754. }
  18755. // we could get finer grain at lengths, or use simple interpolation between two points
  18756. const lengthBefore = arcLengths[ i ];
  18757. const lengthAfter = arcLengths[ i + 1 ];
  18758. const segmentLength = lengthAfter - lengthBefore;
  18759. // determine where we are between the 'before' and 'after' points
  18760. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  18761. // add that fractional amount to t
  18762. const t = ( i + segmentFraction ) / ( il - 1 );
  18763. return t;
  18764. }
  18765. // Returns a unit vector tangent at t
  18766. // In case any sub curve does not implement its tangent derivation,
  18767. // 2 points a small delta apart will be used to find its gradient
  18768. // which seems to give a reasonable approximation
  18769. getTangent( t, optionalTarget ) {
  18770. const delta = 0.0001;
  18771. let t1 = t - delta;
  18772. let t2 = t + delta;
  18773. // Capping in case of danger
  18774. if ( t1 < 0 ) t1 = 0;
  18775. if ( t2 > 1 ) t2 = 1;
  18776. const pt1 = this.getPoint( t1 );
  18777. const pt2 = this.getPoint( t2 );
  18778. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  18779. tangent.copy( pt2 ).sub( pt1 ).normalize();
  18780. return tangent;
  18781. }
  18782. getTangentAt( u, optionalTarget ) {
  18783. const t = this.getUtoTmapping( u );
  18784. return this.getTangent( t, optionalTarget );
  18785. }
  18786. computeFrenetFrames( segments, closed ) {
  18787. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18788. const normal = new Vector3();
  18789. const tangents = [];
  18790. const normals = [];
  18791. const binormals = [];
  18792. const vec = new Vector3();
  18793. const mat = new Matrix4();
  18794. // compute the tangent vectors for each segment on the curve
  18795. for ( let i = 0; i <= segments; i ++ ) {
  18796. const u = i / segments;
  18797. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  18798. }
  18799. // select an initial normal vector perpendicular to the first tangent vector,
  18800. // and in the direction of the minimum tangent xyz component
  18801. normals[ 0 ] = new Vector3();
  18802. binormals[ 0 ] = new Vector3();
  18803. let min = Number.MAX_VALUE;
  18804. const tx = Math.abs( tangents[ 0 ].x );
  18805. const ty = Math.abs( tangents[ 0 ].y );
  18806. const tz = Math.abs( tangents[ 0 ].z );
  18807. if ( tx <= min ) {
  18808. min = tx;
  18809. normal.set( 1, 0, 0 );
  18810. }
  18811. if ( ty <= min ) {
  18812. min = ty;
  18813. normal.set( 0, 1, 0 );
  18814. }
  18815. if ( tz <= min ) {
  18816. normal.set( 0, 0, 1 );
  18817. }
  18818. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  18819. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  18820. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  18821. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  18822. for ( let i = 1; i <= segments; i ++ ) {
  18823. normals[ i ] = normals[ i - 1 ].clone();
  18824. binormals[ i ] = binormals[ i - 1 ].clone();
  18825. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  18826. if ( vec.length() > Number.EPSILON ) {
  18827. vec.normalize();
  18828. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  18829. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  18830. }
  18831. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18832. }
  18833. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18834. if ( closed === true ) {
  18835. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  18836. theta /= segments;
  18837. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  18838. theta = - theta;
  18839. }
  18840. for ( let i = 1; i <= segments; i ++ ) {
  18841. // twist a little...
  18842. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  18843. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18844. }
  18845. }
  18846. return {
  18847. tangents: tangents,
  18848. normals: normals,
  18849. binormals: binormals
  18850. };
  18851. }
  18852. clone() {
  18853. return new this.constructor().copy( this );
  18854. }
  18855. copy( source ) {
  18856. this.arcLengthDivisions = source.arcLengthDivisions;
  18857. return this;
  18858. }
  18859. toJSON() {
  18860. const data = {
  18861. metadata: {
  18862. version: 4.5,
  18863. type: 'Curve',
  18864. generator: 'Curve.toJSON'
  18865. }
  18866. };
  18867. data.arcLengthDivisions = this.arcLengthDivisions;
  18868. data.type = this.type;
  18869. return data;
  18870. }
  18871. fromJSON( json ) {
  18872. this.arcLengthDivisions = json.arcLengthDivisions;
  18873. return this;
  18874. }
  18875. }
  18876. class EllipseCurve extends Curve {
  18877. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  18878. super();
  18879. this.isEllipseCurve = true;
  18880. this.type = 'EllipseCurve';
  18881. this.aX = aX;
  18882. this.aY = aY;
  18883. this.xRadius = xRadius;
  18884. this.yRadius = yRadius;
  18885. this.aStartAngle = aStartAngle;
  18886. this.aEndAngle = aEndAngle;
  18887. this.aClockwise = aClockwise;
  18888. this.aRotation = aRotation;
  18889. }
  18890. getPoint( t, optionalTarget ) {
  18891. const point = optionalTarget || new Vector2();
  18892. const twoPi = Math.PI * 2;
  18893. let deltaAngle = this.aEndAngle - this.aStartAngle;
  18894. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  18895. // ensures that deltaAngle is 0 .. 2 PI
  18896. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  18897. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  18898. if ( deltaAngle < Number.EPSILON ) {
  18899. if ( samePoints ) {
  18900. deltaAngle = 0;
  18901. } else {
  18902. deltaAngle = twoPi;
  18903. }
  18904. }
  18905. if ( this.aClockwise === true && ! samePoints ) {
  18906. if ( deltaAngle === twoPi ) {
  18907. deltaAngle = - twoPi;
  18908. } else {
  18909. deltaAngle = deltaAngle - twoPi;
  18910. }
  18911. }
  18912. const angle = this.aStartAngle + t * deltaAngle;
  18913. let x = this.aX + this.xRadius * Math.cos( angle );
  18914. let y = this.aY + this.yRadius * Math.sin( angle );
  18915. if ( this.aRotation !== 0 ) {
  18916. const cos = Math.cos( this.aRotation );
  18917. const sin = Math.sin( this.aRotation );
  18918. const tx = x - this.aX;
  18919. const ty = y - this.aY;
  18920. // Rotate the point about the center of the ellipse.
  18921. x = tx * cos - ty * sin + this.aX;
  18922. y = tx * sin + ty * cos + this.aY;
  18923. }
  18924. return point.set( x, y );
  18925. }
  18926. copy( source ) {
  18927. super.copy( source );
  18928. this.aX = source.aX;
  18929. this.aY = source.aY;
  18930. this.xRadius = source.xRadius;
  18931. this.yRadius = source.yRadius;
  18932. this.aStartAngle = source.aStartAngle;
  18933. this.aEndAngle = source.aEndAngle;
  18934. this.aClockwise = source.aClockwise;
  18935. this.aRotation = source.aRotation;
  18936. return this;
  18937. }
  18938. toJSON() {
  18939. const data = super.toJSON();
  18940. data.aX = this.aX;
  18941. data.aY = this.aY;
  18942. data.xRadius = this.xRadius;
  18943. data.yRadius = this.yRadius;
  18944. data.aStartAngle = this.aStartAngle;
  18945. data.aEndAngle = this.aEndAngle;
  18946. data.aClockwise = this.aClockwise;
  18947. data.aRotation = this.aRotation;
  18948. return data;
  18949. }
  18950. fromJSON( json ) {
  18951. super.fromJSON( json );
  18952. this.aX = json.aX;
  18953. this.aY = json.aY;
  18954. this.xRadius = json.xRadius;
  18955. this.yRadius = json.yRadius;
  18956. this.aStartAngle = json.aStartAngle;
  18957. this.aEndAngle = json.aEndAngle;
  18958. this.aClockwise = json.aClockwise;
  18959. this.aRotation = json.aRotation;
  18960. return this;
  18961. }
  18962. }
  18963. class ArcCurve extends EllipseCurve {
  18964. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18965. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18966. this.isArcCurve = true;
  18967. this.type = 'ArcCurve';
  18968. }
  18969. }
  18970. /**
  18971. * Centripetal CatmullRom Curve - which is useful for avoiding
  18972. * cusps and self-intersections in non-uniform catmull rom curves.
  18973. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  18974. *
  18975. * curve.type accepts centripetal(default), chordal and catmullrom
  18976. * curve.tension is used for catmullrom which defaults to 0.5
  18977. */
  18978. /*
  18979. Based on an optimized c++ solution in
  18980. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  18981. - http://ideone.com/NoEbVM
  18982. This CubicPoly class could be used for reusing some variables and calculations,
  18983. but for three.js curve use, it could be possible inlined and flatten into a single function call
  18984. which can be placed in CurveUtils.
  18985. */
  18986. function CubicPoly() {
  18987. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  18988. /*
  18989. * Compute coefficients for a cubic polynomial
  18990. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  18991. * such that
  18992. * p(0) = x0, p(1) = x1
  18993. * and
  18994. * p'(0) = t0, p'(1) = t1.
  18995. */
  18996. function init( x0, x1, t0, t1 ) {
  18997. c0 = x0;
  18998. c1 = t0;
  18999. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  19000. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  19001. }
  19002. return {
  19003. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  19004. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  19005. },
  19006. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  19007. // compute tangents when parameterized in [t1,t2]
  19008. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  19009. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  19010. // rescale tangents for parametrization in [0,1]
  19011. t1 *= dt1;
  19012. t2 *= dt1;
  19013. init( x1, x2, t1, t2 );
  19014. },
  19015. calc: function ( t ) {
  19016. const t2 = t * t;
  19017. const t3 = t2 * t;
  19018. return c0 + c1 * t + c2 * t2 + c3 * t3;
  19019. }
  19020. };
  19021. }
  19022. //
  19023. const tmp = /*@__PURE__*/ new Vector3();
  19024. const px = /*@__PURE__*/ new CubicPoly();
  19025. const py = /*@__PURE__*/ new CubicPoly();
  19026. const pz = /*@__PURE__*/ new CubicPoly();
  19027. class CatmullRomCurve3 extends Curve {
  19028. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  19029. super();
  19030. this.isCatmullRomCurve3 = true;
  19031. this.type = 'CatmullRomCurve3';
  19032. this.points = points;
  19033. this.closed = closed;
  19034. this.curveType = curveType;
  19035. this.tension = tension;
  19036. }
  19037. getPoint( t, optionalTarget = new Vector3() ) {
  19038. const point = optionalTarget;
  19039. const points = this.points;
  19040. const l = points.length;
  19041. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  19042. let intPoint = Math.floor( p );
  19043. let weight = p - intPoint;
  19044. if ( this.closed ) {
  19045. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  19046. } else if ( weight === 0 && intPoint === l - 1 ) {
  19047. intPoint = l - 2;
  19048. weight = 1;
  19049. }
  19050. let p0, p3; // 4 points (p1 & p2 defined below)
  19051. if ( this.closed || intPoint > 0 ) {
  19052. p0 = points[ ( intPoint - 1 ) % l ];
  19053. } else {
  19054. // extrapolate first point
  19055. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  19056. p0 = tmp;
  19057. }
  19058. const p1 = points[ intPoint % l ];
  19059. const p2 = points[ ( intPoint + 1 ) % l ];
  19060. if ( this.closed || intPoint + 2 < l ) {
  19061. p3 = points[ ( intPoint + 2 ) % l ];
  19062. } else {
  19063. // extrapolate last point
  19064. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  19065. p3 = tmp;
  19066. }
  19067. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  19068. // init Centripetal / Chordal Catmull-Rom
  19069. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  19070. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  19071. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  19072. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  19073. // safety check for repeated points
  19074. if ( dt1 < 1e-4 ) dt1 = 1.0;
  19075. if ( dt0 < 1e-4 ) dt0 = dt1;
  19076. if ( dt2 < 1e-4 ) dt2 = dt1;
  19077. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  19078. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  19079. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  19080. } else if ( this.curveType === 'catmullrom' ) {
  19081. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  19082. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  19083. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  19084. }
  19085. point.set(
  19086. px.calc( weight ),
  19087. py.calc( weight ),
  19088. pz.calc( weight )
  19089. );
  19090. return point;
  19091. }
  19092. copy( source ) {
  19093. super.copy( source );
  19094. this.points = [];
  19095. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19096. const point = source.points[ i ];
  19097. this.points.push( point.clone() );
  19098. }
  19099. this.closed = source.closed;
  19100. this.curveType = source.curveType;
  19101. this.tension = source.tension;
  19102. return this;
  19103. }
  19104. toJSON() {
  19105. const data = super.toJSON();
  19106. data.points = [];
  19107. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19108. const point = this.points[ i ];
  19109. data.points.push( point.toArray() );
  19110. }
  19111. data.closed = this.closed;
  19112. data.curveType = this.curveType;
  19113. data.tension = this.tension;
  19114. return data;
  19115. }
  19116. fromJSON( json ) {
  19117. super.fromJSON( json );
  19118. this.points = [];
  19119. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19120. const point = json.points[ i ];
  19121. this.points.push( new Vector3().fromArray( point ) );
  19122. }
  19123. this.closed = json.closed;
  19124. this.curveType = json.curveType;
  19125. this.tension = json.tension;
  19126. return this;
  19127. }
  19128. }
  19129. /**
  19130. * Bezier Curves formulas obtained from
  19131. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  19132. */
  19133. function CatmullRom( t, p0, p1, p2, p3 ) {
  19134. const v0 = ( p2 - p0 ) * 0.5;
  19135. const v1 = ( p3 - p1 ) * 0.5;
  19136. const t2 = t * t;
  19137. const t3 = t * t2;
  19138. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  19139. }
  19140. //
  19141. function QuadraticBezierP0( t, p ) {
  19142. const k = 1 - t;
  19143. return k * k * p;
  19144. }
  19145. function QuadraticBezierP1( t, p ) {
  19146. return 2 * ( 1 - t ) * t * p;
  19147. }
  19148. function QuadraticBezierP2( t, p ) {
  19149. return t * t * p;
  19150. }
  19151. function QuadraticBezier( t, p0, p1, p2 ) {
  19152. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  19153. QuadraticBezierP2( t, p2 );
  19154. }
  19155. //
  19156. function CubicBezierP0( t, p ) {
  19157. const k = 1 - t;
  19158. return k * k * k * p;
  19159. }
  19160. function CubicBezierP1( t, p ) {
  19161. const k = 1 - t;
  19162. return 3 * k * k * t * p;
  19163. }
  19164. function CubicBezierP2( t, p ) {
  19165. return 3 * ( 1 - t ) * t * t * p;
  19166. }
  19167. function CubicBezierP3( t, p ) {
  19168. return t * t * t * p;
  19169. }
  19170. function CubicBezier( t, p0, p1, p2, p3 ) {
  19171. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  19172. CubicBezierP3( t, p3 );
  19173. }
  19174. class CubicBezierCurve extends Curve {
  19175. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  19176. super();
  19177. this.isCubicBezierCurve = true;
  19178. this.type = 'CubicBezierCurve';
  19179. this.v0 = v0;
  19180. this.v1 = v1;
  19181. this.v2 = v2;
  19182. this.v3 = v3;
  19183. }
  19184. getPoint( t, optionalTarget = new Vector2() ) {
  19185. const point = optionalTarget;
  19186. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19187. point.set(
  19188. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19189. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  19190. );
  19191. return point;
  19192. }
  19193. copy( source ) {
  19194. super.copy( source );
  19195. this.v0.copy( source.v0 );
  19196. this.v1.copy( source.v1 );
  19197. this.v2.copy( source.v2 );
  19198. this.v3.copy( source.v3 );
  19199. return this;
  19200. }
  19201. toJSON() {
  19202. const data = super.toJSON();
  19203. data.v0 = this.v0.toArray();
  19204. data.v1 = this.v1.toArray();
  19205. data.v2 = this.v2.toArray();
  19206. data.v3 = this.v3.toArray();
  19207. return data;
  19208. }
  19209. fromJSON( json ) {
  19210. super.fromJSON( json );
  19211. this.v0.fromArray( json.v0 );
  19212. this.v1.fromArray( json.v1 );
  19213. this.v2.fromArray( json.v2 );
  19214. this.v3.fromArray( json.v3 );
  19215. return this;
  19216. }
  19217. }
  19218. class CubicBezierCurve3 extends Curve {
  19219. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  19220. super();
  19221. this.isCubicBezierCurve3 = true;
  19222. this.type = 'CubicBezierCurve3';
  19223. this.v0 = v0;
  19224. this.v1 = v1;
  19225. this.v2 = v2;
  19226. this.v3 = v3;
  19227. }
  19228. getPoint( t, optionalTarget = new Vector3() ) {
  19229. const point = optionalTarget;
  19230. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19231. point.set(
  19232. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19233. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  19234. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  19235. );
  19236. return point;
  19237. }
  19238. copy( source ) {
  19239. super.copy( source );
  19240. this.v0.copy( source.v0 );
  19241. this.v1.copy( source.v1 );
  19242. this.v2.copy( source.v2 );
  19243. this.v3.copy( source.v3 );
  19244. return this;
  19245. }
  19246. toJSON() {
  19247. const data = super.toJSON();
  19248. data.v0 = this.v0.toArray();
  19249. data.v1 = this.v1.toArray();
  19250. data.v2 = this.v2.toArray();
  19251. data.v3 = this.v3.toArray();
  19252. return data;
  19253. }
  19254. fromJSON( json ) {
  19255. super.fromJSON( json );
  19256. this.v0.fromArray( json.v0 );
  19257. this.v1.fromArray( json.v1 );
  19258. this.v2.fromArray( json.v2 );
  19259. this.v3.fromArray( json.v3 );
  19260. return this;
  19261. }
  19262. }
  19263. class LineCurve extends Curve {
  19264. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  19265. super();
  19266. this.isLineCurve = true;
  19267. this.type = 'LineCurve';
  19268. this.v1 = v1;
  19269. this.v2 = v2;
  19270. }
  19271. getPoint( t, optionalTarget = new Vector2() ) {
  19272. const point = optionalTarget;
  19273. if ( t === 1 ) {
  19274. point.copy( this.v2 );
  19275. } else {
  19276. point.copy( this.v2 ).sub( this.v1 );
  19277. point.multiplyScalar( t ).add( this.v1 );
  19278. }
  19279. return point;
  19280. }
  19281. // Line curve is linear, so we can overwrite default getPointAt
  19282. getPointAt( u, optionalTarget ) {
  19283. return this.getPoint( u, optionalTarget );
  19284. }
  19285. getTangent( t, optionalTarget ) {
  19286. const tangent = optionalTarget || new Vector2();
  19287. tangent.copy( this.v2 ).sub( this.v1 ).normalize();
  19288. return tangent;
  19289. }
  19290. copy( source ) {
  19291. super.copy( source );
  19292. this.v1.copy( source.v1 );
  19293. this.v2.copy( source.v2 );
  19294. return this;
  19295. }
  19296. toJSON() {
  19297. const data = super.toJSON();
  19298. data.v1 = this.v1.toArray();
  19299. data.v2 = this.v2.toArray();
  19300. return data;
  19301. }
  19302. fromJSON( json ) {
  19303. super.fromJSON( json );
  19304. this.v1.fromArray( json.v1 );
  19305. this.v2.fromArray( json.v2 );
  19306. return this;
  19307. }
  19308. }
  19309. class LineCurve3 extends Curve {
  19310. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  19311. super();
  19312. this.isLineCurve3 = true;
  19313. this.type = 'LineCurve3';
  19314. this.v1 = v1;
  19315. this.v2 = v2;
  19316. }
  19317. getPoint( t, optionalTarget = new Vector3() ) {
  19318. const point = optionalTarget;
  19319. if ( t === 1 ) {
  19320. point.copy( this.v2 );
  19321. } else {
  19322. point.copy( this.v2 ).sub( this.v1 );
  19323. point.multiplyScalar( t ).add( this.v1 );
  19324. }
  19325. return point;
  19326. }
  19327. // Line curve is linear, so we can overwrite default getPointAt
  19328. getPointAt( u, optionalTarget ) {
  19329. return this.getPoint( u, optionalTarget );
  19330. }
  19331. copy( source ) {
  19332. super.copy( source );
  19333. this.v1.copy( source.v1 );
  19334. this.v2.copy( source.v2 );
  19335. return this;
  19336. }
  19337. toJSON() {
  19338. const data = super.toJSON();
  19339. data.v1 = this.v1.toArray();
  19340. data.v2 = this.v2.toArray();
  19341. return data;
  19342. }
  19343. fromJSON( json ) {
  19344. super.fromJSON( json );
  19345. this.v1.fromArray( json.v1 );
  19346. this.v2.fromArray( json.v2 );
  19347. return this;
  19348. }
  19349. }
  19350. class QuadraticBezierCurve extends Curve {
  19351. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  19352. super();
  19353. this.isQuadraticBezierCurve = true;
  19354. this.type = 'QuadraticBezierCurve';
  19355. this.v0 = v0;
  19356. this.v1 = v1;
  19357. this.v2 = v2;
  19358. }
  19359. getPoint( t, optionalTarget = new Vector2() ) {
  19360. const point = optionalTarget;
  19361. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19362. point.set(
  19363. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19364. QuadraticBezier( t, v0.y, v1.y, v2.y )
  19365. );
  19366. return point;
  19367. }
  19368. copy( source ) {
  19369. super.copy( source );
  19370. this.v0.copy( source.v0 );
  19371. this.v1.copy( source.v1 );
  19372. this.v2.copy( source.v2 );
  19373. return this;
  19374. }
  19375. toJSON() {
  19376. const data = super.toJSON();
  19377. data.v0 = this.v0.toArray();
  19378. data.v1 = this.v1.toArray();
  19379. data.v2 = this.v2.toArray();
  19380. return data;
  19381. }
  19382. fromJSON( json ) {
  19383. super.fromJSON( json );
  19384. this.v0.fromArray( json.v0 );
  19385. this.v1.fromArray( json.v1 );
  19386. this.v2.fromArray( json.v2 );
  19387. return this;
  19388. }
  19389. }
  19390. class QuadraticBezierCurve3 extends Curve {
  19391. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  19392. super();
  19393. this.isQuadraticBezierCurve3 = true;
  19394. this.type = 'QuadraticBezierCurve3';
  19395. this.v0 = v0;
  19396. this.v1 = v1;
  19397. this.v2 = v2;
  19398. }
  19399. getPoint( t, optionalTarget = new Vector3() ) {
  19400. const point = optionalTarget;
  19401. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19402. point.set(
  19403. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19404. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  19405. QuadraticBezier( t, v0.z, v1.z, v2.z )
  19406. );
  19407. return point;
  19408. }
  19409. copy( source ) {
  19410. super.copy( source );
  19411. this.v0.copy( source.v0 );
  19412. this.v1.copy( source.v1 );
  19413. this.v2.copy( source.v2 );
  19414. return this;
  19415. }
  19416. toJSON() {
  19417. const data = super.toJSON();
  19418. data.v0 = this.v0.toArray();
  19419. data.v1 = this.v1.toArray();
  19420. data.v2 = this.v2.toArray();
  19421. return data;
  19422. }
  19423. fromJSON( json ) {
  19424. super.fromJSON( json );
  19425. this.v0.fromArray( json.v0 );
  19426. this.v1.fromArray( json.v1 );
  19427. this.v2.fromArray( json.v2 );
  19428. return this;
  19429. }
  19430. }
  19431. class SplineCurve extends Curve {
  19432. constructor( points = [] ) {
  19433. super();
  19434. this.isSplineCurve = true;
  19435. this.type = 'SplineCurve';
  19436. this.points = points;
  19437. }
  19438. getPoint( t, optionalTarget = new Vector2() ) {
  19439. const point = optionalTarget;
  19440. const points = this.points;
  19441. const p = ( points.length - 1 ) * t;
  19442. const intPoint = Math.floor( p );
  19443. const weight = p - intPoint;
  19444. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  19445. const p1 = points[ intPoint ];
  19446. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  19447. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  19448. point.set(
  19449. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  19450. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  19451. );
  19452. return point;
  19453. }
  19454. copy( source ) {
  19455. super.copy( source );
  19456. this.points = [];
  19457. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19458. const point = source.points[ i ];
  19459. this.points.push( point.clone() );
  19460. }
  19461. return this;
  19462. }
  19463. toJSON() {
  19464. const data = super.toJSON();
  19465. data.points = [];
  19466. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19467. const point = this.points[ i ];
  19468. data.points.push( point.toArray() );
  19469. }
  19470. return data;
  19471. }
  19472. fromJSON( json ) {
  19473. super.fromJSON( json );
  19474. this.points = [];
  19475. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19476. const point = json.points[ i ];
  19477. this.points.push( new Vector2().fromArray( point ) );
  19478. }
  19479. return this;
  19480. }
  19481. }
  19482. var Curves = /*#__PURE__*/Object.freeze({
  19483. __proto__: null,
  19484. ArcCurve: ArcCurve,
  19485. CatmullRomCurve3: CatmullRomCurve3,
  19486. CubicBezierCurve: CubicBezierCurve,
  19487. CubicBezierCurve3: CubicBezierCurve3,
  19488. EllipseCurve: EllipseCurve,
  19489. LineCurve: LineCurve,
  19490. LineCurve3: LineCurve3,
  19491. QuadraticBezierCurve: QuadraticBezierCurve,
  19492. QuadraticBezierCurve3: QuadraticBezierCurve3,
  19493. SplineCurve: SplineCurve
  19494. });
  19495. /**************************************************************
  19496. * Curved Path - a curve path is simply a array of connected
  19497. * curves, but retains the api of a curve
  19498. **************************************************************/
  19499. class CurvePath extends Curve {
  19500. constructor() {
  19501. super();
  19502. this.type = 'CurvePath';
  19503. this.curves = [];
  19504. this.autoClose = false; // Automatically closes the path
  19505. }
  19506. add( curve ) {
  19507. this.curves.push( curve );
  19508. }
  19509. closePath() {
  19510. // Add a line curve if start and end of lines are not connected
  19511. const startPoint = this.curves[ 0 ].getPoint( 0 );
  19512. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  19513. if ( ! startPoint.equals( endPoint ) ) {
  19514. this.curves.push( new LineCurve( endPoint, startPoint ) );
  19515. }
  19516. }
  19517. // To get accurate point with reference to
  19518. // entire path distance at time t,
  19519. // following has to be done:
  19520. // 1. Length of each sub path have to be known
  19521. // 2. Locate and identify type of curve
  19522. // 3. Get t for the curve
  19523. // 4. Return curve.getPointAt(t')
  19524. getPoint( t, optionalTarget ) {
  19525. const d = t * this.getLength();
  19526. const curveLengths = this.getCurveLengths();
  19527. let i = 0;
  19528. // To think about boundaries points.
  19529. while ( i < curveLengths.length ) {
  19530. if ( curveLengths[ i ] >= d ) {
  19531. const diff = curveLengths[ i ] - d;
  19532. const curve = this.curves[ i ];
  19533. const segmentLength = curve.getLength();
  19534. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  19535. return curve.getPointAt( u, optionalTarget );
  19536. }
  19537. i ++;
  19538. }
  19539. return null;
  19540. // loop where sum != 0, sum > d , sum+1 <d
  19541. }
  19542. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  19543. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  19544. // getPoint() depends on getLength
  19545. getLength() {
  19546. const lens = this.getCurveLengths();
  19547. return lens[ lens.length - 1 ];
  19548. }
  19549. // cacheLengths must be recalculated.
  19550. updateArcLengths() {
  19551. this.needsUpdate = true;
  19552. this.cacheLengths = null;
  19553. this.getCurveLengths();
  19554. }
  19555. // Compute lengths and cache them
  19556. // We cannot overwrite getLengths() because UtoT mapping uses it.
  19557. getCurveLengths() {
  19558. // We use cache values if curves and cache array are same length
  19559. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  19560. return this.cacheLengths;
  19561. }
  19562. // Get length of sub-curve
  19563. // Push sums into cached array
  19564. const lengths = [];
  19565. let sums = 0;
  19566. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19567. sums += this.curves[ i ].getLength();
  19568. lengths.push( sums );
  19569. }
  19570. this.cacheLengths = lengths;
  19571. return lengths;
  19572. }
  19573. getSpacedPoints( divisions = 40 ) {
  19574. const points = [];
  19575. for ( let i = 0; i <= divisions; i ++ ) {
  19576. points.push( this.getPoint( i / divisions ) );
  19577. }
  19578. if ( this.autoClose ) {
  19579. points.push( points[ 0 ] );
  19580. }
  19581. return points;
  19582. }
  19583. getPoints( divisions = 12 ) {
  19584. const points = [];
  19585. let last;
  19586. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  19587. const curve = curves[ i ];
  19588. const resolution = curve.isEllipseCurve ? divisions * 2
  19589. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  19590. : curve.isSplineCurve ? divisions * curve.points.length
  19591. : divisions;
  19592. const pts = curve.getPoints( resolution );
  19593. for ( let j = 0; j < pts.length; j ++ ) {
  19594. const point = pts[ j ];
  19595. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  19596. points.push( point );
  19597. last = point;
  19598. }
  19599. }
  19600. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  19601. points.push( points[ 0 ] );
  19602. }
  19603. return points;
  19604. }
  19605. copy( source ) {
  19606. super.copy( source );
  19607. this.curves = [];
  19608. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  19609. const curve = source.curves[ i ];
  19610. this.curves.push( curve.clone() );
  19611. }
  19612. this.autoClose = source.autoClose;
  19613. return this;
  19614. }
  19615. toJSON() {
  19616. const data = super.toJSON();
  19617. data.autoClose = this.autoClose;
  19618. data.curves = [];
  19619. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19620. const curve = this.curves[ i ];
  19621. data.curves.push( curve.toJSON() );
  19622. }
  19623. return data;
  19624. }
  19625. fromJSON( json ) {
  19626. super.fromJSON( json );
  19627. this.autoClose = json.autoClose;
  19628. this.curves = [];
  19629. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  19630. const curve = json.curves[ i ];
  19631. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  19632. }
  19633. return this;
  19634. }
  19635. }
  19636. class Path extends CurvePath {
  19637. constructor( points ) {
  19638. super();
  19639. this.type = 'Path';
  19640. this.currentPoint = new Vector2();
  19641. if ( points ) {
  19642. this.setFromPoints( points );
  19643. }
  19644. }
  19645. setFromPoints( points ) {
  19646. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  19647. for ( let i = 1, l = points.length; i < l; i ++ ) {
  19648. this.lineTo( points[ i ].x, points[ i ].y );
  19649. }
  19650. return this;
  19651. }
  19652. moveTo( x, y ) {
  19653. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  19654. return this;
  19655. }
  19656. lineTo( x, y ) {
  19657. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  19658. this.curves.push( curve );
  19659. this.currentPoint.set( x, y );
  19660. return this;
  19661. }
  19662. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  19663. const curve = new QuadraticBezierCurve(
  19664. this.currentPoint.clone(),
  19665. new Vector2( aCPx, aCPy ),
  19666. new Vector2( aX, aY )
  19667. );
  19668. this.curves.push( curve );
  19669. this.currentPoint.set( aX, aY );
  19670. return this;
  19671. }
  19672. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  19673. const curve = new CubicBezierCurve(
  19674. this.currentPoint.clone(),
  19675. new Vector2( aCP1x, aCP1y ),
  19676. new Vector2( aCP2x, aCP2y ),
  19677. new Vector2( aX, aY )
  19678. );
  19679. this.curves.push( curve );
  19680. this.currentPoint.set( aX, aY );
  19681. return this;
  19682. }
  19683. splineThru( pts /*Array of Vector*/ ) {
  19684. const npts = [ this.currentPoint.clone() ].concat( pts );
  19685. const curve = new SplineCurve( npts );
  19686. this.curves.push( curve );
  19687. this.currentPoint.copy( pts[ pts.length - 1 ] );
  19688. return this;
  19689. }
  19690. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19691. const x0 = this.currentPoint.x;
  19692. const y0 = this.currentPoint.y;
  19693. this.absarc( aX + x0, aY + y0, aRadius,
  19694. aStartAngle, aEndAngle, aClockwise );
  19695. return this;
  19696. }
  19697. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19698. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  19699. return this;
  19700. }
  19701. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19702. const x0 = this.currentPoint.x;
  19703. const y0 = this.currentPoint.y;
  19704. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19705. return this;
  19706. }
  19707. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19708. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19709. if ( this.curves.length > 0 ) {
  19710. // if a previous curve is present, attempt to join
  19711. const firstPoint = curve.getPoint( 0 );
  19712. if ( ! firstPoint.equals( this.currentPoint ) ) {
  19713. this.lineTo( firstPoint.x, firstPoint.y );
  19714. }
  19715. }
  19716. this.curves.push( curve );
  19717. const lastPoint = curve.getPoint( 1 );
  19718. this.currentPoint.copy( lastPoint );
  19719. return this;
  19720. }
  19721. copy( source ) {
  19722. super.copy( source );
  19723. this.currentPoint.copy( source.currentPoint );
  19724. return this;
  19725. }
  19726. toJSON() {
  19727. const data = super.toJSON();
  19728. data.currentPoint = this.currentPoint.toArray();
  19729. return data;
  19730. }
  19731. fromJSON( json ) {
  19732. super.fromJSON( json );
  19733. this.currentPoint.fromArray( json.currentPoint );
  19734. return this;
  19735. }
  19736. }
  19737. class LatheGeometry extends BufferGeometry {
  19738. 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 ) {
  19739. super();
  19740. this.type = 'LatheGeometry';
  19741. this.parameters = {
  19742. points: points,
  19743. segments: segments,
  19744. phiStart: phiStart,
  19745. phiLength: phiLength
  19746. };
  19747. segments = Math.floor( segments );
  19748. // clamp phiLength so it's in range of [ 0, 2PI ]
  19749. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  19750. // buffers
  19751. const indices = [];
  19752. const vertices = [];
  19753. const uvs = [];
  19754. const initNormals = [];
  19755. const normals = [];
  19756. // helper variables
  19757. const inverseSegments = 1.0 / segments;
  19758. const vertex = new Vector3();
  19759. const uv = new Vector2();
  19760. const normal = new Vector3();
  19761. const curNormal = new Vector3();
  19762. const prevNormal = new Vector3();
  19763. let dx = 0;
  19764. let dy = 0;
  19765. // pre-compute normals for initial "meridian"
  19766. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  19767. switch ( j ) {
  19768. case 0: // special handling for 1st vertex on path
  19769. dx = points[ j + 1 ].x - points[ j ].x;
  19770. dy = points[ j + 1 ].y - points[ j ].y;
  19771. normal.x = dy * 1.0;
  19772. normal.y = - dx;
  19773. normal.z = dy * 0.0;
  19774. prevNormal.copy( normal );
  19775. normal.normalize();
  19776. initNormals.push( normal.x, normal.y, normal.z );
  19777. break;
  19778. case ( points.length - 1 ): // special handling for last Vertex on path
  19779. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  19780. break;
  19781. default: // default handling for all vertices in between
  19782. dx = points[ j + 1 ].x - points[ j ].x;
  19783. dy = points[ j + 1 ].y - points[ j ].y;
  19784. normal.x = dy * 1.0;
  19785. normal.y = - dx;
  19786. normal.z = dy * 0.0;
  19787. curNormal.copy( normal );
  19788. normal.x += prevNormal.x;
  19789. normal.y += prevNormal.y;
  19790. normal.z += prevNormal.z;
  19791. normal.normalize();
  19792. initNormals.push( normal.x, normal.y, normal.z );
  19793. prevNormal.copy( curNormal );
  19794. }
  19795. }
  19796. // generate vertices, uvs and normals
  19797. for ( let i = 0; i <= segments; i ++ ) {
  19798. const phi = phiStart + i * inverseSegments * phiLength;
  19799. const sin = Math.sin( phi );
  19800. const cos = Math.cos( phi );
  19801. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  19802. // vertex
  19803. vertex.x = points[ j ].x * sin;
  19804. vertex.y = points[ j ].y;
  19805. vertex.z = points[ j ].x * cos;
  19806. vertices.push( vertex.x, vertex.y, vertex.z );
  19807. // uv
  19808. uv.x = i / segments;
  19809. uv.y = j / ( points.length - 1 );
  19810. uvs.push( uv.x, uv.y );
  19811. // normal
  19812. const x = initNormals[ 3 * j + 0 ] * sin;
  19813. const y = initNormals[ 3 * j + 1 ];
  19814. const z = initNormals[ 3 * j + 0 ] * cos;
  19815. normals.push( x, y, z );
  19816. }
  19817. }
  19818. // indices
  19819. for ( let i = 0; i < segments; i ++ ) {
  19820. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  19821. const base = j + i * points.length;
  19822. const a = base;
  19823. const b = base + points.length;
  19824. const c = base + points.length + 1;
  19825. const d = base + 1;
  19826. // faces
  19827. indices.push( a, b, d );
  19828. indices.push( c, d, b );
  19829. }
  19830. }
  19831. // build geometry
  19832. this.setIndex( indices );
  19833. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19834. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19835. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19836. }
  19837. static fromJSON( data ) {
  19838. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  19839. }
  19840. }
  19841. class CapsuleGeometry extends LatheGeometry {
  19842. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  19843. const path = new Path();
  19844. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  19845. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  19846. super( path.getPoints( capSegments ), radialSegments );
  19847. this.type = 'CapsuleGeometry';
  19848. this.parameters = {
  19849. radius: radius,
  19850. height: length,
  19851. capSegments: capSegments,
  19852. radialSegments: radialSegments,
  19853. };
  19854. }
  19855. static fromJSON( data ) {
  19856. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  19857. }
  19858. }
  19859. class CircleGeometry extends BufferGeometry {
  19860. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19861. super();
  19862. this.type = 'CircleGeometry';
  19863. this.parameters = {
  19864. radius: radius,
  19865. segments: segments,
  19866. thetaStart: thetaStart,
  19867. thetaLength: thetaLength
  19868. };
  19869. segments = Math.max( 3, segments );
  19870. // buffers
  19871. const indices = [];
  19872. const vertices = [];
  19873. const normals = [];
  19874. const uvs = [];
  19875. // helper variables
  19876. const vertex = new Vector3();
  19877. const uv = new Vector2();
  19878. // center point
  19879. vertices.push( 0, 0, 0 );
  19880. normals.push( 0, 0, 1 );
  19881. uvs.push( 0.5, 0.5 );
  19882. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  19883. const segment = thetaStart + s / segments * thetaLength;
  19884. // vertex
  19885. vertex.x = radius * Math.cos( segment );
  19886. vertex.y = radius * Math.sin( segment );
  19887. vertices.push( vertex.x, vertex.y, vertex.z );
  19888. // normal
  19889. normals.push( 0, 0, 1 );
  19890. // uvs
  19891. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  19892. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  19893. uvs.push( uv.x, uv.y );
  19894. }
  19895. // indices
  19896. for ( let i = 1; i <= segments; i ++ ) {
  19897. indices.push( i, i + 1, 0 );
  19898. }
  19899. // build geometry
  19900. this.setIndex( indices );
  19901. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19902. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19903. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19904. }
  19905. static fromJSON( data ) {
  19906. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  19907. }
  19908. }
  19909. class CylinderGeometry extends BufferGeometry {
  19910. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19911. super();
  19912. this.type = 'CylinderGeometry';
  19913. this.parameters = {
  19914. radiusTop: radiusTop,
  19915. radiusBottom: radiusBottom,
  19916. height: height,
  19917. radialSegments: radialSegments,
  19918. heightSegments: heightSegments,
  19919. openEnded: openEnded,
  19920. thetaStart: thetaStart,
  19921. thetaLength: thetaLength
  19922. };
  19923. const scope = this;
  19924. radialSegments = Math.floor( radialSegments );
  19925. heightSegments = Math.floor( heightSegments );
  19926. // buffers
  19927. const indices = [];
  19928. const vertices = [];
  19929. const normals = [];
  19930. const uvs = [];
  19931. // helper variables
  19932. let index = 0;
  19933. const indexArray = [];
  19934. const halfHeight = height / 2;
  19935. let groupStart = 0;
  19936. // generate geometry
  19937. generateTorso();
  19938. if ( openEnded === false ) {
  19939. if ( radiusTop > 0 ) generateCap( true );
  19940. if ( radiusBottom > 0 ) generateCap( false );
  19941. }
  19942. // build geometry
  19943. this.setIndex( indices );
  19944. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19945. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19946. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19947. function generateTorso() {
  19948. const normal = new Vector3();
  19949. const vertex = new Vector3();
  19950. let groupCount = 0;
  19951. // this will be used to calculate the normal
  19952. const slope = ( radiusBottom - radiusTop ) / height;
  19953. // generate vertices, normals and uvs
  19954. for ( let y = 0; y <= heightSegments; y ++ ) {
  19955. const indexRow = [];
  19956. const v = y / heightSegments;
  19957. // calculate the radius of the current row
  19958. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  19959. for ( let x = 0; x <= radialSegments; x ++ ) {
  19960. const u = x / radialSegments;
  19961. const theta = u * thetaLength + thetaStart;
  19962. const sinTheta = Math.sin( theta );
  19963. const cosTheta = Math.cos( theta );
  19964. // vertex
  19965. vertex.x = radius * sinTheta;
  19966. vertex.y = - v * height + halfHeight;
  19967. vertex.z = radius * cosTheta;
  19968. vertices.push( vertex.x, vertex.y, vertex.z );
  19969. // normal
  19970. normal.set( sinTheta, slope, cosTheta ).normalize();
  19971. normals.push( normal.x, normal.y, normal.z );
  19972. // uv
  19973. uvs.push( u, 1 - v );
  19974. // save index of vertex in respective row
  19975. indexRow.push( index ++ );
  19976. }
  19977. // now save vertices of the row in our index array
  19978. indexArray.push( indexRow );
  19979. }
  19980. // generate indices
  19981. for ( let x = 0; x < radialSegments; x ++ ) {
  19982. for ( let y = 0; y < heightSegments; y ++ ) {
  19983. // we use the index array to access the correct indices
  19984. const a = indexArray[ y ][ x ];
  19985. const b = indexArray[ y + 1 ][ x ];
  19986. const c = indexArray[ y + 1 ][ x + 1 ];
  19987. const d = indexArray[ y ][ x + 1 ];
  19988. // faces
  19989. indices.push( a, b, d );
  19990. indices.push( b, c, d );
  19991. // update group counter
  19992. groupCount += 6;
  19993. }
  19994. }
  19995. // add a group to the geometry. this will ensure multi material support
  19996. scope.addGroup( groupStart, groupCount, 0 );
  19997. // calculate new start value for groups
  19998. groupStart += groupCount;
  19999. }
  20000. function generateCap( top ) {
  20001. // save the index of the first center vertex
  20002. const centerIndexStart = index;
  20003. const uv = new Vector2();
  20004. const vertex = new Vector3();
  20005. let groupCount = 0;
  20006. const radius = ( top === true ) ? radiusTop : radiusBottom;
  20007. const sign = ( top === true ) ? 1 : - 1;
  20008. // first we generate the center vertex data of the cap.
  20009. // because the geometry needs one set of uvs per face,
  20010. // we must generate a center vertex per face/segment
  20011. for ( let x = 1; x <= radialSegments; x ++ ) {
  20012. // vertex
  20013. vertices.push( 0, halfHeight * sign, 0 );
  20014. // normal
  20015. normals.push( 0, sign, 0 );
  20016. // uv
  20017. uvs.push( 0.5, 0.5 );
  20018. // increase index
  20019. index ++;
  20020. }
  20021. // save the index of the last center vertex
  20022. const centerIndexEnd = index;
  20023. // now we generate the surrounding vertices, normals and uvs
  20024. for ( let x = 0; x <= radialSegments; x ++ ) {
  20025. const u = x / radialSegments;
  20026. const theta = u * thetaLength + thetaStart;
  20027. const cosTheta = Math.cos( theta );
  20028. const sinTheta = Math.sin( theta );
  20029. // vertex
  20030. vertex.x = radius * sinTheta;
  20031. vertex.y = halfHeight * sign;
  20032. vertex.z = radius * cosTheta;
  20033. vertices.push( vertex.x, vertex.y, vertex.z );
  20034. // normal
  20035. normals.push( 0, sign, 0 );
  20036. // uv
  20037. uv.x = ( cosTheta * 0.5 ) + 0.5;
  20038. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  20039. uvs.push( uv.x, uv.y );
  20040. // increase index
  20041. index ++;
  20042. }
  20043. // generate indices
  20044. for ( let x = 0; x < radialSegments; x ++ ) {
  20045. const c = centerIndexStart + x;
  20046. const i = centerIndexEnd + x;
  20047. if ( top === true ) {
  20048. // face top
  20049. indices.push( i, i + 1, c );
  20050. } else {
  20051. // face bottom
  20052. indices.push( i + 1, i, c );
  20053. }
  20054. groupCount += 3;
  20055. }
  20056. // add a group to the geometry. this will ensure multi material support
  20057. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  20058. // calculate new start value for groups
  20059. groupStart += groupCount;
  20060. }
  20061. }
  20062. static fromJSON( data ) {
  20063. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  20064. }
  20065. }
  20066. class ConeGeometry extends CylinderGeometry {
  20067. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20068. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  20069. this.type = 'ConeGeometry';
  20070. this.parameters = {
  20071. radius: radius,
  20072. height: height,
  20073. radialSegments: radialSegments,
  20074. heightSegments: heightSegments,
  20075. openEnded: openEnded,
  20076. thetaStart: thetaStart,
  20077. thetaLength: thetaLength
  20078. };
  20079. }
  20080. static fromJSON( data ) {
  20081. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  20082. }
  20083. }
  20084. class PolyhedronGeometry extends BufferGeometry {
  20085. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  20086. super();
  20087. this.type = 'PolyhedronGeometry';
  20088. this.parameters = {
  20089. vertices: vertices,
  20090. indices: indices,
  20091. radius: radius,
  20092. detail: detail
  20093. };
  20094. // default buffer data
  20095. const vertexBuffer = [];
  20096. const uvBuffer = [];
  20097. // the subdivision creates the vertex buffer data
  20098. subdivide( detail );
  20099. // all vertices should lie on a conceptual sphere with a given radius
  20100. applyRadius( radius );
  20101. // finally, create the uv data
  20102. generateUVs();
  20103. // build non-indexed geometry
  20104. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  20105. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  20106. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  20107. if ( detail === 0 ) {
  20108. this.computeVertexNormals(); // flat normals
  20109. } else {
  20110. this.normalizeNormals(); // smooth normals
  20111. }
  20112. // helper functions
  20113. function subdivide( detail ) {
  20114. const a = new Vector3();
  20115. const b = new Vector3();
  20116. const c = new Vector3();
  20117. // iterate over all faces and apply a subdivision with the given detail value
  20118. for ( let i = 0; i < indices.length; i += 3 ) {
  20119. // get the vertices of the face
  20120. getVertexByIndex( indices[ i + 0 ], a );
  20121. getVertexByIndex( indices[ i + 1 ], b );
  20122. getVertexByIndex( indices[ i + 2 ], c );
  20123. // perform subdivision
  20124. subdivideFace( a, b, c, detail );
  20125. }
  20126. }
  20127. function subdivideFace( a, b, c, detail ) {
  20128. const cols = detail + 1;
  20129. // we use this multidimensional array as a data structure for creating the subdivision
  20130. const v = [];
  20131. // construct all of the vertices for this subdivision
  20132. for ( let i = 0; i <= cols; i ++ ) {
  20133. v[ i ] = [];
  20134. const aj = a.clone().lerp( c, i / cols );
  20135. const bj = b.clone().lerp( c, i / cols );
  20136. const rows = cols - i;
  20137. for ( let j = 0; j <= rows; j ++ ) {
  20138. if ( j === 0 && i === cols ) {
  20139. v[ i ][ j ] = aj;
  20140. } else {
  20141. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  20142. }
  20143. }
  20144. }
  20145. // construct all of the faces
  20146. for ( let i = 0; i < cols; i ++ ) {
  20147. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  20148. const k = Math.floor( j / 2 );
  20149. if ( j % 2 === 0 ) {
  20150. pushVertex( v[ i ][ k + 1 ] );
  20151. pushVertex( v[ i + 1 ][ k ] );
  20152. pushVertex( v[ i ][ k ] );
  20153. } else {
  20154. pushVertex( v[ i ][ k + 1 ] );
  20155. pushVertex( v[ i + 1 ][ k + 1 ] );
  20156. pushVertex( v[ i + 1 ][ k ] );
  20157. }
  20158. }
  20159. }
  20160. }
  20161. function applyRadius( radius ) {
  20162. const vertex = new Vector3();
  20163. // iterate over the entire buffer and apply the radius to each vertex
  20164. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  20165. vertex.x = vertexBuffer[ i + 0 ];
  20166. vertex.y = vertexBuffer[ i + 1 ];
  20167. vertex.z = vertexBuffer[ i + 2 ];
  20168. vertex.normalize().multiplyScalar( radius );
  20169. vertexBuffer[ i + 0 ] = vertex.x;
  20170. vertexBuffer[ i + 1 ] = vertex.y;
  20171. vertexBuffer[ i + 2 ] = vertex.z;
  20172. }
  20173. }
  20174. function generateUVs() {
  20175. const vertex = new Vector3();
  20176. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  20177. vertex.x = vertexBuffer[ i + 0 ];
  20178. vertex.y = vertexBuffer[ i + 1 ];
  20179. vertex.z = vertexBuffer[ i + 2 ];
  20180. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  20181. const v = inclination( vertex ) / Math.PI + 0.5;
  20182. uvBuffer.push( u, 1 - v );
  20183. }
  20184. correctUVs();
  20185. correctSeam();
  20186. }
  20187. function correctSeam() {
  20188. // handle case when face straddles the seam, see #3269
  20189. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  20190. // uv data of a single face
  20191. const x0 = uvBuffer[ i + 0 ];
  20192. const x1 = uvBuffer[ i + 2 ];
  20193. const x2 = uvBuffer[ i + 4 ];
  20194. const max = Math.max( x0, x1, x2 );
  20195. const min = Math.min( x0, x1, x2 );
  20196. // 0.9 is somewhat arbitrary
  20197. if ( max > 0.9 && min < 0.1 ) {
  20198. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  20199. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  20200. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  20201. }
  20202. }
  20203. }
  20204. function pushVertex( vertex ) {
  20205. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  20206. }
  20207. function getVertexByIndex( index, vertex ) {
  20208. const stride = index * 3;
  20209. vertex.x = vertices[ stride + 0 ];
  20210. vertex.y = vertices[ stride + 1 ];
  20211. vertex.z = vertices[ stride + 2 ];
  20212. }
  20213. function correctUVs() {
  20214. const a = new Vector3();
  20215. const b = new Vector3();
  20216. const c = new Vector3();
  20217. const centroid = new Vector3();
  20218. const uvA = new Vector2();
  20219. const uvB = new Vector2();
  20220. const uvC = new Vector2();
  20221. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  20222. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  20223. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  20224. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  20225. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  20226. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  20227. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  20228. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  20229. const azi = azimuth( centroid );
  20230. correctUV( uvA, j + 0, a, azi );
  20231. correctUV( uvB, j + 2, b, azi );
  20232. correctUV( uvC, j + 4, c, azi );
  20233. }
  20234. }
  20235. function correctUV( uv, stride, vector, azimuth ) {
  20236. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  20237. uvBuffer[ stride ] = uv.x - 1;
  20238. }
  20239. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  20240. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  20241. }
  20242. }
  20243. // Angle around the Y axis, counter-clockwise when looking from above.
  20244. function azimuth( vector ) {
  20245. return Math.atan2( vector.z, - vector.x );
  20246. }
  20247. // Angle above the XZ plane.
  20248. function inclination( vector ) {
  20249. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20250. }
  20251. }
  20252. static fromJSON( data ) {
  20253. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  20254. }
  20255. }
  20256. class DodecahedronGeometry extends PolyhedronGeometry {
  20257. constructor( radius = 1, detail = 0 ) {
  20258. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20259. const r = 1 / t;
  20260. const vertices = [
  20261. // (±1, ±1, ±1)
  20262. - 1, - 1, - 1, - 1, - 1, 1,
  20263. - 1, 1, - 1, - 1, 1, 1,
  20264. 1, - 1, - 1, 1, - 1, 1,
  20265. 1, 1, - 1, 1, 1, 1,
  20266. // (0, ±1/φ, ±φ)
  20267. 0, - r, - t, 0, - r, t,
  20268. 0, r, - t, 0, r, t,
  20269. // (±1/φ, ±φ, 0)
  20270. - r, - t, 0, - r, t, 0,
  20271. r, - t, 0, r, t, 0,
  20272. // (±φ, 0, ±1/φ)
  20273. - t, 0, - r, t, 0, - r,
  20274. - t, 0, r, t, 0, r
  20275. ];
  20276. const indices = [
  20277. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  20278. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  20279. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  20280. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  20281. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  20282. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  20283. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  20284. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  20285. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  20286. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  20287. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  20288. 1, 12, 14, 1, 14, 5, 1, 5, 9
  20289. ];
  20290. super( vertices, indices, radius, detail );
  20291. this.type = 'DodecahedronGeometry';
  20292. this.parameters = {
  20293. radius: radius,
  20294. detail: detail
  20295. };
  20296. }
  20297. static fromJSON( data ) {
  20298. return new DodecahedronGeometry( data.radius, data.detail );
  20299. }
  20300. }
  20301. const _v0 = /*@__PURE__*/ new Vector3();
  20302. const _v1$1 = /*@__PURE__*/ new Vector3();
  20303. const _normal = /*@__PURE__*/ new Vector3();
  20304. const _triangle = /*@__PURE__*/ new Triangle();
  20305. class EdgesGeometry extends BufferGeometry {
  20306. constructor( geometry = null, thresholdAngle = 1 ) {
  20307. super();
  20308. this.type = 'EdgesGeometry';
  20309. this.parameters = {
  20310. geometry: geometry,
  20311. thresholdAngle: thresholdAngle
  20312. };
  20313. if ( geometry !== null ) {
  20314. const precisionPoints = 4;
  20315. const precision = Math.pow( 10, precisionPoints );
  20316. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  20317. const indexAttr = geometry.getIndex();
  20318. const positionAttr = geometry.getAttribute( 'position' );
  20319. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  20320. const indexArr = [ 0, 0, 0 ];
  20321. const vertKeys = [ 'a', 'b', 'c' ];
  20322. const hashes = new Array( 3 );
  20323. const edgeData = {};
  20324. const vertices = [];
  20325. for ( let i = 0; i < indexCount; i += 3 ) {
  20326. if ( indexAttr ) {
  20327. indexArr[ 0 ] = indexAttr.getX( i );
  20328. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  20329. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  20330. } else {
  20331. indexArr[ 0 ] = i;
  20332. indexArr[ 1 ] = i + 1;
  20333. indexArr[ 2 ] = i + 2;
  20334. }
  20335. const { a, b, c } = _triangle;
  20336. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  20337. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  20338. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  20339. _triangle.getNormal( _normal );
  20340. // create hashes for the edge from the vertices
  20341. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  20342. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  20343. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  20344. // skip degenerate triangles
  20345. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  20346. continue;
  20347. }
  20348. // iterate over every edge
  20349. for ( let j = 0; j < 3; j ++ ) {
  20350. // get the first and next vertex making up the edge
  20351. const jNext = ( j + 1 ) % 3;
  20352. const vecHash0 = hashes[ j ];
  20353. const vecHash1 = hashes[ jNext ];
  20354. const v0 = _triangle[ vertKeys[ j ] ];
  20355. const v1 = _triangle[ vertKeys[ jNext ] ];
  20356. const hash = `${ vecHash0 }_${ vecHash1 }`;
  20357. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  20358. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  20359. // if we found a sibling edge add it into the vertex array if
  20360. // it meets the angle threshold and delete the edge from the map.
  20361. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  20362. vertices.push( v0.x, v0.y, v0.z );
  20363. vertices.push( v1.x, v1.y, v1.z );
  20364. }
  20365. edgeData[ reverseHash ] = null;
  20366. } else if ( ! ( hash in edgeData ) ) {
  20367. // if we've already got an edge here then skip adding a new one
  20368. edgeData[ hash ] = {
  20369. index0: indexArr[ j ],
  20370. index1: indexArr[ jNext ],
  20371. normal: _normal.clone(),
  20372. };
  20373. }
  20374. }
  20375. }
  20376. // iterate over all remaining, unmatched edges and add them to the vertex array
  20377. for ( const key in edgeData ) {
  20378. if ( edgeData[ key ] ) {
  20379. const { index0, index1 } = edgeData[ key ];
  20380. _v0.fromBufferAttribute( positionAttr, index0 );
  20381. _v1$1.fromBufferAttribute( positionAttr, index1 );
  20382. vertices.push( _v0.x, _v0.y, _v0.z );
  20383. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  20384. }
  20385. }
  20386. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20387. }
  20388. }
  20389. }
  20390. class Shape extends Path {
  20391. constructor( points ) {
  20392. super( points );
  20393. this.uuid = generateUUID();
  20394. this.type = 'Shape';
  20395. this.holes = [];
  20396. }
  20397. getPointsHoles( divisions ) {
  20398. const holesPts = [];
  20399. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20400. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  20401. }
  20402. return holesPts;
  20403. }
  20404. // get points of shape and holes (keypoints based on segments parameter)
  20405. extractPoints( divisions ) {
  20406. return {
  20407. shape: this.getPoints( divisions ),
  20408. holes: this.getPointsHoles( divisions )
  20409. };
  20410. }
  20411. copy( source ) {
  20412. super.copy( source );
  20413. this.holes = [];
  20414. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  20415. const hole = source.holes[ i ];
  20416. this.holes.push( hole.clone() );
  20417. }
  20418. return this;
  20419. }
  20420. toJSON() {
  20421. const data = super.toJSON();
  20422. data.uuid = this.uuid;
  20423. data.holes = [];
  20424. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20425. const hole = this.holes[ i ];
  20426. data.holes.push( hole.toJSON() );
  20427. }
  20428. return data;
  20429. }
  20430. fromJSON( json ) {
  20431. super.fromJSON( json );
  20432. this.uuid = json.uuid;
  20433. this.holes = [];
  20434. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  20435. const hole = json.holes[ i ];
  20436. this.holes.push( new Path().fromJSON( hole ) );
  20437. }
  20438. return this;
  20439. }
  20440. }
  20441. /**
  20442. * Port from https://github.com/mapbox/earcut (v2.2.4)
  20443. */
  20444. const Earcut = {
  20445. triangulate: function ( data, holeIndices, dim = 2 ) {
  20446. const hasHoles = holeIndices && holeIndices.length;
  20447. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  20448. let outerNode = linkedList( data, 0, outerLen, dim, true );
  20449. const triangles = [];
  20450. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  20451. let minX, minY, maxX, maxY, x, y, invSize;
  20452. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  20453. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  20454. if ( data.length > 80 * dim ) {
  20455. minX = maxX = data[ 0 ];
  20456. minY = maxY = data[ 1 ];
  20457. for ( let i = dim; i < outerLen; i += dim ) {
  20458. x = data[ i ];
  20459. y = data[ i + 1 ];
  20460. if ( x < minX ) minX = x;
  20461. if ( y < minY ) minY = y;
  20462. if ( x > maxX ) maxX = x;
  20463. if ( y > maxY ) maxY = y;
  20464. }
  20465. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  20466. invSize = Math.max( maxX - minX, maxY - minY );
  20467. invSize = invSize !== 0 ? 32767 / invSize : 0;
  20468. }
  20469. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  20470. return triangles;
  20471. }
  20472. };
  20473. // create a circular doubly linked list from polygon points in the specified winding order
  20474. function linkedList( data, start, end, dim, clockwise ) {
  20475. let i, last;
  20476. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  20477. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20478. } else {
  20479. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20480. }
  20481. if ( last && equals( last, last.next ) ) {
  20482. removeNode( last );
  20483. last = last.next;
  20484. }
  20485. return last;
  20486. }
  20487. // eliminate colinear or duplicate points
  20488. function filterPoints( start, end ) {
  20489. if ( ! start ) return start;
  20490. if ( ! end ) end = start;
  20491. let p = start,
  20492. again;
  20493. do {
  20494. again = false;
  20495. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  20496. removeNode( p );
  20497. p = end = p.prev;
  20498. if ( p === p.next ) break;
  20499. again = true;
  20500. } else {
  20501. p = p.next;
  20502. }
  20503. } while ( again || p !== end );
  20504. return end;
  20505. }
  20506. // main ear slicing loop which triangulates a polygon (given as a linked list)
  20507. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  20508. if ( ! ear ) return;
  20509. // interlink polygon nodes in z-order
  20510. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  20511. let stop = ear,
  20512. prev, next;
  20513. // iterate through ears, slicing them one by one
  20514. while ( ear.prev !== ear.next ) {
  20515. prev = ear.prev;
  20516. next = ear.next;
  20517. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  20518. // cut off the triangle
  20519. triangles.push( prev.i / dim | 0 );
  20520. triangles.push( ear.i / dim | 0 );
  20521. triangles.push( next.i / dim | 0 );
  20522. removeNode( ear );
  20523. // skipping the next vertex leads to less sliver triangles
  20524. ear = next.next;
  20525. stop = next.next;
  20526. continue;
  20527. }
  20528. ear = next;
  20529. // if we looped through the whole remaining polygon and can't find any more ears
  20530. if ( ear === stop ) {
  20531. // try filtering points and slicing again
  20532. if ( ! pass ) {
  20533. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  20534. // if this didn't work, try curing all small self-intersections locally
  20535. } else if ( pass === 1 ) {
  20536. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  20537. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  20538. // as a last resort, try splitting the remaining polygon into two
  20539. } else if ( pass === 2 ) {
  20540. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  20541. }
  20542. break;
  20543. }
  20544. }
  20545. }
  20546. // check whether a polygon node forms a valid ear with adjacent nodes
  20547. function isEar( ear ) {
  20548. const a = ear.prev,
  20549. b = ear,
  20550. c = ear.next;
  20551. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20552. // now make sure we don't have other points inside the potential ear
  20553. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  20554. // triangle bbox; min & max are calculated like this for speed
  20555. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  20556. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  20557. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  20558. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  20559. let p = c.next;
  20560. while ( p !== a ) {
  20561. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  20562. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  20563. area( p.prev, p, p.next ) >= 0 ) return false;
  20564. p = p.next;
  20565. }
  20566. return true;
  20567. }
  20568. function isEarHashed( ear, minX, minY, invSize ) {
  20569. const a = ear.prev,
  20570. b = ear,
  20571. c = ear.next;
  20572. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20573. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  20574. // triangle bbox; min & max are calculated like this for speed
  20575. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  20576. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  20577. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  20578. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  20579. // z-order range for the current triangle bbox;
  20580. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  20581. maxZ = zOrder( x1, y1, minX, minY, invSize );
  20582. let p = ear.prevZ,
  20583. n = ear.nextZ;
  20584. // look for points inside the triangle in both directions
  20585. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  20586. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  20587. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  20588. p = p.prevZ;
  20589. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  20590. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  20591. n = n.nextZ;
  20592. }
  20593. // look for remaining points in decreasing z-order
  20594. while ( p && p.z >= minZ ) {
  20595. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  20596. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  20597. p = p.prevZ;
  20598. }
  20599. // look for remaining points in increasing z-order
  20600. while ( n && n.z <= maxZ ) {
  20601. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  20602. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  20603. n = n.nextZ;
  20604. }
  20605. return true;
  20606. }
  20607. // go through all polygon nodes and cure small local self-intersections
  20608. function cureLocalIntersections( start, triangles, dim ) {
  20609. let p = start;
  20610. do {
  20611. const a = p.prev,
  20612. b = p.next.next;
  20613. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  20614. triangles.push( a.i / dim | 0 );
  20615. triangles.push( p.i / dim | 0 );
  20616. triangles.push( b.i / dim | 0 );
  20617. // remove two nodes involved
  20618. removeNode( p );
  20619. removeNode( p.next );
  20620. p = start = b;
  20621. }
  20622. p = p.next;
  20623. } while ( p !== start );
  20624. return filterPoints( p );
  20625. }
  20626. // try splitting polygon into two and triangulate them independently
  20627. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  20628. // look for a valid diagonal that divides the polygon into two
  20629. let a = start;
  20630. do {
  20631. let b = a.next.next;
  20632. while ( b !== a.prev ) {
  20633. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  20634. // split the polygon in two by the diagonal
  20635. let c = splitPolygon( a, b );
  20636. // filter colinear points around the cuts
  20637. a = filterPoints( a, a.next );
  20638. c = filterPoints( c, c.next );
  20639. // run earcut on each half
  20640. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  20641. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  20642. return;
  20643. }
  20644. b = b.next;
  20645. }
  20646. a = a.next;
  20647. } while ( a !== start );
  20648. }
  20649. // link every hole into the outer loop, producing a single-ring polygon without holes
  20650. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  20651. const queue = [];
  20652. let i, len, start, end, list;
  20653. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  20654. start = holeIndices[ i ] * dim;
  20655. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  20656. list = linkedList( data, start, end, dim, false );
  20657. if ( list === list.next ) list.steiner = true;
  20658. queue.push( getLeftmost( list ) );
  20659. }
  20660. queue.sort( compareX );
  20661. // process holes from left to right
  20662. for ( i = 0; i < queue.length; i ++ ) {
  20663. outerNode = eliminateHole( queue[ i ], outerNode );
  20664. }
  20665. return outerNode;
  20666. }
  20667. function compareX( a, b ) {
  20668. return a.x - b.x;
  20669. }
  20670. // find a bridge between vertices that connects hole with an outer ring and link it
  20671. function eliminateHole( hole, outerNode ) {
  20672. const bridge = findHoleBridge( hole, outerNode );
  20673. if ( ! bridge ) {
  20674. return outerNode;
  20675. }
  20676. const bridgeReverse = splitPolygon( bridge, hole );
  20677. // filter collinear points around the cuts
  20678. filterPoints( bridgeReverse, bridgeReverse.next );
  20679. return filterPoints( bridge, bridge.next );
  20680. }
  20681. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  20682. function findHoleBridge( hole, outerNode ) {
  20683. let p = outerNode,
  20684. qx = - Infinity,
  20685. m;
  20686. const hx = hole.x, hy = hole.y;
  20687. // find a segment intersected by a ray from the hole's leftmost point to the left;
  20688. // segment's endpoint with lesser x will be potential connection point
  20689. do {
  20690. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  20691. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  20692. if ( x <= hx && x > qx ) {
  20693. qx = x;
  20694. m = p.x < p.next.x ? p : p.next;
  20695. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  20696. }
  20697. }
  20698. p = p.next;
  20699. } while ( p !== outerNode );
  20700. if ( ! m ) return null;
  20701. // look for points inside the triangle of hole point, segment intersection and endpoint;
  20702. // if there are no points found, we have a valid connection;
  20703. // otherwise choose the point of the minimum angle with the ray as connection point
  20704. const stop = m,
  20705. mx = m.x,
  20706. my = m.y;
  20707. let tanMin = Infinity, tan;
  20708. p = m;
  20709. do {
  20710. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  20711. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  20712. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  20713. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  20714. m = p;
  20715. tanMin = tan;
  20716. }
  20717. }
  20718. p = p.next;
  20719. } while ( p !== stop );
  20720. return m;
  20721. }
  20722. // whether sector in vertex m contains sector in vertex p in the same coordinates
  20723. function sectorContainsSector( m, p ) {
  20724. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  20725. }
  20726. // interlink polygon nodes in z-order
  20727. function indexCurve( start, minX, minY, invSize ) {
  20728. let p = start;
  20729. do {
  20730. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  20731. p.prevZ = p.prev;
  20732. p.nextZ = p.next;
  20733. p = p.next;
  20734. } while ( p !== start );
  20735. p.prevZ.nextZ = null;
  20736. p.prevZ = null;
  20737. sortLinked( p );
  20738. }
  20739. // Simon Tatham's linked list merge sort algorithm
  20740. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  20741. function sortLinked( list ) {
  20742. let i, p, q, e, tail, numMerges, pSize, qSize,
  20743. inSize = 1;
  20744. do {
  20745. p = list;
  20746. list = null;
  20747. tail = null;
  20748. numMerges = 0;
  20749. while ( p ) {
  20750. numMerges ++;
  20751. q = p;
  20752. pSize = 0;
  20753. for ( i = 0; i < inSize; i ++ ) {
  20754. pSize ++;
  20755. q = q.nextZ;
  20756. if ( ! q ) break;
  20757. }
  20758. qSize = inSize;
  20759. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  20760. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  20761. e = p;
  20762. p = p.nextZ;
  20763. pSize --;
  20764. } else {
  20765. e = q;
  20766. q = q.nextZ;
  20767. qSize --;
  20768. }
  20769. if ( tail ) tail.nextZ = e;
  20770. else list = e;
  20771. e.prevZ = tail;
  20772. tail = e;
  20773. }
  20774. p = q;
  20775. }
  20776. tail.nextZ = null;
  20777. inSize *= 2;
  20778. } while ( numMerges > 1 );
  20779. return list;
  20780. }
  20781. // z-order of a point given coords and inverse of the longer side of data bbox
  20782. function zOrder( x, y, minX, minY, invSize ) {
  20783. // coords are transformed into non-negative 15-bit integer range
  20784. x = ( x - minX ) * invSize | 0;
  20785. y = ( y - minY ) * invSize | 0;
  20786. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  20787. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  20788. x = ( x | ( x << 2 ) ) & 0x33333333;
  20789. x = ( x | ( x << 1 ) ) & 0x55555555;
  20790. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  20791. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  20792. y = ( y | ( y << 2 ) ) & 0x33333333;
  20793. y = ( y | ( y << 1 ) ) & 0x55555555;
  20794. return x | ( y << 1 );
  20795. }
  20796. // find the leftmost node of a polygon ring
  20797. function getLeftmost( start ) {
  20798. let p = start,
  20799. leftmost = start;
  20800. do {
  20801. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  20802. p = p.next;
  20803. } while ( p !== start );
  20804. return leftmost;
  20805. }
  20806. // check if a point lies within a convex triangle
  20807. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  20808. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  20809. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  20810. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  20811. }
  20812. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  20813. function isValidDiagonal( a, b ) {
  20814. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  20815. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  20816. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  20817. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  20818. }
  20819. // signed area of a triangle
  20820. function area( p, q, r ) {
  20821. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  20822. }
  20823. // check if two points are equal
  20824. function equals( p1, p2 ) {
  20825. return p1.x === p2.x && p1.y === p2.y;
  20826. }
  20827. // check if two segments intersect
  20828. function intersects( p1, q1, p2, q2 ) {
  20829. const o1 = sign( area( p1, q1, p2 ) );
  20830. const o2 = sign( area( p1, q1, q2 ) );
  20831. const o3 = sign( area( p2, q2, p1 ) );
  20832. const o4 = sign( area( p2, q2, q1 ) );
  20833. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  20834. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  20835. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  20836. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  20837. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  20838. return false;
  20839. }
  20840. // for collinear points p, q, r, check if point q lies on segment pr
  20841. function onSegment( p, q, r ) {
  20842. 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 );
  20843. }
  20844. function sign( num ) {
  20845. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  20846. }
  20847. // check if a polygon diagonal intersects any polygon segments
  20848. function intersectsPolygon( a, b ) {
  20849. let p = a;
  20850. do {
  20851. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  20852. intersects( p, p.next, a, b ) ) return true;
  20853. p = p.next;
  20854. } while ( p !== a );
  20855. return false;
  20856. }
  20857. // check if a polygon diagonal is locally inside the polygon
  20858. function locallyInside( a, b ) {
  20859. return area( a.prev, a, a.next ) < 0 ?
  20860. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  20861. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  20862. }
  20863. // check if the middle point of a polygon diagonal is inside the polygon
  20864. function middleInside( a, b ) {
  20865. let p = a,
  20866. inside = false;
  20867. const px = ( a.x + b.x ) / 2,
  20868. py = ( a.y + b.y ) / 2;
  20869. do {
  20870. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  20871. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  20872. inside = ! inside;
  20873. p = p.next;
  20874. } while ( p !== a );
  20875. return inside;
  20876. }
  20877. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  20878. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  20879. function splitPolygon( a, b ) {
  20880. const a2 = new Node( a.i, a.x, a.y ),
  20881. b2 = new Node( b.i, b.x, b.y ),
  20882. an = a.next,
  20883. bp = b.prev;
  20884. a.next = b;
  20885. b.prev = a;
  20886. a2.next = an;
  20887. an.prev = a2;
  20888. b2.next = a2;
  20889. a2.prev = b2;
  20890. bp.next = b2;
  20891. b2.prev = bp;
  20892. return b2;
  20893. }
  20894. // create a node and optionally link it with previous one (in a circular doubly linked list)
  20895. function insertNode( i, x, y, last ) {
  20896. const p = new Node( i, x, y );
  20897. if ( ! last ) {
  20898. p.prev = p;
  20899. p.next = p;
  20900. } else {
  20901. p.next = last.next;
  20902. p.prev = last;
  20903. last.next.prev = p;
  20904. last.next = p;
  20905. }
  20906. return p;
  20907. }
  20908. function removeNode( p ) {
  20909. p.next.prev = p.prev;
  20910. p.prev.next = p.next;
  20911. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  20912. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  20913. }
  20914. function Node( i, x, y ) {
  20915. // vertex index in coordinates array
  20916. this.i = i;
  20917. // vertex coordinates
  20918. this.x = x;
  20919. this.y = y;
  20920. // previous and next vertex nodes in a polygon ring
  20921. this.prev = null;
  20922. this.next = null;
  20923. // z-order curve value
  20924. this.z = 0;
  20925. // previous and next nodes in z-order
  20926. this.prevZ = null;
  20927. this.nextZ = null;
  20928. // indicates whether this is a steiner point
  20929. this.steiner = false;
  20930. }
  20931. function signedArea( data, start, end, dim ) {
  20932. let sum = 0;
  20933. for ( let i = start, j = end - dim; i < end; i += dim ) {
  20934. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  20935. j = i;
  20936. }
  20937. return sum;
  20938. }
  20939. class ShapeUtils {
  20940. // calculate area of the contour polygon
  20941. static area( contour ) {
  20942. const n = contour.length;
  20943. let a = 0.0;
  20944. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  20945. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  20946. }
  20947. return a * 0.5;
  20948. }
  20949. static isClockWise( pts ) {
  20950. return ShapeUtils.area( pts ) < 0;
  20951. }
  20952. static triangulateShape( contour, holes ) {
  20953. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  20954. const holeIndices = []; // array of hole indices
  20955. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  20956. removeDupEndPts( contour );
  20957. addContour( vertices, contour );
  20958. //
  20959. let holeIndex = contour.length;
  20960. holes.forEach( removeDupEndPts );
  20961. for ( let i = 0; i < holes.length; i ++ ) {
  20962. holeIndices.push( holeIndex );
  20963. holeIndex += holes[ i ].length;
  20964. addContour( vertices, holes[ i ] );
  20965. }
  20966. //
  20967. const triangles = Earcut.triangulate( vertices, holeIndices );
  20968. //
  20969. for ( let i = 0; i < triangles.length; i += 3 ) {
  20970. faces.push( triangles.slice( i, i + 3 ) );
  20971. }
  20972. return faces;
  20973. }
  20974. }
  20975. function removeDupEndPts( points ) {
  20976. const l = points.length;
  20977. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  20978. points.pop();
  20979. }
  20980. }
  20981. function addContour( vertices, contour ) {
  20982. for ( let i = 0; i < contour.length; i ++ ) {
  20983. vertices.push( contour[ i ].x );
  20984. vertices.push( contour[ i ].y );
  20985. }
  20986. }
  20987. /**
  20988. * Creates extruded geometry from a path shape.
  20989. *
  20990. * parameters = {
  20991. *
  20992. * curveSegments: <int>, // number of points on the curves
  20993. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  20994. * depth: <float>, // Depth to extrude the shape
  20995. *
  20996. * bevelEnabled: <bool>, // turn on bevel
  20997. * bevelThickness: <float>, // how deep into the original shape bevel goes
  20998. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  20999. * bevelOffset: <float>, // how far from shape outline does bevel start
  21000. * bevelSegments: <int>, // number of bevel layers
  21001. *
  21002. * extrudePath: <THREE.Curve> // curve to extrude shape along
  21003. *
  21004. * UVGenerator: <Object> // object that provides UV generator functions
  21005. *
  21006. * }
  21007. */
  21008. class ExtrudeGeometry extends BufferGeometry {
  21009. 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 = {} ) {
  21010. super();
  21011. this.type = 'ExtrudeGeometry';
  21012. this.parameters = {
  21013. shapes: shapes,
  21014. options: options
  21015. };
  21016. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  21017. const scope = this;
  21018. const verticesArray = [];
  21019. const uvArray = [];
  21020. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21021. const shape = shapes[ i ];
  21022. addShape( shape );
  21023. }
  21024. // build geometry
  21025. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  21026. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  21027. this.computeVertexNormals();
  21028. // functions
  21029. function addShape( shape ) {
  21030. const placeholder = [];
  21031. // options
  21032. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  21033. const steps = options.steps !== undefined ? options.steps : 1;
  21034. const depth = options.depth !== undefined ? options.depth : 1;
  21035. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  21036. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  21037. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  21038. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  21039. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  21040. const extrudePath = options.extrudePath;
  21041. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  21042. //
  21043. let extrudePts, extrudeByPath = false;
  21044. let splineTube, binormal, normal, position2;
  21045. if ( extrudePath ) {
  21046. extrudePts = extrudePath.getSpacedPoints( steps );
  21047. extrudeByPath = true;
  21048. bevelEnabled = false; // bevels not supported for path extrusion
  21049. // SETUP TNB variables
  21050. // TODO1 - have a .isClosed in spline?
  21051. splineTube = extrudePath.computeFrenetFrames( steps, false );
  21052. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  21053. binormal = new Vector3();
  21054. normal = new Vector3();
  21055. position2 = new Vector3();
  21056. }
  21057. // Safeguards if bevels are not enabled
  21058. if ( ! bevelEnabled ) {
  21059. bevelSegments = 0;
  21060. bevelThickness = 0;
  21061. bevelSize = 0;
  21062. bevelOffset = 0;
  21063. }
  21064. // Variables initialization
  21065. const shapePoints = shape.extractPoints( curveSegments );
  21066. let vertices = shapePoints.shape;
  21067. const holes = shapePoints.holes;
  21068. const reverse = ! ShapeUtils.isClockWise( vertices );
  21069. if ( reverse ) {
  21070. vertices = vertices.reverse();
  21071. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  21072. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21073. const ahole = holes[ h ];
  21074. if ( ShapeUtils.isClockWise( ahole ) ) {
  21075. holes[ h ] = ahole.reverse();
  21076. }
  21077. }
  21078. }
  21079. const faces = ShapeUtils.triangulateShape( vertices, holes );
  21080. /* Vertices */
  21081. const contour = vertices; // vertices has all points but contour has only points of circumference
  21082. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21083. const ahole = holes[ h ];
  21084. vertices = vertices.concat( ahole );
  21085. }
  21086. function scalePt2( pt, vec, size ) {
  21087. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  21088. return vec.clone().multiplyScalar( size ).add( pt );
  21089. }
  21090. const vlen = vertices.length, flen = faces.length;
  21091. // Find directions for point movement
  21092. function getBevelVec( inPt, inPrev, inNext ) {
  21093. // computes for inPt the corresponding point inPt' on a new contour
  21094. // shifted by 1 unit (length of normalized vector) to the left
  21095. // if we walk along contour clockwise, this new contour is outside the old one
  21096. //
  21097. // inPt' is the intersection of the two lines parallel to the two
  21098. // adjacent edges of inPt at a distance of 1 unit on the left side.
  21099. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  21100. // good reading for geometry algorithms (here: line-line intersection)
  21101. // http://geomalgorithms.com/a05-_intersect-1.html
  21102. const v_prev_x = inPt.x - inPrev.x,
  21103. v_prev_y = inPt.y - inPrev.y;
  21104. const v_next_x = inNext.x - inPt.x,
  21105. v_next_y = inNext.y - inPt.y;
  21106. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  21107. // check for collinear edges
  21108. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21109. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  21110. // not collinear
  21111. // length of vectors for normalizing
  21112. const v_prev_len = Math.sqrt( v_prev_lensq );
  21113. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  21114. // shift adjacent points by unit vectors to the left
  21115. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  21116. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  21117. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  21118. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  21119. // scaling factor for v_prev to intersection point
  21120. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  21121. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  21122. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21123. // vector from inPt to intersection point
  21124. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  21125. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  21126. // Don't normalize!, otherwise sharp corners become ugly
  21127. // but prevent crazy spikes
  21128. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  21129. if ( v_trans_lensq <= 2 ) {
  21130. return new Vector2( v_trans_x, v_trans_y );
  21131. } else {
  21132. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  21133. }
  21134. } else {
  21135. // handle special case of collinear edges
  21136. let direction_eq = false; // assumes: opposite
  21137. if ( v_prev_x > Number.EPSILON ) {
  21138. if ( v_next_x > Number.EPSILON ) {
  21139. direction_eq = true;
  21140. }
  21141. } else {
  21142. if ( v_prev_x < - Number.EPSILON ) {
  21143. if ( v_next_x < - Number.EPSILON ) {
  21144. direction_eq = true;
  21145. }
  21146. } else {
  21147. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  21148. direction_eq = true;
  21149. }
  21150. }
  21151. }
  21152. if ( direction_eq ) {
  21153. // console.log("Warning: lines are a straight sequence");
  21154. v_trans_x = - v_prev_y;
  21155. v_trans_y = v_prev_x;
  21156. shrink_by = Math.sqrt( v_prev_lensq );
  21157. } else {
  21158. // console.log("Warning: lines are a straight spike");
  21159. v_trans_x = v_prev_x;
  21160. v_trans_y = v_prev_y;
  21161. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  21162. }
  21163. }
  21164. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  21165. }
  21166. const contourMovements = [];
  21167. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21168. if ( j === il ) j = 0;
  21169. if ( k === il ) k = 0;
  21170. // (j)---(i)---(k)
  21171. // console.log('i,j,k', i, j , k)
  21172. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  21173. }
  21174. const holesMovements = [];
  21175. let oneHoleMovements, verticesMovements = contourMovements.concat();
  21176. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21177. const ahole = holes[ h ];
  21178. oneHoleMovements = [];
  21179. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21180. if ( j === il ) j = 0;
  21181. if ( k === il ) k = 0;
  21182. // (j)---(i)---(k)
  21183. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  21184. }
  21185. holesMovements.push( oneHoleMovements );
  21186. verticesMovements = verticesMovements.concat( oneHoleMovements );
  21187. }
  21188. // Loop bevelSegments, 1 for the front, 1 for the back
  21189. for ( let b = 0; b < bevelSegments; b ++ ) {
  21190. //for ( b = bevelSegments; b > 0; b -- ) {
  21191. const t = b / bevelSegments;
  21192. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21193. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21194. // contract shape
  21195. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21196. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21197. v( vert.x, vert.y, - z );
  21198. }
  21199. // expand holes
  21200. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21201. const ahole = holes[ h ];
  21202. oneHoleMovements = holesMovements[ h ];
  21203. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21204. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21205. v( vert.x, vert.y, - z );
  21206. }
  21207. }
  21208. }
  21209. const bs = bevelSize + bevelOffset;
  21210. // Back facing vertices
  21211. for ( let i = 0; i < vlen; i ++ ) {
  21212. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21213. if ( ! extrudeByPath ) {
  21214. v( vert.x, vert.y, 0 );
  21215. } else {
  21216. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  21217. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  21218. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  21219. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  21220. v( position2.x, position2.y, position2.z );
  21221. }
  21222. }
  21223. // Add stepped vertices...
  21224. // Including front facing vertices
  21225. for ( let s = 1; s <= steps; s ++ ) {
  21226. for ( let i = 0; i < vlen; i ++ ) {
  21227. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21228. if ( ! extrudeByPath ) {
  21229. v( vert.x, vert.y, depth / steps * s );
  21230. } else {
  21231. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  21232. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  21233. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  21234. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  21235. v( position2.x, position2.y, position2.z );
  21236. }
  21237. }
  21238. }
  21239. // Add bevel segments planes
  21240. //for ( b = 1; b <= bevelSegments; b ++ ) {
  21241. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  21242. const t = b / bevelSegments;
  21243. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21244. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21245. // contract shape
  21246. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21247. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21248. v( vert.x, vert.y, depth + z );
  21249. }
  21250. // expand holes
  21251. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21252. const ahole = holes[ h ];
  21253. oneHoleMovements = holesMovements[ h ];
  21254. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21255. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21256. if ( ! extrudeByPath ) {
  21257. v( vert.x, vert.y, depth + z );
  21258. } else {
  21259. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  21260. }
  21261. }
  21262. }
  21263. }
  21264. /* Faces */
  21265. // Top and bottom faces
  21266. buildLidFaces();
  21267. // Sides faces
  21268. buildSideFaces();
  21269. ///// Internal functions
  21270. function buildLidFaces() {
  21271. const start = verticesArray.length / 3;
  21272. if ( bevelEnabled ) {
  21273. let layer = 0; // steps + 1
  21274. let offset = vlen * layer;
  21275. // Bottom faces
  21276. for ( let i = 0; i < flen; i ++ ) {
  21277. const face = faces[ i ];
  21278. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  21279. }
  21280. layer = steps + bevelSegments * 2;
  21281. offset = vlen * layer;
  21282. // Top faces
  21283. for ( let i = 0; i < flen; i ++ ) {
  21284. const face = faces[ i ];
  21285. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  21286. }
  21287. } else {
  21288. // Bottom faces
  21289. for ( let i = 0; i < flen; i ++ ) {
  21290. const face = faces[ i ];
  21291. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  21292. }
  21293. // Top faces
  21294. for ( let i = 0; i < flen; i ++ ) {
  21295. const face = faces[ i ];
  21296. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  21297. }
  21298. }
  21299. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  21300. }
  21301. // Create faces for the z-sides of the shape
  21302. function buildSideFaces() {
  21303. const start = verticesArray.length / 3;
  21304. let layeroffset = 0;
  21305. sidewalls( contour, layeroffset );
  21306. layeroffset += contour.length;
  21307. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21308. const ahole = holes[ h ];
  21309. sidewalls( ahole, layeroffset );
  21310. //, true
  21311. layeroffset += ahole.length;
  21312. }
  21313. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  21314. }
  21315. function sidewalls( contour, layeroffset ) {
  21316. let i = contour.length;
  21317. while ( -- i >= 0 ) {
  21318. const j = i;
  21319. let k = i - 1;
  21320. if ( k < 0 ) k = contour.length - 1;
  21321. //console.log('b', i,j, i-1, k,vertices.length);
  21322. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  21323. const slen1 = vlen * s;
  21324. const slen2 = vlen * ( s + 1 );
  21325. const a = layeroffset + j + slen1,
  21326. b = layeroffset + k + slen1,
  21327. c = layeroffset + k + slen2,
  21328. d = layeroffset + j + slen2;
  21329. f4( a, b, c, d );
  21330. }
  21331. }
  21332. }
  21333. function v( x, y, z ) {
  21334. placeholder.push( x );
  21335. placeholder.push( y );
  21336. placeholder.push( z );
  21337. }
  21338. function f3( a, b, c ) {
  21339. addVertex( a );
  21340. addVertex( b );
  21341. addVertex( c );
  21342. const nextIndex = verticesArray.length / 3;
  21343. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21344. addUV( uvs[ 0 ] );
  21345. addUV( uvs[ 1 ] );
  21346. addUV( uvs[ 2 ] );
  21347. }
  21348. function f4( a, b, c, d ) {
  21349. addVertex( a );
  21350. addVertex( b );
  21351. addVertex( d );
  21352. addVertex( b );
  21353. addVertex( c );
  21354. addVertex( d );
  21355. const nextIndex = verticesArray.length / 3;
  21356. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21357. addUV( uvs[ 0 ] );
  21358. addUV( uvs[ 1 ] );
  21359. addUV( uvs[ 3 ] );
  21360. addUV( uvs[ 1 ] );
  21361. addUV( uvs[ 2 ] );
  21362. addUV( uvs[ 3 ] );
  21363. }
  21364. function addVertex( index ) {
  21365. verticesArray.push( placeholder[ index * 3 + 0 ] );
  21366. verticesArray.push( placeholder[ index * 3 + 1 ] );
  21367. verticesArray.push( placeholder[ index * 3 + 2 ] );
  21368. }
  21369. function addUV( vector2 ) {
  21370. uvArray.push( vector2.x );
  21371. uvArray.push( vector2.y );
  21372. }
  21373. }
  21374. }
  21375. toJSON() {
  21376. const data = super.toJSON();
  21377. const shapes = this.parameters.shapes;
  21378. const options = this.parameters.options;
  21379. return toJSON$1( shapes, options, data );
  21380. }
  21381. static fromJSON( data, shapes ) {
  21382. const geometryShapes = [];
  21383. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21384. const shape = shapes[ data.shapes[ j ] ];
  21385. geometryShapes.push( shape );
  21386. }
  21387. const extrudePath = data.options.extrudePath;
  21388. if ( extrudePath !== undefined ) {
  21389. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  21390. }
  21391. return new ExtrudeGeometry( geometryShapes, data.options );
  21392. }
  21393. }
  21394. const WorldUVGenerator = {
  21395. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  21396. const a_x = vertices[ indexA * 3 ];
  21397. const a_y = vertices[ indexA * 3 + 1 ];
  21398. const b_x = vertices[ indexB * 3 ];
  21399. const b_y = vertices[ indexB * 3 + 1 ];
  21400. const c_x = vertices[ indexC * 3 ];
  21401. const c_y = vertices[ indexC * 3 + 1 ];
  21402. return [
  21403. new Vector2( a_x, a_y ),
  21404. new Vector2( b_x, b_y ),
  21405. new Vector2( c_x, c_y )
  21406. ];
  21407. },
  21408. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  21409. const a_x = vertices[ indexA * 3 ];
  21410. const a_y = vertices[ indexA * 3 + 1 ];
  21411. const a_z = vertices[ indexA * 3 + 2 ];
  21412. const b_x = vertices[ indexB * 3 ];
  21413. const b_y = vertices[ indexB * 3 + 1 ];
  21414. const b_z = vertices[ indexB * 3 + 2 ];
  21415. const c_x = vertices[ indexC * 3 ];
  21416. const c_y = vertices[ indexC * 3 + 1 ];
  21417. const c_z = vertices[ indexC * 3 + 2 ];
  21418. const d_x = vertices[ indexD * 3 ];
  21419. const d_y = vertices[ indexD * 3 + 1 ];
  21420. const d_z = vertices[ indexD * 3 + 2 ];
  21421. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  21422. return [
  21423. new Vector2( a_x, 1 - a_z ),
  21424. new Vector2( b_x, 1 - b_z ),
  21425. new Vector2( c_x, 1 - c_z ),
  21426. new Vector2( d_x, 1 - d_z )
  21427. ];
  21428. } else {
  21429. return [
  21430. new Vector2( a_y, 1 - a_z ),
  21431. new Vector2( b_y, 1 - b_z ),
  21432. new Vector2( c_y, 1 - c_z ),
  21433. new Vector2( d_y, 1 - d_z )
  21434. ];
  21435. }
  21436. }
  21437. };
  21438. function toJSON$1( shapes, options, data ) {
  21439. data.shapes = [];
  21440. if ( Array.isArray( shapes ) ) {
  21441. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21442. const shape = shapes[ i ];
  21443. data.shapes.push( shape.uuid );
  21444. }
  21445. } else {
  21446. data.shapes.push( shapes.uuid );
  21447. }
  21448. data.options = Object.assign( {}, options );
  21449. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  21450. return data;
  21451. }
  21452. class IcosahedronGeometry extends PolyhedronGeometry {
  21453. constructor( radius = 1, detail = 0 ) {
  21454. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21455. const vertices = [
  21456. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  21457. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  21458. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  21459. ];
  21460. const indices = [
  21461. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  21462. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  21463. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  21464. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  21465. ];
  21466. super( vertices, indices, radius, detail );
  21467. this.type = 'IcosahedronGeometry';
  21468. this.parameters = {
  21469. radius: radius,
  21470. detail: detail
  21471. };
  21472. }
  21473. static fromJSON( data ) {
  21474. return new IcosahedronGeometry( data.radius, data.detail );
  21475. }
  21476. }
  21477. class OctahedronGeometry extends PolyhedronGeometry {
  21478. constructor( radius = 1, detail = 0 ) {
  21479. const vertices = [
  21480. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  21481. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  21482. ];
  21483. const indices = [
  21484. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  21485. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  21486. 1, 3, 4, 1, 4, 2
  21487. ];
  21488. super( vertices, indices, radius, detail );
  21489. this.type = 'OctahedronGeometry';
  21490. this.parameters = {
  21491. radius: radius,
  21492. detail: detail
  21493. };
  21494. }
  21495. static fromJSON( data ) {
  21496. return new OctahedronGeometry( data.radius, data.detail );
  21497. }
  21498. }
  21499. class RingGeometry extends BufferGeometry {
  21500. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21501. super();
  21502. this.type = 'RingGeometry';
  21503. this.parameters = {
  21504. innerRadius: innerRadius,
  21505. outerRadius: outerRadius,
  21506. thetaSegments: thetaSegments,
  21507. phiSegments: phiSegments,
  21508. thetaStart: thetaStart,
  21509. thetaLength: thetaLength
  21510. };
  21511. thetaSegments = Math.max( 3, thetaSegments );
  21512. phiSegments = Math.max( 1, phiSegments );
  21513. // buffers
  21514. const indices = [];
  21515. const vertices = [];
  21516. const normals = [];
  21517. const uvs = [];
  21518. // some helper variables
  21519. let radius = innerRadius;
  21520. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  21521. const vertex = new Vector3();
  21522. const uv = new Vector2();
  21523. // generate vertices, normals and uvs
  21524. for ( let j = 0; j <= phiSegments; j ++ ) {
  21525. for ( let i = 0; i <= thetaSegments; i ++ ) {
  21526. // values are generate from the inside of the ring to the outside
  21527. const segment = thetaStart + i / thetaSegments * thetaLength;
  21528. // vertex
  21529. vertex.x = radius * Math.cos( segment );
  21530. vertex.y = radius * Math.sin( segment );
  21531. vertices.push( vertex.x, vertex.y, vertex.z );
  21532. // normal
  21533. normals.push( 0, 0, 1 );
  21534. // uv
  21535. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  21536. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  21537. uvs.push( uv.x, uv.y );
  21538. }
  21539. // increase the radius for next row of vertices
  21540. radius += radiusStep;
  21541. }
  21542. // indices
  21543. for ( let j = 0; j < phiSegments; j ++ ) {
  21544. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  21545. for ( let i = 0; i < thetaSegments; i ++ ) {
  21546. const segment = i + thetaSegmentLevel;
  21547. const a = segment;
  21548. const b = segment + thetaSegments + 1;
  21549. const c = segment + thetaSegments + 2;
  21550. const d = segment + 1;
  21551. // faces
  21552. indices.push( a, b, d );
  21553. indices.push( b, c, d );
  21554. }
  21555. }
  21556. // build geometry
  21557. this.setIndex( indices );
  21558. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21559. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21560. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21561. }
  21562. static fromJSON( data ) {
  21563. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  21564. }
  21565. }
  21566. class ShapeGeometry extends BufferGeometry {
  21567. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  21568. super();
  21569. this.type = 'ShapeGeometry';
  21570. this.parameters = {
  21571. shapes: shapes,
  21572. curveSegments: curveSegments
  21573. };
  21574. // buffers
  21575. const indices = [];
  21576. const vertices = [];
  21577. const normals = [];
  21578. const uvs = [];
  21579. // helper variables
  21580. let groupStart = 0;
  21581. let groupCount = 0;
  21582. // allow single and array values for "shapes" parameter
  21583. if ( Array.isArray( shapes ) === false ) {
  21584. addShape( shapes );
  21585. } else {
  21586. for ( let i = 0; i < shapes.length; i ++ ) {
  21587. addShape( shapes[ i ] );
  21588. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  21589. groupStart += groupCount;
  21590. groupCount = 0;
  21591. }
  21592. }
  21593. // build geometry
  21594. this.setIndex( indices );
  21595. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21596. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21597. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21598. // helper functions
  21599. function addShape( shape ) {
  21600. const indexOffset = vertices.length / 3;
  21601. const points = shape.extractPoints( curveSegments );
  21602. let shapeVertices = points.shape;
  21603. const shapeHoles = points.holes;
  21604. // check direction of vertices
  21605. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  21606. shapeVertices = shapeVertices.reverse();
  21607. }
  21608. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21609. const shapeHole = shapeHoles[ i ];
  21610. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  21611. shapeHoles[ i ] = shapeHole.reverse();
  21612. }
  21613. }
  21614. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  21615. // join vertices of inner and outer paths to a single array
  21616. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21617. const shapeHole = shapeHoles[ i ];
  21618. shapeVertices = shapeVertices.concat( shapeHole );
  21619. }
  21620. // vertices, normals, uvs
  21621. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  21622. const vertex = shapeVertices[ i ];
  21623. vertices.push( vertex.x, vertex.y, 0 );
  21624. normals.push( 0, 0, 1 );
  21625. uvs.push( vertex.x, vertex.y ); // world uvs
  21626. }
  21627. // indices
  21628. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  21629. const face = faces[ i ];
  21630. const a = face[ 0 ] + indexOffset;
  21631. const b = face[ 1 ] + indexOffset;
  21632. const c = face[ 2 ] + indexOffset;
  21633. indices.push( a, b, c );
  21634. groupCount += 3;
  21635. }
  21636. }
  21637. }
  21638. toJSON() {
  21639. const data = super.toJSON();
  21640. const shapes = this.parameters.shapes;
  21641. return toJSON( shapes, data );
  21642. }
  21643. static fromJSON( data, shapes ) {
  21644. const geometryShapes = [];
  21645. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21646. const shape = shapes[ data.shapes[ j ] ];
  21647. geometryShapes.push( shape );
  21648. }
  21649. return new ShapeGeometry( geometryShapes, data.curveSegments );
  21650. }
  21651. }
  21652. function toJSON( shapes, data ) {
  21653. data.shapes = [];
  21654. if ( Array.isArray( shapes ) ) {
  21655. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21656. const shape = shapes[ i ];
  21657. data.shapes.push( shape.uuid );
  21658. }
  21659. } else {
  21660. data.shapes.push( shapes.uuid );
  21661. }
  21662. return data;
  21663. }
  21664. class SphereGeometry extends BufferGeometry {
  21665. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  21666. super();
  21667. this.type = 'SphereGeometry';
  21668. this.parameters = {
  21669. radius: radius,
  21670. widthSegments: widthSegments,
  21671. heightSegments: heightSegments,
  21672. phiStart: phiStart,
  21673. phiLength: phiLength,
  21674. thetaStart: thetaStart,
  21675. thetaLength: thetaLength
  21676. };
  21677. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  21678. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  21679. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  21680. let index = 0;
  21681. const grid = [];
  21682. const vertex = new Vector3();
  21683. const normal = new Vector3();
  21684. // buffers
  21685. const indices = [];
  21686. const vertices = [];
  21687. const normals = [];
  21688. const uvs = [];
  21689. // generate vertices, normals and uvs
  21690. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  21691. const verticesRow = [];
  21692. const v = iy / heightSegments;
  21693. // special case for the poles
  21694. let uOffset = 0;
  21695. if ( iy == 0 && thetaStart == 0 ) {
  21696. uOffset = 0.5 / widthSegments;
  21697. } else if ( iy == heightSegments && thetaEnd == Math.PI ) {
  21698. uOffset = - 0.5 / widthSegments;
  21699. }
  21700. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  21701. const u = ix / widthSegments;
  21702. // vertex
  21703. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21704. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  21705. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21706. vertices.push( vertex.x, vertex.y, vertex.z );
  21707. // normal
  21708. normal.copy( vertex ).normalize();
  21709. normals.push( normal.x, normal.y, normal.z );
  21710. // uv
  21711. uvs.push( u + uOffset, 1 - v );
  21712. verticesRow.push( index ++ );
  21713. }
  21714. grid.push( verticesRow );
  21715. }
  21716. // indices
  21717. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  21718. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  21719. const a = grid[ iy ][ ix + 1 ];
  21720. const b = grid[ iy ][ ix ];
  21721. const c = grid[ iy + 1 ][ ix ];
  21722. const d = grid[ iy + 1 ][ ix + 1 ];
  21723. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  21724. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  21725. }
  21726. }
  21727. // build geometry
  21728. this.setIndex( indices );
  21729. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21730. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21731. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21732. }
  21733. static fromJSON( data ) {
  21734. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  21735. }
  21736. }
  21737. class TetrahedronGeometry extends PolyhedronGeometry {
  21738. constructor( radius = 1, detail = 0 ) {
  21739. const vertices = [
  21740. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  21741. ];
  21742. const indices = [
  21743. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  21744. ];
  21745. super( vertices, indices, radius, detail );
  21746. this.type = 'TetrahedronGeometry';
  21747. this.parameters = {
  21748. radius: radius,
  21749. detail: detail
  21750. };
  21751. }
  21752. static fromJSON( data ) {
  21753. return new TetrahedronGeometry( data.radius, data.detail );
  21754. }
  21755. }
  21756. class TorusGeometry extends BufferGeometry {
  21757. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  21758. super();
  21759. this.type = 'TorusGeometry';
  21760. this.parameters = {
  21761. radius: radius,
  21762. tube: tube,
  21763. radialSegments: radialSegments,
  21764. tubularSegments: tubularSegments,
  21765. arc: arc
  21766. };
  21767. radialSegments = Math.floor( radialSegments );
  21768. tubularSegments = Math.floor( tubularSegments );
  21769. // buffers
  21770. const indices = [];
  21771. const vertices = [];
  21772. const normals = [];
  21773. const uvs = [];
  21774. // helper variables
  21775. const center = new Vector3();
  21776. const vertex = new Vector3();
  21777. const normal = new Vector3();
  21778. // generate vertices, normals and uvs
  21779. for ( let j = 0; j <= radialSegments; j ++ ) {
  21780. for ( let i = 0; i <= tubularSegments; i ++ ) {
  21781. const u = i / tubularSegments * arc;
  21782. const v = j / radialSegments * Math.PI * 2;
  21783. // vertex
  21784. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  21785. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  21786. vertex.z = tube * Math.sin( v );
  21787. vertices.push( vertex.x, vertex.y, vertex.z );
  21788. // normal
  21789. center.x = radius * Math.cos( u );
  21790. center.y = radius * Math.sin( u );
  21791. normal.subVectors( vertex, center ).normalize();
  21792. normals.push( normal.x, normal.y, normal.z );
  21793. // uv
  21794. uvs.push( i / tubularSegments );
  21795. uvs.push( j / radialSegments );
  21796. }
  21797. }
  21798. // generate indices
  21799. for ( let j = 1; j <= radialSegments; j ++ ) {
  21800. for ( let i = 1; i <= tubularSegments; i ++ ) {
  21801. // indices
  21802. const a = ( tubularSegments + 1 ) * j + i - 1;
  21803. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  21804. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  21805. const d = ( tubularSegments + 1 ) * j + i;
  21806. // faces
  21807. indices.push( a, b, d );
  21808. indices.push( b, c, d );
  21809. }
  21810. }
  21811. // build geometry
  21812. this.setIndex( indices );
  21813. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21814. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21815. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21816. }
  21817. static fromJSON( data ) {
  21818. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  21819. }
  21820. }
  21821. class TorusKnotGeometry extends BufferGeometry {
  21822. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  21823. super();
  21824. this.type = 'TorusKnotGeometry';
  21825. this.parameters = {
  21826. radius: radius,
  21827. tube: tube,
  21828. tubularSegments: tubularSegments,
  21829. radialSegments: radialSegments,
  21830. p: p,
  21831. q: q
  21832. };
  21833. tubularSegments = Math.floor( tubularSegments );
  21834. radialSegments = Math.floor( radialSegments );
  21835. // buffers
  21836. const indices = [];
  21837. const vertices = [];
  21838. const normals = [];
  21839. const uvs = [];
  21840. // helper variables
  21841. const vertex = new Vector3();
  21842. const normal = new Vector3();
  21843. const P1 = new Vector3();
  21844. const P2 = new Vector3();
  21845. const B = new Vector3();
  21846. const T = new Vector3();
  21847. const N = new Vector3();
  21848. // generate vertices, normals and uvs
  21849. for ( let i = 0; i <= tubularSegments; ++ i ) {
  21850. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  21851. const u = i / tubularSegments * p * Math.PI * 2;
  21852. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  21853. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  21854. calculatePositionOnCurve( u, p, q, radius, P1 );
  21855. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  21856. // calculate orthonormal basis
  21857. T.subVectors( P2, P1 );
  21858. N.addVectors( P2, P1 );
  21859. B.crossVectors( T, N );
  21860. N.crossVectors( B, T );
  21861. // normalize B, N. T can be ignored, we don't use it
  21862. B.normalize();
  21863. N.normalize();
  21864. for ( let j = 0; j <= radialSegments; ++ j ) {
  21865. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  21866. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  21867. const v = j / radialSegments * Math.PI * 2;
  21868. const cx = - tube * Math.cos( v );
  21869. const cy = tube * Math.sin( v );
  21870. // now calculate the final vertex position.
  21871. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  21872. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  21873. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  21874. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  21875. vertices.push( vertex.x, vertex.y, vertex.z );
  21876. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  21877. normal.subVectors( vertex, P1 ).normalize();
  21878. normals.push( normal.x, normal.y, normal.z );
  21879. // uv
  21880. uvs.push( i / tubularSegments );
  21881. uvs.push( j / radialSegments );
  21882. }
  21883. }
  21884. // generate indices
  21885. for ( let j = 1; j <= tubularSegments; j ++ ) {
  21886. for ( let i = 1; i <= radialSegments; i ++ ) {
  21887. // indices
  21888. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  21889. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  21890. const c = ( radialSegments + 1 ) * j + i;
  21891. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  21892. // faces
  21893. indices.push( a, b, d );
  21894. indices.push( b, c, d );
  21895. }
  21896. }
  21897. // build geometry
  21898. this.setIndex( indices );
  21899. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21900. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21901. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21902. // this function calculates the current position on the torus curve
  21903. function calculatePositionOnCurve( u, p, q, radius, position ) {
  21904. const cu = Math.cos( u );
  21905. const su = Math.sin( u );
  21906. const quOverP = q / p * u;
  21907. const cs = Math.cos( quOverP );
  21908. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  21909. position.y = radius * ( 2 + cs ) * su * 0.5;
  21910. position.z = radius * Math.sin( quOverP ) * 0.5;
  21911. }
  21912. }
  21913. static fromJSON( data ) {
  21914. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  21915. }
  21916. }
  21917. class TubeGeometry extends BufferGeometry {
  21918. 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 ) {
  21919. super();
  21920. this.type = 'TubeGeometry';
  21921. this.parameters = {
  21922. path: path,
  21923. tubularSegments: tubularSegments,
  21924. radius: radius,
  21925. radialSegments: radialSegments,
  21926. closed: closed
  21927. };
  21928. const frames = path.computeFrenetFrames( tubularSegments, closed );
  21929. // expose internals
  21930. this.tangents = frames.tangents;
  21931. this.normals = frames.normals;
  21932. this.binormals = frames.binormals;
  21933. // helper variables
  21934. const vertex = new Vector3();
  21935. const normal = new Vector3();
  21936. const uv = new Vector2();
  21937. let P = new Vector3();
  21938. // buffer
  21939. const vertices = [];
  21940. const normals = [];
  21941. const uvs = [];
  21942. const indices = [];
  21943. // create buffer data
  21944. generateBufferData();
  21945. // build geometry
  21946. this.setIndex( indices );
  21947. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21948. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21949. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21950. // functions
  21951. function generateBufferData() {
  21952. for ( let i = 0; i < tubularSegments; i ++ ) {
  21953. generateSegment( i );
  21954. }
  21955. // if the geometry is not closed, generate the last row of vertices and normals
  21956. // at the regular position on the given path
  21957. //
  21958. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  21959. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  21960. // uvs are generated in a separate function.
  21961. // this makes it easy compute correct values for closed geometries
  21962. generateUVs();
  21963. // finally create faces
  21964. generateIndices();
  21965. }
  21966. function generateSegment( i ) {
  21967. // we use getPointAt to sample evenly distributed points from the given path
  21968. P = path.getPointAt( i / tubularSegments, P );
  21969. // retrieve corresponding normal and binormal
  21970. const N = frames.normals[ i ];
  21971. const B = frames.binormals[ i ];
  21972. // generate normals and vertices for the current segment
  21973. for ( let j = 0; j <= radialSegments; j ++ ) {
  21974. const v = j / radialSegments * Math.PI * 2;
  21975. const sin = Math.sin( v );
  21976. const cos = - Math.cos( v );
  21977. // normal
  21978. normal.x = ( cos * N.x + sin * B.x );
  21979. normal.y = ( cos * N.y + sin * B.y );
  21980. normal.z = ( cos * N.z + sin * B.z );
  21981. normal.normalize();
  21982. normals.push( normal.x, normal.y, normal.z );
  21983. // vertex
  21984. vertex.x = P.x + radius * normal.x;
  21985. vertex.y = P.y + radius * normal.y;
  21986. vertex.z = P.z + radius * normal.z;
  21987. vertices.push( vertex.x, vertex.y, vertex.z );
  21988. }
  21989. }
  21990. function generateIndices() {
  21991. for ( let j = 1; j <= tubularSegments; j ++ ) {
  21992. for ( let i = 1; i <= radialSegments; i ++ ) {
  21993. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  21994. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  21995. const c = ( radialSegments + 1 ) * j + i;
  21996. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  21997. // faces
  21998. indices.push( a, b, d );
  21999. indices.push( b, c, d );
  22000. }
  22001. }
  22002. }
  22003. function generateUVs() {
  22004. for ( let i = 0; i <= tubularSegments; i ++ ) {
  22005. for ( let j = 0; j <= radialSegments; j ++ ) {
  22006. uv.x = i / tubularSegments;
  22007. uv.y = j / radialSegments;
  22008. uvs.push( uv.x, uv.y );
  22009. }
  22010. }
  22011. }
  22012. }
  22013. toJSON() {
  22014. const data = super.toJSON();
  22015. data.path = this.parameters.path.toJSON();
  22016. return data;
  22017. }
  22018. static fromJSON( data ) {
  22019. // This only works for built-in curves (e.g. CatmullRomCurve3).
  22020. // User defined curves or instances of CurvePath will not be deserialized.
  22021. return new TubeGeometry(
  22022. new Curves[ data.path.type ]().fromJSON( data.path ),
  22023. data.tubularSegments,
  22024. data.radius,
  22025. data.radialSegments,
  22026. data.closed
  22027. );
  22028. }
  22029. }
  22030. class WireframeGeometry extends BufferGeometry {
  22031. constructor( geometry = null ) {
  22032. super();
  22033. this.type = 'WireframeGeometry';
  22034. this.parameters = {
  22035. geometry: geometry
  22036. };
  22037. if ( geometry !== null ) {
  22038. // buffer
  22039. const vertices = [];
  22040. const edges = new Set();
  22041. // helper variables
  22042. const start = new Vector3();
  22043. const end = new Vector3();
  22044. if ( geometry.index !== null ) {
  22045. // indexed BufferGeometry
  22046. const position = geometry.attributes.position;
  22047. const indices = geometry.index;
  22048. let groups = geometry.groups;
  22049. if ( groups.length === 0 ) {
  22050. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  22051. }
  22052. // create a data structure that contains all edges without duplicates
  22053. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  22054. const group = groups[ o ];
  22055. const groupStart = group.start;
  22056. const groupCount = group.count;
  22057. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  22058. for ( let j = 0; j < 3; j ++ ) {
  22059. const index1 = indices.getX( i + j );
  22060. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  22061. start.fromBufferAttribute( position, index1 );
  22062. end.fromBufferAttribute( position, index2 );
  22063. if ( isUniqueEdge( start, end, edges ) === true ) {
  22064. vertices.push( start.x, start.y, start.z );
  22065. vertices.push( end.x, end.y, end.z );
  22066. }
  22067. }
  22068. }
  22069. }
  22070. } else {
  22071. // non-indexed BufferGeometry
  22072. const position = geometry.attributes.position;
  22073. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  22074. for ( let j = 0; j < 3; j ++ ) {
  22075. // three edges per triangle, an edge is represented as (index1, index2)
  22076. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  22077. const index1 = 3 * i + j;
  22078. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  22079. start.fromBufferAttribute( position, index1 );
  22080. end.fromBufferAttribute( position, index2 );
  22081. if ( isUniqueEdge( start, end, edges ) === true ) {
  22082. vertices.push( start.x, start.y, start.z );
  22083. vertices.push( end.x, end.y, end.z );
  22084. }
  22085. }
  22086. }
  22087. }
  22088. // build geometry
  22089. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22090. }
  22091. }
  22092. }
  22093. function isUniqueEdge( start, end, edges ) {
  22094. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  22095. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  22096. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  22097. return false;
  22098. } else {
  22099. edges.add( hash1 );
  22100. edges.add( hash2 );
  22101. return true;
  22102. }
  22103. }
  22104. var Geometries = /*#__PURE__*/Object.freeze({
  22105. __proto__: null,
  22106. BoxGeometry: BoxGeometry,
  22107. CapsuleGeometry: CapsuleGeometry,
  22108. CircleGeometry: CircleGeometry,
  22109. ConeGeometry: ConeGeometry,
  22110. CylinderGeometry: CylinderGeometry,
  22111. DodecahedronGeometry: DodecahedronGeometry,
  22112. EdgesGeometry: EdgesGeometry,
  22113. ExtrudeGeometry: ExtrudeGeometry,
  22114. IcosahedronGeometry: IcosahedronGeometry,
  22115. LatheGeometry: LatheGeometry,
  22116. OctahedronGeometry: OctahedronGeometry,
  22117. PlaneGeometry: PlaneGeometry,
  22118. PolyhedronGeometry: PolyhedronGeometry,
  22119. RingGeometry: RingGeometry,
  22120. ShapeGeometry: ShapeGeometry,
  22121. SphereGeometry: SphereGeometry,
  22122. TetrahedronGeometry: TetrahedronGeometry,
  22123. TorusGeometry: TorusGeometry,
  22124. TorusKnotGeometry: TorusKnotGeometry,
  22125. TubeGeometry: TubeGeometry,
  22126. WireframeGeometry: WireframeGeometry
  22127. });
  22128. class ShadowMaterial extends Material {
  22129. constructor( parameters ) {
  22130. super();
  22131. this.isShadowMaterial = true;
  22132. this.type = 'ShadowMaterial';
  22133. this.color = new Color( 0x000000 );
  22134. this.transparent = true;
  22135. this.fog = true;
  22136. this.setValues( parameters );
  22137. }
  22138. copy( source ) {
  22139. super.copy( source );
  22140. this.color.copy( source.color );
  22141. this.fog = source.fog;
  22142. return this;
  22143. }
  22144. }
  22145. class RawShaderMaterial extends ShaderMaterial {
  22146. constructor( parameters ) {
  22147. super( parameters );
  22148. this.isRawShaderMaterial = true;
  22149. this.type = 'RawShaderMaterial';
  22150. }
  22151. }
  22152. class MeshStandardMaterial extends Material {
  22153. constructor( parameters ) {
  22154. super();
  22155. this.isMeshStandardMaterial = true;
  22156. this.defines = { 'STANDARD': '' };
  22157. this.type = 'MeshStandardMaterial';
  22158. this.color = new Color( 0xffffff ); // diffuse
  22159. this.roughness = 1.0;
  22160. this.metalness = 0.0;
  22161. this.map = null;
  22162. this.lightMap = null;
  22163. this.lightMapIntensity = 1.0;
  22164. this.aoMap = null;
  22165. this.aoMapIntensity = 1.0;
  22166. this.emissive = new Color( 0x000000 );
  22167. this.emissiveIntensity = 1.0;
  22168. this.emissiveMap = null;
  22169. this.bumpMap = null;
  22170. this.bumpScale = 1;
  22171. this.normalMap = null;
  22172. this.normalMapType = TangentSpaceNormalMap;
  22173. this.normalScale = new Vector2( 1, 1 );
  22174. this.displacementMap = null;
  22175. this.displacementScale = 1;
  22176. this.displacementBias = 0;
  22177. this.roughnessMap = null;
  22178. this.metalnessMap = null;
  22179. this.alphaMap = null;
  22180. this.envMap = null;
  22181. this.envMapIntensity = 1.0;
  22182. this.wireframe = false;
  22183. this.wireframeLinewidth = 1;
  22184. this.wireframeLinecap = 'round';
  22185. this.wireframeLinejoin = 'round';
  22186. this.flatShading = false;
  22187. this.fog = true;
  22188. this.setValues( parameters );
  22189. }
  22190. copy( source ) {
  22191. super.copy( source );
  22192. this.defines = { 'STANDARD': '' };
  22193. this.color.copy( source.color );
  22194. this.roughness = source.roughness;
  22195. this.metalness = source.metalness;
  22196. this.map = source.map;
  22197. this.lightMap = source.lightMap;
  22198. this.lightMapIntensity = source.lightMapIntensity;
  22199. this.aoMap = source.aoMap;
  22200. this.aoMapIntensity = source.aoMapIntensity;
  22201. this.emissive.copy( source.emissive );
  22202. this.emissiveMap = source.emissiveMap;
  22203. this.emissiveIntensity = source.emissiveIntensity;
  22204. this.bumpMap = source.bumpMap;
  22205. this.bumpScale = source.bumpScale;
  22206. this.normalMap = source.normalMap;
  22207. this.normalMapType = source.normalMapType;
  22208. this.normalScale.copy( source.normalScale );
  22209. this.displacementMap = source.displacementMap;
  22210. this.displacementScale = source.displacementScale;
  22211. this.displacementBias = source.displacementBias;
  22212. this.roughnessMap = source.roughnessMap;
  22213. this.metalnessMap = source.metalnessMap;
  22214. this.alphaMap = source.alphaMap;
  22215. this.envMap = source.envMap;
  22216. this.envMapIntensity = source.envMapIntensity;
  22217. this.wireframe = source.wireframe;
  22218. this.wireframeLinewidth = source.wireframeLinewidth;
  22219. this.wireframeLinecap = source.wireframeLinecap;
  22220. this.wireframeLinejoin = source.wireframeLinejoin;
  22221. this.flatShading = source.flatShading;
  22222. this.fog = source.fog;
  22223. return this;
  22224. }
  22225. }
  22226. class MeshPhysicalMaterial extends MeshStandardMaterial {
  22227. constructor( parameters ) {
  22228. super();
  22229. this.isMeshPhysicalMaterial = true;
  22230. this.defines = {
  22231. 'STANDARD': '',
  22232. 'PHYSICAL': ''
  22233. };
  22234. this.type = 'MeshPhysicalMaterial';
  22235. this.clearcoatMap = null;
  22236. this.clearcoatRoughness = 0.0;
  22237. this.clearcoatRoughnessMap = null;
  22238. this.clearcoatNormalScale = new Vector2( 1, 1 );
  22239. this.clearcoatNormalMap = null;
  22240. this.ior = 1.5;
  22241. Object.defineProperty( this, 'reflectivity', {
  22242. get: function () {
  22243. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  22244. },
  22245. set: function ( reflectivity ) {
  22246. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  22247. }
  22248. } );
  22249. this.iridescenceMap = null;
  22250. this.iridescenceIOR = 1.3;
  22251. this.iridescenceThicknessRange = [ 100, 400 ];
  22252. this.iridescenceThicknessMap = null;
  22253. this.sheenColor = new Color( 0x000000 );
  22254. this.sheenColorMap = null;
  22255. this.sheenRoughness = 1.0;
  22256. this.sheenRoughnessMap = null;
  22257. this.transmissionMap = null;
  22258. this.thickness = 0;
  22259. this.thicknessMap = null;
  22260. this.attenuationDistance = Infinity;
  22261. this.attenuationColor = new Color( 1, 1, 1 );
  22262. this.specularIntensity = 1.0;
  22263. this.specularIntensityMap = null;
  22264. this.specularColor = new Color( 1, 1, 1 );
  22265. this.specularColorMap = null;
  22266. this._sheen = 0.0;
  22267. this._clearcoat = 0;
  22268. this._iridescence = 0;
  22269. this._transmission = 0;
  22270. this.setValues( parameters );
  22271. }
  22272. get sheen() {
  22273. return this._sheen;
  22274. }
  22275. set sheen( value ) {
  22276. if ( this._sheen > 0 !== value > 0 ) {
  22277. this.version ++;
  22278. }
  22279. this._sheen = value;
  22280. }
  22281. get clearcoat() {
  22282. return this._clearcoat;
  22283. }
  22284. set clearcoat( value ) {
  22285. if ( this._clearcoat > 0 !== value > 0 ) {
  22286. this.version ++;
  22287. }
  22288. this._clearcoat = value;
  22289. }
  22290. get iridescence() {
  22291. return this._iridescence;
  22292. }
  22293. set iridescence( value ) {
  22294. if ( this._iridescence > 0 !== value > 0 ) {
  22295. this.version ++;
  22296. }
  22297. this._iridescence = value;
  22298. }
  22299. get transmission() {
  22300. return this._transmission;
  22301. }
  22302. set transmission( value ) {
  22303. if ( this._transmission > 0 !== value > 0 ) {
  22304. this.version ++;
  22305. }
  22306. this._transmission = value;
  22307. }
  22308. copy( source ) {
  22309. super.copy( source );
  22310. this.defines = {
  22311. 'STANDARD': '',
  22312. 'PHYSICAL': ''
  22313. };
  22314. this.clearcoat = source.clearcoat;
  22315. this.clearcoatMap = source.clearcoatMap;
  22316. this.clearcoatRoughness = source.clearcoatRoughness;
  22317. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  22318. this.clearcoatNormalMap = source.clearcoatNormalMap;
  22319. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  22320. this.ior = source.ior;
  22321. this.iridescence = source.iridescence;
  22322. this.iridescenceMap = source.iridescenceMap;
  22323. this.iridescenceIOR = source.iridescenceIOR;
  22324. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  22325. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  22326. this.sheen = source.sheen;
  22327. this.sheenColor.copy( source.sheenColor );
  22328. this.sheenColorMap = source.sheenColorMap;
  22329. this.sheenRoughness = source.sheenRoughness;
  22330. this.sheenRoughnessMap = source.sheenRoughnessMap;
  22331. this.transmission = source.transmission;
  22332. this.transmissionMap = source.transmissionMap;
  22333. this.thickness = source.thickness;
  22334. this.thicknessMap = source.thicknessMap;
  22335. this.attenuationDistance = source.attenuationDistance;
  22336. this.attenuationColor.copy( source.attenuationColor );
  22337. this.specularIntensity = source.specularIntensity;
  22338. this.specularIntensityMap = source.specularIntensityMap;
  22339. this.specularColor.copy( source.specularColor );
  22340. this.specularColorMap = source.specularColorMap;
  22341. return this;
  22342. }
  22343. }
  22344. class MeshPhongMaterial extends Material {
  22345. constructor( parameters ) {
  22346. super();
  22347. this.isMeshPhongMaterial = true;
  22348. this.type = 'MeshPhongMaterial';
  22349. this.color = new Color( 0xffffff ); // diffuse
  22350. this.specular = new Color( 0x111111 );
  22351. this.shininess = 30;
  22352. this.map = null;
  22353. this.lightMap = null;
  22354. this.lightMapIntensity = 1.0;
  22355. this.aoMap = null;
  22356. this.aoMapIntensity = 1.0;
  22357. this.emissive = new Color( 0x000000 );
  22358. this.emissiveIntensity = 1.0;
  22359. this.emissiveMap = null;
  22360. this.bumpMap = null;
  22361. this.bumpScale = 1;
  22362. this.normalMap = null;
  22363. this.normalMapType = TangentSpaceNormalMap;
  22364. this.normalScale = new Vector2( 1, 1 );
  22365. this.displacementMap = null;
  22366. this.displacementScale = 1;
  22367. this.displacementBias = 0;
  22368. this.specularMap = null;
  22369. this.alphaMap = null;
  22370. this.envMap = null;
  22371. this.combine = MultiplyOperation;
  22372. this.reflectivity = 1;
  22373. this.refractionRatio = 0.98;
  22374. this.wireframe = false;
  22375. this.wireframeLinewidth = 1;
  22376. this.wireframeLinecap = 'round';
  22377. this.wireframeLinejoin = 'round';
  22378. this.flatShading = false;
  22379. this.fog = true;
  22380. this.setValues( parameters );
  22381. }
  22382. copy( source ) {
  22383. super.copy( source );
  22384. this.color.copy( source.color );
  22385. this.specular.copy( source.specular );
  22386. this.shininess = source.shininess;
  22387. this.map = source.map;
  22388. this.lightMap = source.lightMap;
  22389. this.lightMapIntensity = source.lightMapIntensity;
  22390. this.aoMap = source.aoMap;
  22391. this.aoMapIntensity = source.aoMapIntensity;
  22392. this.emissive.copy( source.emissive );
  22393. this.emissiveMap = source.emissiveMap;
  22394. this.emissiveIntensity = source.emissiveIntensity;
  22395. this.bumpMap = source.bumpMap;
  22396. this.bumpScale = source.bumpScale;
  22397. this.normalMap = source.normalMap;
  22398. this.normalMapType = source.normalMapType;
  22399. this.normalScale.copy( source.normalScale );
  22400. this.displacementMap = source.displacementMap;
  22401. this.displacementScale = source.displacementScale;
  22402. this.displacementBias = source.displacementBias;
  22403. this.specularMap = source.specularMap;
  22404. this.alphaMap = source.alphaMap;
  22405. this.envMap = source.envMap;
  22406. this.combine = source.combine;
  22407. this.reflectivity = source.reflectivity;
  22408. this.refractionRatio = source.refractionRatio;
  22409. this.wireframe = source.wireframe;
  22410. this.wireframeLinewidth = source.wireframeLinewidth;
  22411. this.wireframeLinecap = source.wireframeLinecap;
  22412. this.wireframeLinejoin = source.wireframeLinejoin;
  22413. this.flatShading = source.flatShading;
  22414. this.fog = source.fog;
  22415. return this;
  22416. }
  22417. }
  22418. class MeshToonMaterial extends Material {
  22419. constructor( parameters ) {
  22420. super();
  22421. this.isMeshToonMaterial = true;
  22422. this.defines = { 'TOON': '' };
  22423. this.type = 'MeshToonMaterial';
  22424. this.color = new Color( 0xffffff );
  22425. this.map = null;
  22426. this.gradientMap = null;
  22427. this.lightMap = null;
  22428. this.lightMapIntensity = 1.0;
  22429. this.aoMap = null;
  22430. this.aoMapIntensity = 1.0;
  22431. this.emissive = new Color( 0x000000 );
  22432. this.emissiveIntensity = 1.0;
  22433. this.emissiveMap = null;
  22434. this.bumpMap = null;
  22435. this.bumpScale = 1;
  22436. this.normalMap = null;
  22437. this.normalMapType = TangentSpaceNormalMap;
  22438. this.normalScale = new Vector2( 1, 1 );
  22439. this.displacementMap = null;
  22440. this.displacementScale = 1;
  22441. this.displacementBias = 0;
  22442. this.alphaMap = null;
  22443. this.wireframe = false;
  22444. this.wireframeLinewidth = 1;
  22445. this.wireframeLinecap = 'round';
  22446. this.wireframeLinejoin = 'round';
  22447. this.fog = true;
  22448. this.setValues( parameters );
  22449. }
  22450. copy( source ) {
  22451. super.copy( source );
  22452. this.color.copy( source.color );
  22453. this.map = source.map;
  22454. this.gradientMap = source.gradientMap;
  22455. this.lightMap = source.lightMap;
  22456. this.lightMapIntensity = source.lightMapIntensity;
  22457. this.aoMap = source.aoMap;
  22458. this.aoMapIntensity = source.aoMapIntensity;
  22459. this.emissive.copy( source.emissive );
  22460. this.emissiveMap = source.emissiveMap;
  22461. this.emissiveIntensity = source.emissiveIntensity;
  22462. this.bumpMap = source.bumpMap;
  22463. this.bumpScale = source.bumpScale;
  22464. this.normalMap = source.normalMap;
  22465. this.normalMapType = source.normalMapType;
  22466. this.normalScale.copy( source.normalScale );
  22467. this.displacementMap = source.displacementMap;
  22468. this.displacementScale = source.displacementScale;
  22469. this.displacementBias = source.displacementBias;
  22470. this.alphaMap = source.alphaMap;
  22471. this.wireframe = source.wireframe;
  22472. this.wireframeLinewidth = source.wireframeLinewidth;
  22473. this.wireframeLinecap = source.wireframeLinecap;
  22474. this.wireframeLinejoin = source.wireframeLinejoin;
  22475. this.fog = source.fog;
  22476. return this;
  22477. }
  22478. }
  22479. class MeshNormalMaterial extends Material {
  22480. constructor( parameters ) {
  22481. super();
  22482. this.isMeshNormalMaterial = true;
  22483. this.type = 'MeshNormalMaterial';
  22484. this.bumpMap = null;
  22485. this.bumpScale = 1;
  22486. this.normalMap = null;
  22487. this.normalMapType = TangentSpaceNormalMap;
  22488. this.normalScale = new Vector2( 1, 1 );
  22489. this.displacementMap = null;
  22490. this.displacementScale = 1;
  22491. this.displacementBias = 0;
  22492. this.wireframe = false;
  22493. this.wireframeLinewidth = 1;
  22494. this.flatShading = false;
  22495. this.setValues( parameters );
  22496. }
  22497. copy( source ) {
  22498. super.copy( source );
  22499. this.bumpMap = source.bumpMap;
  22500. this.bumpScale = source.bumpScale;
  22501. this.normalMap = source.normalMap;
  22502. this.normalMapType = source.normalMapType;
  22503. this.normalScale.copy( source.normalScale );
  22504. this.displacementMap = source.displacementMap;
  22505. this.displacementScale = source.displacementScale;
  22506. this.displacementBias = source.displacementBias;
  22507. this.wireframe = source.wireframe;
  22508. this.wireframeLinewidth = source.wireframeLinewidth;
  22509. this.flatShading = source.flatShading;
  22510. return this;
  22511. }
  22512. }
  22513. class MeshLambertMaterial extends Material {
  22514. constructor( parameters ) {
  22515. super();
  22516. this.isMeshLambertMaterial = true;
  22517. this.type = 'MeshLambertMaterial';
  22518. this.color = new Color( 0xffffff ); // diffuse
  22519. this.map = null;
  22520. this.lightMap = null;
  22521. this.lightMapIntensity = 1.0;
  22522. this.aoMap = null;
  22523. this.aoMapIntensity = 1.0;
  22524. this.emissive = new Color( 0x000000 );
  22525. this.emissiveIntensity = 1.0;
  22526. this.emissiveMap = null;
  22527. this.bumpMap = null;
  22528. this.bumpScale = 1;
  22529. this.normalMap = null;
  22530. this.normalMapType = TangentSpaceNormalMap;
  22531. this.normalScale = new Vector2( 1, 1 );
  22532. this.displacementMap = null;
  22533. this.displacementScale = 1;
  22534. this.displacementBias = 0;
  22535. this.specularMap = null;
  22536. this.alphaMap = null;
  22537. this.envMap = null;
  22538. this.combine = MultiplyOperation;
  22539. this.reflectivity = 1;
  22540. this.refractionRatio = 0.98;
  22541. this.wireframe = false;
  22542. this.wireframeLinewidth = 1;
  22543. this.wireframeLinecap = 'round';
  22544. this.wireframeLinejoin = 'round';
  22545. this.flatShading = false;
  22546. this.fog = true;
  22547. this.setValues( parameters );
  22548. }
  22549. copy( source ) {
  22550. super.copy( source );
  22551. this.color.copy( source.color );
  22552. this.map = source.map;
  22553. this.lightMap = source.lightMap;
  22554. this.lightMapIntensity = source.lightMapIntensity;
  22555. this.aoMap = source.aoMap;
  22556. this.aoMapIntensity = source.aoMapIntensity;
  22557. this.emissive.copy( source.emissive );
  22558. this.emissiveMap = source.emissiveMap;
  22559. this.emissiveIntensity = source.emissiveIntensity;
  22560. this.bumpMap = source.bumpMap;
  22561. this.bumpScale = source.bumpScale;
  22562. this.normalMap = source.normalMap;
  22563. this.normalMapType = source.normalMapType;
  22564. this.normalScale.copy( source.normalScale );
  22565. this.displacementMap = source.displacementMap;
  22566. this.displacementScale = source.displacementScale;
  22567. this.displacementBias = source.displacementBias;
  22568. this.specularMap = source.specularMap;
  22569. this.alphaMap = source.alphaMap;
  22570. this.envMap = source.envMap;
  22571. this.combine = source.combine;
  22572. this.reflectivity = source.reflectivity;
  22573. this.refractionRatio = source.refractionRatio;
  22574. this.wireframe = source.wireframe;
  22575. this.wireframeLinewidth = source.wireframeLinewidth;
  22576. this.wireframeLinecap = source.wireframeLinecap;
  22577. this.wireframeLinejoin = source.wireframeLinejoin;
  22578. this.flatShading = source.flatShading;
  22579. this.fog = source.fog;
  22580. return this;
  22581. }
  22582. }
  22583. class MeshMatcapMaterial extends Material {
  22584. constructor( parameters ) {
  22585. super();
  22586. this.isMeshMatcapMaterial = true;
  22587. this.defines = { 'MATCAP': '' };
  22588. this.type = 'MeshMatcapMaterial';
  22589. this.color = new Color( 0xffffff ); // diffuse
  22590. this.matcap = null;
  22591. this.map = null;
  22592. this.bumpMap = null;
  22593. this.bumpScale = 1;
  22594. this.normalMap = null;
  22595. this.normalMapType = TangentSpaceNormalMap;
  22596. this.normalScale = new Vector2( 1, 1 );
  22597. this.displacementMap = null;
  22598. this.displacementScale = 1;
  22599. this.displacementBias = 0;
  22600. this.alphaMap = null;
  22601. this.flatShading = false;
  22602. this.fog = true;
  22603. this.setValues( parameters );
  22604. }
  22605. copy( source ) {
  22606. super.copy( source );
  22607. this.defines = { 'MATCAP': '' };
  22608. this.color.copy( source.color );
  22609. this.matcap = source.matcap;
  22610. this.map = source.map;
  22611. this.bumpMap = source.bumpMap;
  22612. this.bumpScale = source.bumpScale;
  22613. this.normalMap = source.normalMap;
  22614. this.normalMapType = source.normalMapType;
  22615. this.normalScale.copy( source.normalScale );
  22616. this.displacementMap = source.displacementMap;
  22617. this.displacementScale = source.displacementScale;
  22618. this.displacementBias = source.displacementBias;
  22619. this.alphaMap = source.alphaMap;
  22620. this.flatShading = source.flatShading;
  22621. this.fog = source.fog;
  22622. return this;
  22623. }
  22624. }
  22625. class LineDashedMaterial extends LineBasicMaterial {
  22626. constructor( parameters ) {
  22627. super();
  22628. this.isLineDashedMaterial = true;
  22629. this.type = 'LineDashedMaterial';
  22630. this.scale = 1;
  22631. this.dashSize = 3;
  22632. this.gapSize = 1;
  22633. this.setValues( parameters );
  22634. }
  22635. copy( source ) {
  22636. super.copy( source );
  22637. this.scale = source.scale;
  22638. this.dashSize = source.dashSize;
  22639. this.gapSize = source.gapSize;
  22640. return this;
  22641. }
  22642. }
  22643. // same as Array.prototype.slice, but also works on typed arrays
  22644. function arraySlice( array, from, to ) {
  22645. if ( isTypedArray( array ) ) {
  22646. // in ios9 array.subarray(from, undefined) will return empty array
  22647. // but array.subarray(from) or array.subarray(from, len) is correct
  22648. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  22649. }
  22650. return array.slice( from, to );
  22651. }
  22652. // converts an array to a specific type
  22653. function convertArray( array, type, forceClone ) {
  22654. if ( ! array || // let 'undefined' and 'null' pass
  22655. ! forceClone && array.constructor === type ) return array;
  22656. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  22657. return new type( array ); // create typed array
  22658. }
  22659. return Array.prototype.slice.call( array ); // create Array
  22660. }
  22661. function isTypedArray( object ) {
  22662. return ArrayBuffer.isView( object ) &&
  22663. ! ( object instanceof DataView );
  22664. }
  22665. // returns an array by which times and values can be sorted
  22666. function getKeyframeOrder( times ) {
  22667. function compareTime( i, j ) {
  22668. return times[ i ] - times[ j ];
  22669. }
  22670. const n = times.length;
  22671. const result = new Array( n );
  22672. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  22673. result.sort( compareTime );
  22674. return result;
  22675. }
  22676. // uses the array previously returned by 'getKeyframeOrder' to sort data
  22677. function sortedArray( values, stride, order ) {
  22678. const nValues = values.length;
  22679. const result = new values.constructor( nValues );
  22680. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  22681. const srcOffset = order[ i ] * stride;
  22682. for ( let j = 0; j !== stride; ++ j ) {
  22683. result[ dstOffset ++ ] = values[ srcOffset + j ];
  22684. }
  22685. }
  22686. return result;
  22687. }
  22688. // function for parsing AOS keyframe formats
  22689. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  22690. let i = 1, key = jsonKeys[ 0 ];
  22691. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  22692. key = jsonKeys[ i ++ ];
  22693. }
  22694. if ( key === undefined ) return; // no data
  22695. let value = key[ valuePropertyName ];
  22696. if ( value === undefined ) return; // no data
  22697. if ( Array.isArray( value ) ) {
  22698. do {
  22699. value = key[ valuePropertyName ];
  22700. if ( value !== undefined ) {
  22701. times.push( key.time );
  22702. values.push.apply( values, value ); // push all elements
  22703. }
  22704. key = jsonKeys[ i ++ ];
  22705. } while ( key !== undefined );
  22706. } else if ( value.toArray !== undefined ) {
  22707. // ...assume THREE.Math-ish
  22708. do {
  22709. value = key[ valuePropertyName ];
  22710. if ( value !== undefined ) {
  22711. times.push( key.time );
  22712. value.toArray( values, values.length );
  22713. }
  22714. key = jsonKeys[ i ++ ];
  22715. } while ( key !== undefined );
  22716. } else {
  22717. // otherwise push as-is
  22718. do {
  22719. value = key[ valuePropertyName ];
  22720. if ( value !== undefined ) {
  22721. times.push( key.time );
  22722. values.push( value );
  22723. }
  22724. key = jsonKeys[ i ++ ];
  22725. } while ( key !== undefined );
  22726. }
  22727. }
  22728. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  22729. const clip = sourceClip.clone();
  22730. clip.name = name;
  22731. const tracks = [];
  22732. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22733. const track = clip.tracks[ i ];
  22734. const valueSize = track.getValueSize();
  22735. const times = [];
  22736. const values = [];
  22737. for ( let j = 0; j < track.times.length; ++ j ) {
  22738. const frame = track.times[ j ] * fps;
  22739. if ( frame < startFrame || frame >= endFrame ) continue;
  22740. times.push( track.times[ j ] );
  22741. for ( let k = 0; k < valueSize; ++ k ) {
  22742. values.push( track.values[ j * valueSize + k ] );
  22743. }
  22744. }
  22745. if ( times.length === 0 ) continue;
  22746. track.times = convertArray( times, track.times.constructor );
  22747. track.values = convertArray( values, track.values.constructor );
  22748. tracks.push( track );
  22749. }
  22750. clip.tracks = tracks;
  22751. // find minimum .times value across all tracks in the trimmed clip
  22752. let minStartTime = Infinity;
  22753. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22754. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  22755. minStartTime = clip.tracks[ i ].times[ 0 ];
  22756. }
  22757. }
  22758. // shift all tracks such that clip begins at t=0
  22759. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22760. clip.tracks[ i ].shift( - 1 * minStartTime );
  22761. }
  22762. clip.resetDuration();
  22763. return clip;
  22764. }
  22765. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  22766. if ( fps <= 0 ) fps = 30;
  22767. const numTracks = referenceClip.tracks.length;
  22768. const referenceTime = referenceFrame / fps;
  22769. // Make each track's values relative to the values at the reference frame
  22770. for ( let i = 0; i < numTracks; ++ i ) {
  22771. const referenceTrack = referenceClip.tracks[ i ];
  22772. const referenceTrackType = referenceTrack.ValueTypeName;
  22773. // Skip this track if it's non-numeric
  22774. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  22775. // Find the track in the target clip whose name and type matches the reference track
  22776. const targetTrack = targetClip.tracks.find( function ( track ) {
  22777. return track.name === referenceTrack.name
  22778. && track.ValueTypeName === referenceTrackType;
  22779. } );
  22780. if ( targetTrack === undefined ) continue;
  22781. let referenceOffset = 0;
  22782. const referenceValueSize = referenceTrack.getValueSize();
  22783. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  22784. referenceOffset = referenceValueSize / 3;
  22785. }
  22786. let targetOffset = 0;
  22787. const targetValueSize = targetTrack.getValueSize();
  22788. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  22789. targetOffset = targetValueSize / 3;
  22790. }
  22791. const lastIndex = referenceTrack.times.length - 1;
  22792. let referenceValue;
  22793. // Find the value to subtract out of the track
  22794. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  22795. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  22796. const startIndex = referenceOffset;
  22797. const endIndex = referenceValueSize - referenceOffset;
  22798. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  22799. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  22800. // Reference frame is after the last keyframe, so just use the last keyframe
  22801. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  22802. const endIndex = startIndex + referenceValueSize - referenceOffset;
  22803. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  22804. } else {
  22805. // Interpolate to the reference value
  22806. const interpolant = referenceTrack.createInterpolant();
  22807. const startIndex = referenceOffset;
  22808. const endIndex = referenceValueSize - referenceOffset;
  22809. interpolant.evaluate( referenceTime );
  22810. referenceValue = arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  22811. }
  22812. // Conjugate the quaternion
  22813. if ( referenceTrackType === 'quaternion' ) {
  22814. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  22815. referenceQuat.toArray( referenceValue );
  22816. }
  22817. // Subtract the reference value from all of the track values
  22818. const numTimes = targetTrack.times.length;
  22819. for ( let j = 0; j < numTimes; ++ j ) {
  22820. const valueStart = j * targetValueSize + targetOffset;
  22821. if ( referenceTrackType === 'quaternion' ) {
  22822. // Multiply the conjugate for quaternion track types
  22823. Quaternion.multiplyQuaternionsFlat(
  22824. targetTrack.values,
  22825. valueStart,
  22826. referenceValue,
  22827. 0,
  22828. targetTrack.values,
  22829. valueStart
  22830. );
  22831. } else {
  22832. const valueEnd = targetValueSize - targetOffset * 2;
  22833. // Subtract each value for all other numeric track types
  22834. for ( let k = 0; k < valueEnd; ++ k ) {
  22835. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  22836. }
  22837. }
  22838. }
  22839. }
  22840. targetClip.blendMode = AdditiveAnimationBlendMode;
  22841. return targetClip;
  22842. }
  22843. var AnimationUtils = /*#__PURE__*/Object.freeze({
  22844. __proto__: null,
  22845. arraySlice: arraySlice,
  22846. convertArray: convertArray,
  22847. flattenJSON: flattenJSON,
  22848. getKeyframeOrder: getKeyframeOrder,
  22849. isTypedArray: isTypedArray,
  22850. makeClipAdditive: makeClipAdditive,
  22851. sortedArray: sortedArray,
  22852. subclip: subclip
  22853. });
  22854. /**
  22855. * Abstract base class of interpolants over parametric samples.
  22856. *
  22857. * The parameter domain is one dimensional, typically the time or a path
  22858. * along a curve defined by the data.
  22859. *
  22860. * The sample values can have any dimensionality and derived classes may
  22861. * apply special interpretations to the data.
  22862. *
  22863. * This class provides the interval seek in a Template Method, deferring
  22864. * the actual interpolation to derived classes.
  22865. *
  22866. * Time complexity is O(1) for linear access crossing at most two points
  22867. * and O(log N) for random access, where N is the number of positions.
  22868. *
  22869. * References:
  22870. *
  22871. * http://www.oodesign.com/template-method-pattern.html
  22872. *
  22873. */
  22874. class Interpolant {
  22875. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22876. this.parameterPositions = parameterPositions;
  22877. this._cachedIndex = 0;
  22878. this.resultBuffer = resultBuffer !== undefined ?
  22879. resultBuffer : new sampleValues.constructor( sampleSize );
  22880. this.sampleValues = sampleValues;
  22881. this.valueSize = sampleSize;
  22882. this.settings = null;
  22883. this.DefaultSettings_ = {};
  22884. }
  22885. evaluate( t ) {
  22886. const pp = this.parameterPositions;
  22887. let i1 = this._cachedIndex,
  22888. t1 = pp[ i1 ],
  22889. t0 = pp[ i1 - 1 ];
  22890. validate_interval: {
  22891. seek: {
  22892. let right;
  22893. linear_scan: {
  22894. //- See http://jsperf.com/comparison-to-undefined/3
  22895. //- slower code:
  22896. //-
  22897. //- if ( t >= t1 || t1 === undefined ) {
  22898. forward_scan: if ( ! ( t < t1 ) ) {
  22899. for ( let giveUpAt = i1 + 2; ; ) {
  22900. if ( t1 === undefined ) {
  22901. if ( t < t0 ) break forward_scan;
  22902. // after end
  22903. i1 = pp.length;
  22904. this._cachedIndex = i1;
  22905. return this.copySampleValue_( i1 - 1 );
  22906. }
  22907. if ( i1 === giveUpAt ) break; // this loop
  22908. t0 = t1;
  22909. t1 = pp[ ++ i1 ];
  22910. if ( t < t1 ) {
  22911. // we have arrived at the sought interval
  22912. break seek;
  22913. }
  22914. }
  22915. // prepare binary search on the right side of the index
  22916. right = pp.length;
  22917. break linear_scan;
  22918. }
  22919. //- slower code:
  22920. //- if ( t < t0 || t0 === undefined ) {
  22921. if ( ! ( t >= t0 ) ) {
  22922. // looping?
  22923. const t1global = pp[ 1 ];
  22924. if ( t < t1global ) {
  22925. i1 = 2; // + 1, using the scan for the details
  22926. t0 = t1global;
  22927. }
  22928. // linear reverse scan
  22929. for ( let giveUpAt = i1 - 2; ; ) {
  22930. if ( t0 === undefined ) {
  22931. // before start
  22932. this._cachedIndex = 0;
  22933. return this.copySampleValue_( 0 );
  22934. }
  22935. if ( i1 === giveUpAt ) break; // this loop
  22936. t1 = t0;
  22937. t0 = pp[ -- i1 - 1 ];
  22938. if ( t >= t0 ) {
  22939. // we have arrived at the sought interval
  22940. break seek;
  22941. }
  22942. }
  22943. // prepare binary search on the left side of the index
  22944. right = i1;
  22945. i1 = 0;
  22946. break linear_scan;
  22947. }
  22948. // the interval is valid
  22949. break validate_interval;
  22950. } // linear scan
  22951. // binary search
  22952. while ( i1 < right ) {
  22953. const mid = ( i1 + right ) >>> 1;
  22954. if ( t < pp[ mid ] ) {
  22955. right = mid;
  22956. } else {
  22957. i1 = mid + 1;
  22958. }
  22959. }
  22960. t1 = pp[ i1 ];
  22961. t0 = pp[ i1 - 1 ];
  22962. // check boundary cases, again
  22963. if ( t0 === undefined ) {
  22964. this._cachedIndex = 0;
  22965. return this.copySampleValue_( 0 );
  22966. }
  22967. if ( t1 === undefined ) {
  22968. i1 = pp.length;
  22969. this._cachedIndex = i1;
  22970. return this.copySampleValue_( i1 - 1 );
  22971. }
  22972. } // seek
  22973. this._cachedIndex = i1;
  22974. this.intervalChanged_( i1, t0, t1 );
  22975. } // validate_interval
  22976. return this.interpolate_( i1, t0, t, t1 );
  22977. }
  22978. getSettings_() {
  22979. return this.settings || this.DefaultSettings_;
  22980. }
  22981. copySampleValue_( index ) {
  22982. // copies a sample value to the result buffer
  22983. const result = this.resultBuffer,
  22984. values = this.sampleValues,
  22985. stride = this.valueSize,
  22986. offset = index * stride;
  22987. for ( let i = 0; i !== stride; ++ i ) {
  22988. result[ i ] = values[ offset + i ];
  22989. }
  22990. return result;
  22991. }
  22992. // Template methods for derived classes:
  22993. interpolate_( /* i1, t0, t, t1 */ ) {
  22994. throw new Error( 'call to abstract method' );
  22995. // implementations shall return this.resultBuffer
  22996. }
  22997. intervalChanged_( /* i1, t0, t1 */ ) {
  22998. // empty
  22999. }
  23000. }
  23001. /**
  23002. * Fast and simple cubic spline interpolant.
  23003. *
  23004. * It was derived from a Hermitian construction setting the first derivative
  23005. * at each sample position to the linear slope between neighboring positions
  23006. * over their parameter interval.
  23007. */
  23008. class CubicInterpolant extends Interpolant {
  23009. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23010. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23011. this._weightPrev = - 0;
  23012. this._offsetPrev = - 0;
  23013. this._weightNext = - 0;
  23014. this._offsetNext = - 0;
  23015. this.DefaultSettings_ = {
  23016. endingStart: ZeroCurvatureEnding,
  23017. endingEnd: ZeroCurvatureEnding
  23018. };
  23019. }
  23020. intervalChanged_( i1, t0, t1 ) {
  23021. const pp = this.parameterPositions;
  23022. let iPrev = i1 - 2,
  23023. iNext = i1 + 1,
  23024. tPrev = pp[ iPrev ],
  23025. tNext = pp[ iNext ];
  23026. if ( tPrev === undefined ) {
  23027. switch ( this.getSettings_().endingStart ) {
  23028. case ZeroSlopeEnding:
  23029. // f'(t0) = 0
  23030. iPrev = i1;
  23031. tPrev = 2 * t0 - t1;
  23032. break;
  23033. case WrapAroundEnding:
  23034. // use the other end of the curve
  23035. iPrev = pp.length - 2;
  23036. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  23037. break;
  23038. default: // ZeroCurvatureEnding
  23039. // f''(t0) = 0 a.k.a. Natural Spline
  23040. iPrev = i1;
  23041. tPrev = t1;
  23042. }
  23043. }
  23044. if ( tNext === undefined ) {
  23045. switch ( this.getSettings_().endingEnd ) {
  23046. case ZeroSlopeEnding:
  23047. // f'(tN) = 0
  23048. iNext = i1;
  23049. tNext = 2 * t1 - t0;
  23050. break;
  23051. case WrapAroundEnding:
  23052. // use the other end of the curve
  23053. iNext = 1;
  23054. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  23055. break;
  23056. default: // ZeroCurvatureEnding
  23057. // f''(tN) = 0, a.k.a. Natural Spline
  23058. iNext = i1 - 1;
  23059. tNext = t0;
  23060. }
  23061. }
  23062. const halfDt = ( t1 - t0 ) * 0.5,
  23063. stride = this.valueSize;
  23064. this._weightPrev = halfDt / ( t0 - tPrev );
  23065. this._weightNext = halfDt / ( tNext - t1 );
  23066. this._offsetPrev = iPrev * stride;
  23067. this._offsetNext = iNext * stride;
  23068. }
  23069. interpolate_( i1, t0, t, t1 ) {
  23070. const result = this.resultBuffer,
  23071. values = this.sampleValues,
  23072. stride = this.valueSize,
  23073. o1 = i1 * stride, o0 = o1 - stride,
  23074. oP = this._offsetPrev, oN = this._offsetNext,
  23075. wP = this._weightPrev, wN = this._weightNext,
  23076. p = ( t - t0 ) / ( t1 - t0 ),
  23077. pp = p * p,
  23078. ppp = pp * p;
  23079. // evaluate polynomials
  23080. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  23081. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  23082. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  23083. const sN = wN * ppp - wN * pp;
  23084. // combine data linearly
  23085. for ( let i = 0; i !== stride; ++ i ) {
  23086. result[ i ] =
  23087. sP * values[ oP + i ] +
  23088. s0 * values[ o0 + i ] +
  23089. s1 * values[ o1 + i ] +
  23090. sN * values[ oN + i ];
  23091. }
  23092. return result;
  23093. }
  23094. }
  23095. class LinearInterpolant extends Interpolant {
  23096. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23097. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23098. }
  23099. interpolate_( i1, t0, t, t1 ) {
  23100. const result = this.resultBuffer,
  23101. values = this.sampleValues,
  23102. stride = this.valueSize,
  23103. offset1 = i1 * stride,
  23104. offset0 = offset1 - stride,
  23105. weight1 = ( t - t0 ) / ( t1 - t0 ),
  23106. weight0 = 1 - weight1;
  23107. for ( let i = 0; i !== stride; ++ i ) {
  23108. result[ i ] =
  23109. values[ offset0 + i ] * weight0 +
  23110. values[ offset1 + i ] * weight1;
  23111. }
  23112. return result;
  23113. }
  23114. }
  23115. /**
  23116. *
  23117. * Interpolant that evaluates to the sample value at the position preceding
  23118. * the parameter.
  23119. */
  23120. class DiscreteInterpolant extends Interpolant {
  23121. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23122. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23123. }
  23124. interpolate_( i1 /*, t0, t, t1 */ ) {
  23125. return this.copySampleValue_( i1 - 1 );
  23126. }
  23127. }
  23128. class KeyframeTrack {
  23129. constructor( name, times, values, interpolation ) {
  23130. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  23131. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  23132. this.name = name;
  23133. this.times = convertArray( times, this.TimeBufferType );
  23134. this.values = convertArray( values, this.ValueBufferType );
  23135. this.setInterpolation( interpolation || this.DefaultInterpolation );
  23136. }
  23137. // Serialization (in static context, because of constructor invocation
  23138. // and automatic invocation of .toJSON):
  23139. static toJSON( track ) {
  23140. const trackType = track.constructor;
  23141. let json;
  23142. // derived classes can define a static toJSON method
  23143. if ( trackType.toJSON !== this.toJSON ) {
  23144. json = trackType.toJSON( track );
  23145. } else {
  23146. // by default, we assume the data can be serialized as-is
  23147. json = {
  23148. 'name': track.name,
  23149. 'times': convertArray( track.times, Array ),
  23150. 'values': convertArray( track.values, Array )
  23151. };
  23152. const interpolation = track.getInterpolation();
  23153. if ( interpolation !== track.DefaultInterpolation ) {
  23154. json.interpolation = interpolation;
  23155. }
  23156. }
  23157. json.type = track.ValueTypeName; // mandatory
  23158. return json;
  23159. }
  23160. InterpolantFactoryMethodDiscrete( result ) {
  23161. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  23162. }
  23163. InterpolantFactoryMethodLinear( result ) {
  23164. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23165. }
  23166. InterpolantFactoryMethodSmooth( result ) {
  23167. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  23168. }
  23169. setInterpolation( interpolation ) {
  23170. let factoryMethod;
  23171. switch ( interpolation ) {
  23172. case InterpolateDiscrete:
  23173. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  23174. break;
  23175. case InterpolateLinear:
  23176. factoryMethod = this.InterpolantFactoryMethodLinear;
  23177. break;
  23178. case InterpolateSmooth:
  23179. factoryMethod = this.InterpolantFactoryMethodSmooth;
  23180. break;
  23181. }
  23182. if ( factoryMethod === undefined ) {
  23183. const message = 'unsupported interpolation for ' +
  23184. this.ValueTypeName + ' keyframe track named ' + this.name;
  23185. if ( this.createInterpolant === undefined ) {
  23186. // fall back to default, unless the default itself is messed up
  23187. if ( interpolation !== this.DefaultInterpolation ) {
  23188. this.setInterpolation( this.DefaultInterpolation );
  23189. } else {
  23190. throw new Error( message ); // fatal, in this case
  23191. }
  23192. }
  23193. console.warn( 'THREE.KeyframeTrack:', message );
  23194. return this;
  23195. }
  23196. this.createInterpolant = factoryMethod;
  23197. return this;
  23198. }
  23199. getInterpolation() {
  23200. switch ( this.createInterpolant ) {
  23201. case this.InterpolantFactoryMethodDiscrete:
  23202. return InterpolateDiscrete;
  23203. case this.InterpolantFactoryMethodLinear:
  23204. return InterpolateLinear;
  23205. case this.InterpolantFactoryMethodSmooth:
  23206. return InterpolateSmooth;
  23207. }
  23208. }
  23209. getValueSize() {
  23210. return this.values.length / this.times.length;
  23211. }
  23212. // move all keyframes either forwards or backwards in time
  23213. shift( timeOffset ) {
  23214. if ( timeOffset !== 0.0 ) {
  23215. const times = this.times;
  23216. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23217. times[ i ] += timeOffset;
  23218. }
  23219. }
  23220. return this;
  23221. }
  23222. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  23223. scale( timeScale ) {
  23224. if ( timeScale !== 1.0 ) {
  23225. const times = this.times;
  23226. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23227. times[ i ] *= timeScale;
  23228. }
  23229. }
  23230. return this;
  23231. }
  23232. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  23233. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  23234. trim( startTime, endTime ) {
  23235. const times = this.times,
  23236. nKeys = times.length;
  23237. let from = 0,
  23238. to = nKeys - 1;
  23239. while ( from !== nKeys && times[ from ] < startTime ) {
  23240. ++ from;
  23241. }
  23242. while ( to !== - 1 && times[ to ] > endTime ) {
  23243. -- to;
  23244. }
  23245. ++ to; // inclusive -> exclusive bound
  23246. if ( from !== 0 || to !== nKeys ) {
  23247. // empty tracks are forbidden, so keep at least one keyframe
  23248. if ( from >= to ) {
  23249. to = Math.max( to, 1 );
  23250. from = to - 1;
  23251. }
  23252. const stride = this.getValueSize();
  23253. this.times = arraySlice( times, from, to );
  23254. this.values = arraySlice( this.values, from * stride, to * stride );
  23255. }
  23256. return this;
  23257. }
  23258. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  23259. validate() {
  23260. let valid = true;
  23261. const valueSize = this.getValueSize();
  23262. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  23263. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  23264. valid = false;
  23265. }
  23266. const times = this.times,
  23267. values = this.values,
  23268. nKeys = times.length;
  23269. if ( nKeys === 0 ) {
  23270. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  23271. valid = false;
  23272. }
  23273. let prevTime = null;
  23274. for ( let i = 0; i !== nKeys; i ++ ) {
  23275. const currTime = times[ i ];
  23276. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  23277. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  23278. valid = false;
  23279. break;
  23280. }
  23281. if ( prevTime !== null && prevTime > currTime ) {
  23282. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  23283. valid = false;
  23284. break;
  23285. }
  23286. prevTime = currTime;
  23287. }
  23288. if ( values !== undefined ) {
  23289. if ( isTypedArray( values ) ) {
  23290. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  23291. const value = values[ i ];
  23292. if ( isNaN( value ) ) {
  23293. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  23294. valid = false;
  23295. break;
  23296. }
  23297. }
  23298. }
  23299. }
  23300. return valid;
  23301. }
  23302. // removes equivalent sequential keys as common in morph target sequences
  23303. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  23304. optimize() {
  23305. // times or values may be shared with other tracks, so overwriting is unsafe
  23306. const times = arraySlice( this.times ),
  23307. values = arraySlice( this.values ),
  23308. stride = this.getValueSize(),
  23309. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  23310. lastIndex = times.length - 1;
  23311. let writeIndex = 1;
  23312. for ( let i = 1; i < lastIndex; ++ i ) {
  23313. let keep = false;
  23314. const time = times[ i ];
  23315. const timeNext = times[ i + 1 ];
  23316. // remove adjacent keyframes scheduled at the same time
  23317. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  23318. if ( ! smoothInterpolation ) {
  23319. // remove unnecessary keyframes same as their neighbors
  23320. const offset = i * stride,
  23321. offsetP = offset - stride,
  23322. offsetN = offset + stride;
  23323. for ( let j = 0; j !== stride; ++ j ) {
  23324. const value = values[ offset + j ];
  23325. if ( value !== values[ offsetP + j ] ||
  23326. value !== values[ offsetN + j ] ) {
  23327. keep = true;
  23328. break;
  23329. }
  23330. }
  23331. } else {
  23332. keep = true;
  23333. }
  23334. }
  23335. // in-place compaction
  23336. if ( keep ) {
  23337. if ( i !== writeIndex ) {
  23338. times[ writeIndex ] = times[ i ];
  23339. const readOffset = i * stride,
  23340. writeOffset = writeIndex * stride;
  23341. for ( let j = 0; j !== stride; ++ j ) {
  23342. values[ writeOffset + j ] = values[ readOffset + j ];
  23343. }
  23344. }
  23345. ++ writeIndex;
  23346. }
  23347. }
  23348. // flush last keyframe (compaction looks ahead)
  23349. if ( lastIndex > 0 ) {
  23350. times[ writeIndex ] = times[ lastIndex ];
  23351. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  23352. values[ writeOffset + j ] = values[ readOffset + j ];
  23353. }
  23354. ++ writeIndex;
  23355. }
  23356. if ( writeIndex !== times.length ) {
  23357. this.times = arraySlice( times, 0, writeIndex );
  23358. this.values = arraySlice( values, 0, writeIndex * stride );
  23359. } else {
  23360. this.times = times;
  23361. this.values = values;
  23362. }
  23363. return this;
  23364. }
  23365. clone() {
  23366. const times = arraySlice( this.times, 0 );
  23367. const values = arraySlice( this.values, 0 );
  23368. const TypedKeyframeTrack = this.constructor;
  23369. const track = new TypedKeyframeTrack( this.name, times, values );
  23370. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  23371. track.createInterpolant = this.createInterpolant;
  23372. return track;
  23373. }
  23374. }
  23375. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  23376. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  23377. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23378. /**
  23379. * A Track of Boolean keyframe values.
  23380. */
  23381. class BooleanKeyframeTrack extends KeyframeTrack {}
  23382. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  23383. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  23384. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23385. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23386. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23387. /**
  23388. * A Track of keyframe values that represent color.
  23389. */
  23390. class ColorKeyframeTrack extends KeyframeTrack {}
  23391. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  23392. /**
  23393. * A Track of numeric keyframe values.
  23394. */
  23395. class NumberKeyframeTrack extends KeyframeTrack {}
  23396. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  23397. /**
  23398. * Spherical linear unit quaternion interpolant.
  23399. */
  23400. class QuaternionLinearInterpolant extends Interpolant {
  23401. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23402. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23403. }
  23404. interpolate_( i1, t0, t, t1 ) {
  23405. const result = this.resultBuffer,
  23406. values = this.sampleValues,
  23407. stride = this.valueSize,
  23408. alpha = ( t - t0 ) / ( t1 - t0 );
  23409. let offset = i1 * stride;
  23410. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  23411. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  23412. }
  23413. return result;
  23414. }
  23415. }
  23416. /**
  23417. * A Track of quaternion keyframe values.
  23418. */
  23419. class QuaternionKeyframeTrack extends KeyframeTrack {
  23420. InterpolantFactoryMethodLinear( result ) {
  23421. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23422. }
  23423. }
  23424. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  23425. // ValueBufferType is inherited
  23426. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23427. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23428. /**
  23429. * A Track that interpolates Strings
  23430. */
  23431. class StringKeyframeTrack extends KeyframeTrack {}
  23432. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  23433. StringKeyframeTrack.prototype.ValueBufferType = Array;
  23434. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23435. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23436. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23437. /**
  23438. * A Track of vectored keyframe values.
  23439. */
  23440. class VectorKeyframeTrack extends KeyframeTrack {}
  23441. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  23442. class AnimationClip {
  23443. constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  23444. this.name = name;
  23445. this.tracks = tracks;
  23446. this.duration = duration;
  23447. this.blendMode = blendMode;
  23448. this.uuid = generateUUID();
  23449. // this means it should figure out its duration by scanning the tracks
  23450. if ( this.duration < 0 ) {
  23451. this.resetDuration();
  23452. }
  23453. }
  23454. static parse( json ) {
  23455. const tracks = [],
  23456. jsonTracks = json.tracks,
  23457. frameTime = 1.0 / ( json.fps || 1.0 );
  23458. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  23459. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  23460. }
  23461. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  23462. clip.uuid = json.uuid;
  23463. return clip;
  23464. }
  23465. static toJSON( clip ) {
  23466. const tracks = [],
  23467. clipTracks = clip.tracks;
  23468. const json = {
  23469. 'name': clip.name,
  23470. 'duration': clip.duration,
  23471. 'tracks': tracks,
  23472. 'uuid': clip.uuid,
  23473. 'blendMode': clip.blendMode
  23474. };
  23475. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  23476. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  23477. }
  23478. return json;
  23479. }
  23480. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  23481. const numMorphTargets = morphTargetSequence.length;
  23482. const tracks = [];
  23483. for ( let i = 0; i < numMorphTargets; i ++ ) {
  23484. let times = [];
  23485. let values = [];
  23486. times.push(
  23487. ( i + numMorphTargets - 1 ) % numMorphTargets,
  23488. i,
  23489. ( i + 1 ) % numMorphTargets );
  23490. values.push( 0, 1, 0 );
  23491. const order = getKeyframeOrder( times );
  23492. times = sortedArray( times, 1, order );
  23493. values = sortedArray( values, 1, order );
  23494. // if there is a key at the first frame, duplicate it as the
  23495. // last frame as well for perfect loop.
  23496. if ( ! noLoop && times[ 0 ] === 0 ) {
  23497. times.push( numMorphTargets );
  23498. values.push( values[ 0 ] );
  23499. }
  23500. tracks.push(
  23501. new NumberKeyframeTrack(
  23502. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  23503. times, values
  23504. ).scale( 1.0 / fps ) );
  23505. }
  23506. return new this( name, - 1, tracks );
  23507. }
  23508. static findByName( objectOrClipArray, name ) {
  23509. let clipArray = objectOrClipArray;
  23510. if ( ! Array.isArray( objectOrClipArray ) ) {
  23511. const o = objectOrClipArray;
  23512. clipArray = o.geometry && o.geometry.animations || o.animations;
  23513. }
  23514. for ( let i = 0; i < clipArray.length; i ++ ) {
  23515. if ( clipArray[ i ].name === name ) {
  23516. return clipArray[ i ];
  23517. }
  23518. }
  23519. return null;
  23520. }
  23521. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  23522. const animationToMorphTargets = {};
  23523. // tested with https://regex101.com/ on trick sequences
  23524. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  23525. const pattern = /^([\w-]*?)([\d]+)$/;
  23526. // sort morph target names into animation groups based
  23527. // patterns like Walk_001, Walk_002, Run_001, Run_002
  23528. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  23529. const morphTarget = morphTargets[ i ];
  23530. const parts = morphTarget.name.match( pattern );
  23531. if ( parts && parts.length > 1 ) {
  23532. const name = parts[ 1 ];
  23533. let animationMorphTargets = animationToMorphTargets[ name ];
  23534. if ( ! animationMorphTargets ) {
  23535. animationToMorphTargets[ name ] = animationMorphTargets = [];
  23536. }
  23537. animationMorphTargets.push( morphTarget );
  23538. }
  23539. }
  23540. const clips = [];
  23541. for ( const name in animationToMorphTargets ) {
  23542. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  23543. }
  23544. return clips;
  23545. }
  23546. // parse the animation.hierarchy format
  23547. static parseAnimation( animation, bones ) {
  23548. if ( ! animation ) {
  23549. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  23550. return null;
  23551. }
  23552. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  23553. // only return track if there are actually keys.
  23554. if ( animationKeys.length !== 0 ) {
  23555. const times = [];
  23556. const values = [];
  23557. flattenJSON( animationKeys, times, values, propertyName );
  23558. // empty keys are filtered out, so check again
  23559. if ( times.length !== 0 ) {
  23560. destTracks.push( new trackType( trackName, times, values ) );
  23561. }
  23562. }
  23563. };
  23564. const tracks = [];
  23565. const clipName = animation.name || 'default';
  23566. const fps = animation.fps || 30;
  23567. const blendMode = animation.blendMode;
  23568. // automatic length determination in AnimationClip.
  23569. let duration = animation.length || - 1;
  23570. const hierarchyTracks = animation.hierarchy || [];
  23571. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  23572. const animationKeys = hierarchyTracks[ h ].keys;
  23573. // skip empty tracks
  23574. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  23575. // process morph targets
  23576. if ( animationKeys[ 0 ].morphTargets ) {
  23577. // figure out all morph targets used in this track
  23578. const morphTargetNames = {};
  23579. let k;
  23580. for ( k = 0; k < animationKeys.length; k ++ ) {
  23581. if ( animationKeys[ k ].morphTargets ) {
  23582. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  23583. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  23584. }
  23585. }
  23586. }
  23587. // create a track for each morph target with all zero
  23588. // morphTargetInfluences except for the keys in which
  23589. // the morphTarget is named.
  23590. for ( const morphTargetName in morphTargetNames ) {
  23591. const times = [];
  23592. const values = [];
  23593. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  23594. const animationKey = animationKeys[ k ];
  23595. times.push( animationKey.time );
  23596. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  23597. }
  23598. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  23599. }
  23600. duration = morphTargetNames.length * fps;
  23601. } else {
  23602. // ...assume skeletal animation
  23603. const boneName = '.bones[' + bones[ h ].name + ']';
  23604. addNonemptyTrack(
  23605. VectorKeyframeTrack, boneName + '.position',
  23606. animationKeys, 'pos', tracks );
  23607. addNonemptyTrack(
  23608. QuaternionKeyframeTrack, boneName + '.quaternion',
  23609. animationKeys, 'rot', tracks );
  23610. addNonemptyTrack(
  23611. VectorKeyframeTrack, boneName + '.scale',
  23612. animationKeys, 'scl', tracks );
  23613. }
  23614. }
  23615. if ( tracks.length === 0 ) {
  23616. return null;
  23617. }
  23618. const clip = new this( clipName, duration, tracks, blendMode );
  23619. return clip;
  23620. }
  23621. resetDuration() {
  23622. const tracks = this.tracks;
  23623. let duration = 0;
  23624. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  23625. const track = this.tracks[ i ];
  23626. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  23627. }
  23628. this.duration = duration;
  23629. return this;
  23630. }
  23631. trim() {
  23632. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23633. this.tracks[ i ].trim( 0, this.duration );
  23634. }
  23635. return this;
  23636. }
  23637. validate() {
  23638. let valid = true;
  23639. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23640. valid = valid && this.tracks[ i ].validate();
  23641. }
  23642. return valid;
  23643. }
  23644. optimize() {
  23645. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23646. this.tracks[ i ].optimize();
  23647. }
  23648. return this;
  23649. }
  23650. clone() {
  23651. const tracks = [];
  23652. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23653. tracks.push( this.tracks[ i ].clone() );
  23654. }
  23655. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  23656. }
  23657. toJSON() {
  23658. return this.constructor.toJSON( this );
  23659. }
  23660. }
  23661. function getTrackTypeForValueTypeName( typeName ) {
  23662. switch ( typeName.toLowerCase() ) {
  23663. case 'scalar':
  23664. case 'double':
  23665. case 'float':
  23666. case 'number':
  23667. case 'integer':
  23668. return NumberKeyframeTrack;
  23669. case 'vector':
  23670. case 'vector2':
  23671. case 'vector3':
  23672. case 'vector4':
  23673. return VectorKeyframeTrack;
  23674. case 'color':
  23675. return ColorKeyframeTrack;
  23676. case 'quaternion':
  23677. return QuaternionKeyframeTrack;
  23678. case 'bool':
  23679. case 'boolean':
  23680. return BooleanKeyframeTrack;
  23681. case 'string':
  23682. return StringKeyframeTrack;
  23683. }
  23684. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  23685. }
  23686. function parseKeyframeTrack( json ) {
  23687. if ( json.type === undefined ) {
  23688. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  23689. }
  23690. const trackType = getTrackTypeForValueTypeName( json.type );
  23691. if ( json.times === undefined ) {
  23692. const times = [], values = [];
  23693. flattenJSON( json.keys, times, values, 'value' );
  23694. json.times = times;
  23695. json.values = values;
  23696. }
  23697. // derived classes can define a static parse method
  23698. if ( trackType.parse !== undefined ) {
  23699. return trackType.parse( json );
  23700. } else {
  23701. // by default, we assume a constructor compatible with the base
  23702. return new trackType( json.name, json.times, json.values, json.interpolation );
  23703. }
  23704. }
  23705. const Cache = {
  23706. enabled: false,
  23707. files: {},
  23708. add: function ( key, file ) {
  23709. if ( this.enabled === false ) return;
  23710. // console.log( 'THREE.Cache', 'Adding key:', key );
  23711. this.files[ key ] = file;
  23712. },
  23713. get: function ( key ) {
  23714. if ( this.enabled === false ) return;
  23715. // console.log( 'THREE.Cache', 'Checking key:', key );
  23716. return this.files[ key ];
  23717. },
  23718. remove: function ( key ) {
  23719. delete this.files[ key ];
  23720. },
  23721. clear: function () {
  23722. this.files = {};
  23723. }
  23724. };
  23725. class LoadingManager {
  23726. constructor( onLoad, onProgress, onError ) {
  23727. const scope = this;
  23728. let isLoading = false;
  23729. let itemsLoaded = 0;
  23730. let itemsTotal = 0;
  23731. let urlModifier = undefined;
  23732. const handlers = [];
  23733. // Refer to #5689 for the reason why we don't set .onStart
  23734. // in the constructor
  23735. this.onStart = undefined;
  23736. this.onLoad = onLoad;
  23737. this.onProgress = onProgress;
  23738. this.onError = onError;
  23739. this.itemStart = function ( url ) {
  23740. itemsTotal ++;
  23741. if ( isLoading === false ) {
  23742. if ( scope.onStart !== undefined ) {
  23743. scope.onStart( url, itemsLoaded, itemsTotal );
  23744. }
  23745. }
  23746. isLoading = true;
  23747. };
  23748. this.itemEnd = function ( url ) {
  23749. itemsLoaded ++;
  23750. if ( scope.onProgress !== undefined ) {
  23751. scope.onProgress( url, itemsLoaded, itemsTotal );
  23752. }
  23753. if ( itemsLoaded === itemsTotal ) {
  23754. isLoading = false;
  23755. if ( scope.onLoad !== undefined ) {
  23756. scope.onLoad();
  23757. }
  23758. }
  23759. };
  23760. this.itemError = function ( url ) {
  23761. if ( scope.onError !== undefined ) {
  23762. scope.onError( url );
  23763. }
  23764. };
  23765. this.resolveURL = function ( url ) {
  23766. if ( urlModifier ) {
  23767. return urlModifier( url );
  23768. }
  23769. return url;
  23770. };
  23771. this.setURLModifier = function ( transform ) {
  23772. urlModifier = transform;
  23773. return this;
  23774. };
  23775. this.addHandler = function ( regex, loader ) {
  23776. handlers.push( regex, loader );
  23777. return this;
  23778. };
  23779. this.removeHandler = function ( regex ) {
  23780. const index = handlers.indexOf( regex );
  23781. if ( index !== - 1 ) {
  23782. handlers.splice( index, 2 );
  23783. }
  23784. return this;
  23785. };
  23786. this.getHandler = function ( file ) {
  23787. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  23788. const regex = handlers[ i ];
  23789. const loader = handlers[ i + 1 ];
  23790. if ( regex.global ) regex.lastIndex = 0; // see #17920
  23791. if ( regex.test( file ) ) {
  23792. return loader;
  23793. }
  23794. }
  23795. return null;
  23796. };
  23797. }
  23798. }
  23799. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  23800. class Loader {
  23801. constructor( manager ) {
  23802. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23803. this.crossOrigin = 'anonymous';
  23804. this.withCredentials = false;
  23805. this.path = '';
  23806. this.resourcePath = '';
  23807. this.requestHeader = {};
  23808. }
  23809. load( /* url, onLoad, onProgress, onError */ ) {}
  23810. loadAsync( url, onProgress ) {
  23811. const scope = this;
  23812. return new Promise( function ( resolve, reject ) {
  23813. scope.load( url, resolve, onProgress, reject );
  23814. } );
  23815. }
  23816. parse( /* data */ ) {}
  23817. setCrossOrigin( crossOrigin ) {
  23818. this.crossOrigin = crossOrigin;
  23819. return this;
  23820. }
  23821. setWithCredentials( value ) {
  23822. this.withCredentials = value;
  23823. return this;
  23824. }
  23825. setPath( path ) {
  23826. this.path = path;
  23827. return this;
  23828. }
  23829. setResourcePath( resourcePath ) {
  23830. this.resourcePath = resourcePath;
  23831. return this;
  23832. }
  23833. setRequestHeader( requestHeader ) {
  23834. this.requestHeader = requestHeader;
  23835. return this;
  23836. }
  23837. }
  23838. const loading = {};
  23839. class HttpError extends Error {
  23840. constructor( message, response ) {
  23841. super( message );
  23842. this.response = response;
  23843. }
  23844. }
  23845. class FileLoader extends Loader {
  23846. constructor( manager ) {
  23847. super( manager );
  23848. }
  23849. load( url, onLoad, onProgress, onError ) {
  23850. if ( url === undefined ) url = '';
  23851. if ( this.path !== undefined ) url = this.path + url;
  23852. url = this.manager.resolveURL( url );
  23853. const cached = Cache.get( url );
  23854. if ( cached !== undefined ) {
  23855. this.manager.itemStart( url );
  23856. setTimeout( () => {
  23857. if ( onLoad ) onLoad( cached );
  23858. this.manager.itemEnd( url );
  23859. }, 0 );
  23860. return cached;
  23861. }
  23862. // Check if request is duplicate
  23863. if ( loading[ url ] !== undefined ) {
  23864. loading[ url ].push( {
  23865. onLoad: onLoad,
  23866. onProgress: onProgress,
  23867. onError: onError
  23868. } );
  23869. return;
  23870. }
  23871. // Initialise array for duplicate requests
  23872. loading[ url ] = [];
  23873. loading[ url ].push( {
  23874. onLoad: onLoad,
  23875. onProgress: onProgress,
  23876. onError: onError,
  23877. } );
  23878. // create request
  23879. const req = new Request( url, {
  23880. headers: new Headers( this.requestHeader ),
  23881. credentials: this.withCredentials ? 'include' : 'same-origin',
  23882. // An abort controller could be added within a future PR
  23883. } );
  23884. // record states ( avoid data race )
  23885. const mimeType = this.mimeType;
  23886. const responseType = this.responseType;
  23887. // start the fetch
  23888. fetch( req )
  23889. .then( response => {
  23890. if ( response.status === 200 || response.status === 0 ) {
  23891. // Some browsers return HTTP Status 0 when using non-http protocol
  23892. // e.g. 'file://' or 'data://'. Handle as success.
  23893. if ( response.status === 0 ) {
  23894. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  23895. }
  23896. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  23897. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  23898. return response;
  23899. }
  23900. const callbacks = loading[ url ];
  23901. const reader = response.body.getReader();
  23902. // Nginx needs X-File-Size check
  23903. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  23904. const contentLength = response.headers.get( 'Content-Length' ) || response.headers.get( 'X-File-Size' );
  23905. const total = contentLength ? parseInt( contentLength ) : 0;
  23906. const lengthComputable = total !== 0;
  23907. let loaded = 0;
  23908. // periodically read data into the new stream tracking while download progress
  23909. const stream = new ReadableStream( {
  23910. start( controller ) {
  23911. readData();
  23912. function readData() {
  23913. reader.read().then( ( { done, value } ) => {
  23914. if ( done ) {
  23915. controller.close();
  23916. } else {
  23917. loaded += value.byteLength;
  23918. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  23919. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23920. const callback = callbacks[ i ];
  23921. if ( callback.onProgress ) callback.onProgress( event );
  23922. }
  23923. controller.enqueue( value );
  23924. readData();
  23925. }
  23926. } );
  23927. }
  23928. }
  23929. } );
  23930. return new Response( stream );
  23931. } else {
  23932. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  23933. }
  23934. } )
  23935. .then( response => {
  23936. switch ( responseType ) {
  23937. case 'arraybuffer':
  23938. return response.arrayBuffer();
  23939. case 'blob':
  23940. return response.blob();
  23941. case 'document':
  23942. return response.text()
  23943. .then( text => {
  23944. const parser = new DOMParser();
  23945. return parser.parseFromString( text, mimeType );
  23946. } );
  23947. case 'json':
  23948. return response.json();
  23949. default:
  23950. if ( mimeType === undefined ) {
  23951. return response.text();
  23952. } else {
  23953. // sniff encoding
  23954. const re = /charset="?([^;"\s]*)"?/i;
  23955. const exec = re.exec( mimeType );
  23956. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  23957. const decoder = new TextDecoder( label );
  23958. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  23959. }
  23960. }
  23961. } )
  23962. .then( data => {
  23963. // Add to cache only on HTTP success, so that we do not cache
  23964. // error response bodies as proper responses to requests.
  23965. Cache.add( url, data );
  23966. const callbacks = loading[ url ];
  23967. delete loading[ url ];
  23968. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23969. const callback = callbacks[ i ];
  23970. if ( callback.onLoad ) callback.onLoad( data );
  23971. }
  23972. } )
  23973. .catch( err => {
  23974. // Abort errors and other errors are handled the same
  23975. const callbacks = loading[ url ];
  23976. if ( callbacks === undefined ) {
  23977. // When onLoad was called and url was deleted in `loading`
  23978. this.manager.itemError( url );
  23979. throw err;
  23980. }
  23981. delete loading[ url ];
  23982. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23983. const callback = callbacks[ i ];
  23984. if ( callback.onError ) callback.onError( err );
  23985. }
  23986. this.manager.itemError( url );
  23987. } )
  23988. .finally( () => {
  23989. this.manager.itemEnd( url );
  23990. } );
  23991. this.manager.itemStart( url );
  23992. }
  23993. setResponseType( value ) {
  23994. this.responseType = value;
  23995. return this;
  23996. }
  23997. setMimeType( value ) {
  23998. this.mimeType = value;
  23999. return this;
  24000. }
  24001. }
  24002. class AnimationLoader extends Loader {
  24003. constructor( manager ) {
  24004. super( manager );
  24005. }
  24006. load( url, onLoad, onProgress, onError ) {
  24007. const scope = this;
  24008. const loader = new FileLoader( this.manager );
  24009. loader.setPath( this.path );
  24010. loader.setRequestHeader( this.requestHeader );
  24011. loader.setWithCredentials( this.withCredentials );
  24012. loader.load( url, function ( text ) {
  24013. try {
  24014. onLoad( scope.parse( JSON.parse( text ) ) );
  24015. } catch ( e ) {
  24016. if ( onError ) {
  24017. onError( e );
  24018. } else {
  24019. console.error( e );
  24020. }
  24021. scope.manager.itemError( url );
  24022. }
  24023. }, onProgress, onError );
  24024. }
  24025. parse( json ) {
  24026. const animations = [];
  24027. for ( let i = 0; i < json.length; i ++ ) {
  24028. const clip = AnimationClip.parse( json[ i ] );
  24029. animations.push( clip );
  24030. }
  24031. return animations;
  24032. }
  24033. }
  24034. /**
  24035. * Abstract Base class to block based textures loader (dds, pvr, ...)
  24036. *
  24037. * Sub classes have to implement the parse() method which will be used in load().
  24038. */
  24039. class CompressedTextureLoader extends Loader {
  24040. constructor( manager ) {
  24041. super( manager );
  24042. }
  24043. load( url, onLoad, onProgress, onError ) {
  24044. const scope = this;
  24045. const images = [];
  24046. const texture = new CompressedTexture();
  24047. const loader = new FileLoader( this.manager );
  24048. loader.setPath( this.path );
  24049. loader.setResponseType( 'arraybuffer' );
  24050. loader.setRequestHeader( this.requestHeader );
  24051. loader.setWithCredentials( scope.withCredentials );
  24052. let loaded = 0;
  24053. function loadTexture( i ) {
  24054. loader.load( url[ i ], function ( buffer ) {
  24055. const texDatas = scope.parse( buffer, true );
  24056. images[ i ] = {
  24057. width: texDatas.width,
  24058. height: texDatas.height,
  24059. format: texDatas.format,
  24060. mipmaps: texDatas.mipmaps
  24061. };
  24062. loaded += 1;
  24063. if ( loaded === 6 ) {
  24064. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  24065. texture.image = images;
  24066. texture.format = texDatas.format;
  24067. texture.needsUpdate = true;
  24068. if ( onLoad ) onLoad( texture );
  24069. }
  24070. }, onProgress, onError );
  24071. }
  24072. if ( Array.isArray( url ) ) {
  24073. for ( let i = 0, il = url.length; i < il; ++ i ) {
  24074. loadTexture( i );
  24075. }
  24076. } else {
  24077. // compressed cubemap texture stored in a single DDS file
  24078. loader.load( url, function ( buffer ) {
  24079. const texDatas = scope.parse( buffer, true );
  24080. if ( texDatas.isCubemap ) {
  24081. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  24082. for ( let f = 0; f < faces; f ++ ) {
  24083. images[ f ] = { mipmaps: [] };
  24084. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  24085. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  24086. images[ f ].format = texDatas.format;
  24087. images[ f ].width = texDatas.width;
  24088. images[ f ].height = texDatas.height;
  24089. }
  24090. }
  24091. texture.image = images;
  24092. } else {
  24093. texture.image.width = texDatas.width;
  24094. texture.image.height = texDatas.height;
  24095. texture.mipmaps = texDatas.mipmaps;
  24096. }
  24097. if ( texDatas.mipmapCount === 1 ) {
  24098. texture.minFilter = LinearFilter;
  24099. }
  24100. texture.format = texDatas.format;
  24101. texture.needsUpdate = true;
  24102. if ( onLoad ) onLoad( texture );
  24103. }, onProgress, onError );
  24104. }
  24105. return texture;
  24106. }
  24107. }
  24108. class ImageLoader extends Loader {
  24109. constructor( manager ) {
  24110. super( manager );
  24111. }
  24112. load( url, onLoad, onProgress, onError ) {
  24113. if ( this.path !== undefined ) url = this.path + url;
  24114. url = this.manager.resolveURL( url );
  24115. const scope = this;
  24116. const cached = Cache.get( url );
  24117. if ( cached !== undefined ) {
  24118. scope.manager.itemStart( url );
  24119. setTimeout( function () {
  24120. if ( onLoad ) onLoad( cached );
  24121. scope.manager.itemEnd( url );
  24122. }, 0 );
  24123. return cached;
  24124. }
  24125. const image = createElementNS( 'img' );
  24126. function onImageLoad() {
  24127. removeEventListeners();
  24128. Cache.add( url, this );
  24129. if ( onLoad ) onLoad( this );
  24130. scope.manager.itemEnd( url );
  24131. }
  24132. function onImageError( event ) {
  24133. removeEventListeners();
  24134. if ( onError ) onError( event );
  24135. scope.manager.itemError( url );
  24136. scope.manager.itemEnd( url );
  24137. }
  24138. function removeEventListeners() {
  24139. image.removeEventListener( 'load', onImageLoad, false );
  24140. image.removeEventListener( 'error', onImageError, false );
  24141. }
  24142. image.addEventListener( 'load', onImageLoad, false );
  24143. image.addEventListener( 'error', onImageError, false );
  24144. if ( url.slice( 0, 5 ) !== 'data:' ) {
  24145. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  24146. }
  24147. scope.manager.itemStart( url );
  24148. image.src = url;
  24149. return image;
  24150. }
  24151. }
  24152. class CubeTextureLoader extends Loader {
  24153. constructor( manager ) {
  24154. super( manager );
  24155. }
  24156. load( urls, onLoad, onProgress, onError ) {
  24157. const texture = new CubeTexture();
  24158. const loader = new ImageLoader( this.manager );
  24159. loader.setCrossOrigin( this.crossOrigin );
  24160. loader.setPath( this.path );
  24161. let loaded = 0;
  24162. function loadTexture( i ) {
  24163. loader.load( urls[ i ], function ( image ) {
  24164. texture.images[ i ] = image;
  24165. loaded ++;
  24166. if ( loaded === 6 ) {
  24167. texture.needsUpdate = true;
  24168. if ( onLoad ) onLoad( texture );
  24169. }
  24170. }, undefined, onError );
  24171. }
  24172. for ( let i = 0; i < urls.length; ++ i ) {
  24173. loadTexture( i );
  24174. }
  24175. return texture;
  24176. }
  24177. }
  24178. /**
  24179. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  24180. *
  24181. * Sub classes have to implement the parse() method which will be used in load().
  24182. */
  24183. class DataTextureLoader extends Loader {
  24184. constructor( manager ) {
  24185. super( manager );
  24186. }
  24187. load( url, onLoad, onProgress, onError ) {
  24188. const scope = this;
  24189. const texture = new DataTexture();
  24190. const loader = new FileLoader( this.manager );
  24191. loader.setResponseType( 'arraybuffer' );
  24192. loader.setRequestHeader( this.requestHeader );
  24193. loader.setPath( this.path );
  24194. loader.setWithCredentials( scope.withCredentials );
  24195. loader.load( url, function ( buffer ) {
  24196. const texData = scope.parse( buffer );
  24197. if ( ! texData ) return;
  24198. if ( texData.image !== undefined ) {
  24199. texture.image = texData.image;
  24200. } else if ( texData.data !== undefined ) {
  24201. texture.image.width = texData.width;
  24202. texture.image.height = texData.height;
  24203. texture.image.data = texData.data;
  24204. }
  24205. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  24206. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  24207. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  24208. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  24209. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  24210. if ( texData.encoding !== undefined ) {
  24211. texture.encoding = texData.encoding;
  24212. }
  24213. if ( texData.flipY !== undefined ) {
  24214. texture.flipY = texData.flipY;
  24215. }
  24216. if ( texData.format !== undefined ) {
  24217. texture.format = texData.format;
  24218. }
  24219. if ( texData.type !== undefined ) {
  24220. texture.type = texData.type;
  24221. }
  24222. if ( texData.mipmaps !== undefined ) {
  24223. texture.mipmaps = texData.mipmaps;
  24224. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  24225. }
  24226. if ( texData.mipmapCount === 1 ) {
  24227. texture.minFilter = LinearFilter;
  24228. }
  24229. if ( texData.generateMipmaps !== undefined ) {
  24230. texture.generateMipmaps = texData.generateMipmaps;
  24231. }
  24232. texture.needsUpdate = true;
  24233. if ( onLoad ) onLoad( texture, texData );
  24234. }, onProgress, onError );
  24235. return texture;
  24236. }
  24237. }
  24238. class TextureLoader extends Loader {
  24239. constructor( manager ) {
  24240. super( manager );
  24241. }
  24242. load( url, onLoad, onProgress, onError ) {
  24243. const texture = new Texture();
  24244. const loader = new ImageLoader( this.manager );
  24245. loader.setCrossOrigin( this.crossOrigin );
  24246. loader.setPath( this.path );
  24247. loader.load( url, function ( image ) {
  24248. texture.image = image;
  24249. texture.needsUpdate = true;
  24250. if ( onLoad !== undefined ) {
  24251. onLoad( texture );
  24252. }
  24253. }, onProgress, onError );
  24254. return texture;
  24255. }
  24256. }
  24257. class Light extends Object3D {
  24258. constructor( color, intensity = 1 ) {
  24259. super();
  24260. this.isLight = true;
  24261. this.type = 'Light';
  24262. this.color = new Color( color );
  24263. this.intensity = intensity;
  24264. }
  24265. dispose() {
  24266. // Empty here in base class; some subclasses override.
  24267. }
  24268. copy( source, recursive ) {
  24269. super.copy( source, recursive );
  24270. this.color.copy( source.color );
  24271. this.intensity = source.intensity;
  24272. return this;
  24273. }
  24274. toJSON( meta ) {
  24275. const data = super.toJSON( meta );
  24276. data.object.color = this.color.getHex();
  24277. data.object.intensity = this.intensity;
  24278. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  24279. if ( this.distance !== undefined ) data.object.distance = this.distance;
  24280. if ( this.angle !== undefined ) data.object.angle = this.angle;
  24281. if ( this.decay !== undefined ) data.object.decay = this.decay;
  24282. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  24283. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  24284. return data;
  24285. }
  24286. }
  24287. class HemisphereLight extends Light {
  24288. constructor( skyColor, groundColor, intensity ) {
  24289. super( skyColor, intensity );
  24290. this.isHemisphereLight = true;
  24291. this.type = 'HemisphereLight';
  24292. this.position.copy( Object3D.DEFAULT_UP );
  24293. this.updateMatrix();
  24294. this.groundColor = new Color( groundColor );
  24295. }
  24296. copy( source, recursive ) {
  24297. super.copy( source, recursive );
  24298. this.groundColor.copy( source.groundColor );
  24299. return this;
  24300. }
  24301. }
  24302. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  24303. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  24304. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  24305. class LightShadow {
  24306. constructor( camera ) {
  24307. this.camera = camera;
  24308. this.bias = 0;
  24309. this.normalBias = 0;
  24310. this.radius = 1;
  24311. this.blurSamples = 8;
  24312. this.mapSize = new Vector2( 512, 512 );
  24313. this.map = null;
  24314. this.mapPass = null;
  24315. this.matrix = new Matrix4();
  24316. this.autoUpdate = true;
  24317. this.needsUpdate = false;
  24318. this._frustum = new Frustum();
  24319. this._frameExtents = new Vector2( 1, 1 );
  24320. this._viewportCount = 1;
  24321. this._viewports = [
  24322. new Vector4( 0, 0, 1, 1 )
  24323. ];
  24324. }
  24325. getViewportCount() {
  24326. return this._viewportCount;
  24327. }
  24328. getFrustum() {
  24329. return this._frustum;
  24330. }
  24331. updateMatrices( light ) {
  24332. const shadowCamera = this.camera;
  24333. const shadowMatrix = this.matrix;
  24334. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  24335. shadowCamera.position.copy( _lightPositionWorld$1 );
  24336. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  24337. shadowCamera.lookAt( _lookTarget$1 );
  24338. shadowCamera.updateMatrixWorld();
  24339. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  24340. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  24341. shadowMatrix.set(
  24342. 0.5, 0.0, 0.0, 0.5,
  24343. 0.0, 0.5, 0.0, 0.5,
  24344. 0.0, 0.0, 0.5, 0.5,
  24345. 0.0, 0.0, 0.0, 1.0
  24346. );
  24347. shadowMatrix.multiply( _projScreenMatrix$1 );
  24348. }
  24349. getViewport( viewportIndex ) {
  24350. return this._viewports[ viewportIndex ];
  24351. }
  24352. getFrameExtents() {
  24353. return this._frameExtents;
  24354. }
  24355. dispose() {
  24356. if ( this.map ) {
  24357. this.map.dispose();
  24358. }
  24359. if ( this.mapPass ) {
  24360. this.mapPass.dispose();
  24361. }
  24362. }
  24363. copy( source ) {
  24364. this.camera = source.camera.clone();
  24365. this.bias = source.bias;
  24366. this.radius = source.radius;
  24367. this.mapSize.copy( source.mapSize );
  24368. return this;
  24369. }
  24370. clone() {
  24371. return new this.constructor().copy( this );
  24372. }
  24373. toJSON() {
  24374. const object = {};
  24375. if ( this.bias !== 0 ) object.bias = this.bias;
  24376. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  24377. if ( this.radius !== 1 ) object.radius = this.radius;
  24378. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  24379. object.camera = this.camera.toJSON( false ).object;
  24380. delete object.camera.matrix;
  24381. return object;
  24382. }
  24383. }
  24384. class SpotLightShadow extends LightShadow {
  24385. constructor() {
  24386. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  24387. this.isSpotLightShadow = true;
  24388. this.focus = 1;
  24389. }
  24390. updateMatrices( light ) {
  24391. const camera = this.camera;
  24392. const fov = RAD2DEG * 2 * light.angle * this.focus;
  24393. const aspect = this.mapSize.width / this.mapSize.height;
  24394. const far = light.distance || camera.far;
  24395. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  24396. camera.fov = fov;
  24397. camera.aspect = aspect;
  24398. camera.far = far;
  24399. camera.updateProjectionMatrix();
  24400. }
  24401. super.updateMatrices( light );
  24402. }
  24403. copy( source ) {
  24404. super.copy( source );
  24405. this.focus = source.focus;
  24406. return this;
  24407. }
  24408. }
  24409. class SpotLight extends Light {
  24410. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  24411. super( color, intensity );
  24412. this.isSpotLight = true;
  24413. this.type = 'SpotLight';
  24414. this.position.copy( Object3D.DEFAULT_UP );
  24415. this.updateMatrix();
  24416. this.target = new Object3D();
  24417. this.distance = distance;
  24418. this.angle = angle;
  24419. this.penumbra = penumbra;
  24420. this.decay = decay;
  24421. this.map = null;
  24422. this.shadow = new SpotLightShadow();
  24423. }
  24424. get power() {
  24425. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24426. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  24427. return this.intensity * Math.PI;
  24428. }
  24429. set power( power ) {
  24430. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24431. this.intensity = power / Math.PI;
  24432. }
  24433. dispose() {
  24434. this.shadow.dispose();
  24435. }
  24436. copy( source, recursive ) {
  24437. super.copy( source, recursive );
  24438. this.distance = source.distance;
  24439. this.angle = source.angle;
  24440. this.penumbra = source.penumbra;
  24441. this.decay = source.decay;
  24442. this.target = source.target.clone();
  24443. this.shadow = source.shadow.clone();
  24444. return this;
  24445. }
  24446. }
  24447. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  24448. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  24449. const _lookTarget = /*@__PURE__*/ new Vector3();
  24450. class PointLightShadow extends LightShadow {
  24451. constructor() {
  24452. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  24453. this.isPointLightShadow = true;
  24454. this._frameExtents = new Vector2( 4, 2 );
  24455. this._viewportCount = 6;
  24456. this._viewports = [
  24457. // These viewports map a cube-map onto a 2D texture with the
  24458. // following orientation:
  24459. //
  24460. // xzXZ
  24461. // y Y
  24462. //
  24463. // X - Positive x direction
  24464. // x - Negative x direction
  24465. // Y - Positive y direction
  24466. // y - Negative y direction
  24467. // Z - Positive z direction
  24468. // z - Negative z direction
  24469. // positive X
  24470. new Vector4( 2, 1, 1, 1 ),
  24471. // negative X
  24472. new Vector4( 0, 1, 1, 1 ),
  24473. // positive Z
  24474. new Vector4( 3, 1, 1, 1 ),
  24475. // negative Z
  24476. new Vector4( 1, 1, 1, 1 ),
  24477. // positive Y
  24478. new Vector4( 3, 0, 1, 1 ),
  24479. // negative Y
  24480. new Vector4( 1, 0, 1, 1 )
  24481. ];
  24482. this._cubeDirections = [
  24483. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  24484. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  24485. ];
  24486. this._cubeUps = [
  24487. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  24488. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  24489. ];
  24490. }
  24491. updateMatrices( light, viewportIndex = 0 ) {
  24492. const camera = this.camera;
  24493. const shadowMatrix = this.matrix;
  24494. const far = light.distance || camera.far;
  24495. if ( far !== camera.far ) {
  24496. camera.far = far;
  24497. camera.updateProjectionMatrix();
  24498. }
  24499. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  24500. camera.position.copy( _lightPositionWorld );
  24501. _lookTarget.copy( camera.position );
  24502. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  24503. camera.up.copy( this._cubeUps[ viewportIndex ] );
  24504. camera.lookAt( _lookTarget );
  24505. camera.updateMatrixWorld();
  24506. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  24507. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  24508. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  24509. }
  24510. }
  24511. class PointLight extends Light {
  24512. constructor( color, intensity, distance = 0, decay = 2 ) {
  24513. super( color, intensity );
  24514. this.isPointLight = true;
  24515. this.type = 'PointLight';
  24516. this.distance = distance;
  24517. this.decay = decay;
  24518. this.shadow = new PointLightShadow();
  24519. }
  24520. get power() {
  24521. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24522. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  24523. return this.intensity * 4 * Math.PI;
  24524. }
  24525. set power( power ) {
  24526. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24527. this.intensity = power / ( 4 * Math.PI );
  24528. }
  24529. dispose() {
  24530. this.shadow.dispose();
  24531. }
  24532. copy( source, recursive ) {
  24533. super.copy( source, recursive );
  24534. this.distance = source.distance;
  24535. this.decay = source.decay;
  24536. this.shadow = source.shadow.clone();
  24537. return this;
  24538. }
  24539. }
  24540. class DirectionalLightShadow extends LightShadow {
  24541. constructor() {
  24542. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  24543. this.isDirectionalLightShadow = true;
  24544. }
  24545. }
  24546. class DirectionalLight extends Light {
  24547. constructor( color, intensity ) {
  24548. super( color, intensity );
  24549. this.isDirectionalLight = true;
  24550. this.type = 'DirectionalLight';
  24551. this.position.copy( Object3D.DEFAULT_UP );
  24552. this.updateMatrix();
  24553. this.target = new Object3D();
  24554. this.shadow = new DirectionalLightShadow();
  24555. }
  24556. dispose() {
  24557. this.shadow.dispose();
  24558. }
  24559. copy( source ) {
  24560. super.copy( source );
  24561. this.target = source.target.clone();
  24562. this.shadow = source.shadow.clone();
  24563. return this;
  24564. }
  24565. }
  24566. class AmbientLight extends Light {
  24567. constructor( color, intensity ) {
  24568. super( color, intensity );
  24569. this.isAmbientLight = true;
  24570. this.type = 'AmbientLight';
  24571. }
  24572. }
  24573. class RectAreaLight extends Light {
  24574. constructor( color, intensity, width = 10, height = 10 ) {
  24575. super( color, intensity );
  24576. this.isRectAreaLight = true;
  24577. this.type = 'RectAreaLight';
  24578. this.width = width;
  24579. this.height = height;
  24580. }
  24581. get power() {
  24582. // compute the light's luminous power (in lumens) from its intensity (in nits)
  24583. return this.intensity * this.width * this.height * Math.PI;
  24584. }
  24585. set power( power ) {
  24586. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  24587. this.intensity = power / ( this.width * this.height * Math.PI );
  24588. }
  24589. copy( source ) {
  24590. super.copy( source );
  24591. this.width = source.width;
  24592. this.height = source.height;
  24593. return this;
  24594. }
  24595. toJSON( meta ) {
  24596. const data = super.toJSON( meta );
  24597. data.object.width = this.width;
  24598. data.object.height = this.height;
  24599. return data;
  24600. }
  24601. }
  24602. /**
  24603. * Primary reference:
  24604. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24605. *
  24606. * Secondary reference:
  24607. * https://www.ppsloan.org/publications/StupidSH36.pdf
  24608. */
  24609. // 3-band SH defined by 9 coefficients
  24610. class SphericalHarmonics3 {
  24611. constructor() {
  24612. this.isSphericalHarmonics3 = true;
  24613. this.coefficients = [];
  24614. for ( let i = 0; i < 9; i ++ ) {
  24615. this.coefficients.push( new Vector3() );
  24616. }
  24617. }
  24618. set( coefficients ) {
  24619. for ( let i = 0; i < 9; i ++ ) {
  24620. this.coefficients[ i ].copy( coefficients[ i ] );
  24621. }
  24622. return this;
  24623. }
  24624. zero() {
  24625. for ( let i = 0; i < 9; i ++ ) {
  24626. this.coefficients[ i ].set( 0, 0, 0 );
  24627. }
  24628. return this;
  24629. }
  24630. // get the radiance in the direction of the normal
  24631. // target is a Vector3
  24632. getAt( normal, target ) {
  24633. // normal is assumed to be unit length
  24634. const x = normal.x, y = normal.y, z = normal.z;
  24635. const coeff = this.coefficients;
  24636. // band 0
  24637. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  24638. // band 1
  24639. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  24640. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  24641. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  24642. // band 2
  24643. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  24644. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  24645. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  24646. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  24647. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  24648. return target;
  24649. }
  24650. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  24651. // target is a Vector3
  24652. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24653. getIrradianceAt( normal, target ) {
  24654. // normal is assumed to be unit length
  24655. const x = normal.x, y = normal.y, z = normal.z;
  24656. const coeff = this.coefficients;
  24657. // band 0
  24658. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  24659. // band 1
  24660. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  24661. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  24662. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  24663. // band 2
  24664. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  24665. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  24666. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  24667. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  24668. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  24669. return target;
  24670. }
  24671. add( sh ) {
  24672. for ( let i = 0; i < 9; i ++ ) {
  24673. this.coefficients[ i ].add( sh.coefficients[ i ] );
  24674. }
  24675. return this;
  24676. }
  24677. addScaledSH( sh, s ) {
  24678. for ( let i = 0; i < 9; i ++ ) {
  24679. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  24680. }
  24681. return this;
  24682. }
  24683. scale( s ) {
  24684. for ( let i = 0; i < 9; i ++ ) {
  24685. this.coefficients[ i ].multiplyScalar( s );
  24686. }
  24687. return this;
  24688. }
  24689. lerp( sh, alpha ) {
  24690. for ( let i = 0; i < 9; i ++ ) {
  24691. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  24692. }
  24693. return this;
  24694. }
  24695. equals( sh ) {
  24696. for ( let i = 0; i < 9; i ++ ) {
  24697. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  24698. return false;
  24699. }
  24700. }
  24701. return true;
  24702. }
  24703. copy( sh ) {
  24704. return this.set( sh.coefficients );
  24705. }
  24706. clone() {
  24707. return new this.constructor().copy( this );
  24708. }
  24709. fromArray( array, offset = 0 ) {
  24710. const coefficients = this.coefficients;
  24711. for ( let i = 0; i < 9; i ++ ) {
  24712. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  24713. }
  24714. return this;
  24715. }
  24716. toArray( array = [], offset = 0 ) {
  24717. const coefficients = this.coefficients;
  24718. for ( let i = 0; i < 9; i ++ ) {
  24719. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  24720. }
  24721. return array;
  24722. }
  24723. // evaluate the basis functions
  24724. // shBasis is an Array[ 9 ]
  24725. static getBasisAt( normal, shBasis ) {
  24726. // normal is assumed to be unit length
  24727. const x = normal.x, y = normal.y, z = normal.z;
  24728. // band 0
  24729. shBasis[ 0 ] = 0.282095;
  24730. // band 1
  24731. shBasis[ 1 ] = 0.488603 * y;
  24732. shBasis[ 2 ] = 0.488603 * z;
  24733. shBasis[ 3 ] = 0.488603 * x;
  24734. // band 2
  24735. shBasis[ 4 ] = 1.092548 * x * y;
  24736. shBasis[ 5 ] = 1.092548 * y * z;
  24737. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  24738. shBasis[ 7 ] = 1.092548 * x * z;
  24739. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  24740. }
  24741. }
  24742. class LightProbe extends Light {
  24743. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  24744. super( undefined, intensity );
  24745. this.isLightProbe = true;
  24746. this.sh = sh;
  24747. }
  24748. copy( source ) {
  24749. super.copy( source );
  24750. this.sh.copy( source.sh );
  24751. return this;
  24752. }
  24753. fromJSON( json ) {
  24754. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  24755. this.sh.fromArray( json.sh );
  24756. return this;
  24757. }
  24758. toJSON( meta ) {
  24759. const data = super.toJSON( meta );
  24760. data.object.sh = this.sh.toArray();
  24761. return data;
  24762. }
  24763. }
  24764. class MaterialLoader extends Loader {
  24765. constructor( manager ) {
  24766. super( manager );
  24767. this.textures = {};
  24768. }
  24769. load( url, onLoad, onProgress, onError ) {
  24770. const scope = this;
  24771. const loader = new FileLoader( scope.manager );
  24772. loader.setPath( scope.path );
  24773. loader.setRequestHeader( scope.requestHeader );
  24774. loader.setWithCredentials( scope.withCredentials );
  24775. loader.load( url, function ( text ) {
  24776. try {
  24777. onLoad( scope.parse( JSON.parse( text ) ) );
  24778. } catch ( e ) {
  24779. if ( onError ) {
  24780. onError( e );
  24781. } else {
  24782. console.error( e );
  24783. }
  24784. scope.manager.itemError( url );
  24785. }
  24786. }, onProgress, onError );
  24787. }
  24788. parse( json ) {
  24789. const textures = this.textures;
  24790. function getTexture( name ) {
  24791. if ( textures[ name ] === undefined ) {
  24792. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  24793. }
  24794. return textures[ name ];
  24795. }
  24796. const material = MaterialLoader.createMaterialFromType( json.type );
  24797. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  24798. if ( json.name !== undefined ) material.name = json.name;
  24799. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  24800. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  24801. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  24802. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  24803. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  24804. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  24805. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  24806. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  24807. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  24808. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  24809. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  24810. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  24811. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  24812. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  24813. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  24814. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  24815. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  24816. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  24817. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  24818. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  24819. if ( json.fog !== undefined ) material.fog = json.fog;
  24820. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  24821. if ( json.blending !== undefined ) material.blending = json.blending;
  24822. if ( json.combine !== undefined ) material.combine = json.combine;
  24823. if ( json.side !== undefined ) material.side = json.side;
  24824. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  24825. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  24826. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  24827. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  24828. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  24829. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  24830. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  24831. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  24832. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  24833. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  24834. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  24835. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  24836. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  24837. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  24838. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  24839. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  24840. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  24841. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  24842. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  24843. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  24844. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  24845. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  24846. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  24847. if ( json.scale !== undefined ) material.scale = json.scale;
  24848. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  24849. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24850. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24851. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  24852. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  24853. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  24854. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  24855. if ( json.visible !== undefined ) material.visible = json.visible;
  24856. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  24857. if ( json.userData !== undefined ) material.userData = json.userData;
  24858. if ( json.vertexColors !== undefined ) {
  24859. if ( typeof json.vertexColors === 'number' ) {
  24860. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  24861. } else {
  24862. material.vertexColors = json.vertexColors;
  24863. }
  24864. }
  24865. // Shader Material
  24866. if ( json.uniforms !== undefined ) {
  24867. for ( const name in json.uniforms ) {
  24868. const uniform = json.uniforms[ name ];
  24869. material.uniforms[ name ] = {};
  24870. switch ( uniform.type ) {
  24871. case 't':
  24872. material.uniforms[ name ].value = getTexture( uniform.value );
  24873. break;
  24874. case 'c':
  24875. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  24876. break;
  24877. case 'v2':
  24878. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  24879. break;
  24880. case 'v3':
  24881. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  24882. break;
  24883. case 'v4':
  24884. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  24885. break;
  24886. case 'm3':
  24887. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  24888. break;
  24889. case 'm4':
  24890. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  24891. break;
  24892. default:
  24893. material.uniforms[ name ].value = uniform.value;
  24894. }
  24895. }
  24896. }
  24897. if ( json.defines !== undefined ) material.defines = json.defines;
  24898. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  24899. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  24900. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  24901. if ( json.extensions !== undefined ) {
  24902. for ( const key in json.extensions ) {
  24903. material.extensions[ key ] = json.extensions[ key ];
  24904. }
  24905. }
  24906. // for PointsMaterial
  24907. if ( json.size !== undefined ) material.size = json.size;
  24908. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  24909. // maps
  24910. if ( json.map !== undefined ) material.map = getTexture( json.map );
  24911. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  24912. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  24913. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  24914. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  24915. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  24916. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  24917. if ( json.normalScale !== undefined ) {
  24918. let normalScale = json.normalScale;
  24919. if ( Array.isArray( normalScale ) === false ) {
  24920. // Blender exporter used to export a scalar. See #7459
  24921. normalScale = [ normalScale, normalScale ];
  24922. }
  24923. material.normalScale = new Vector2().fromArray( normalScale );
  24924. }
  24925. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  24926. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  24927. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  24928. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  24929. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  24930. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  24931. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  24932. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  24933. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  24934. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  24935. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  24936. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  24937. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  24938. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  24939. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  24940. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  24941. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  24942. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  24943. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  24944. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  24945. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  24946. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  24947. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  24948. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  24949. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  24950. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  24951. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  24952. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  24953. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  24954. return material;
  24955. }
  24956. setTextures( value ) {
  24957. this.textures = value;
  24958. return this;
  24959. }
  24960. static createMaterialFromType( type ) {
  24961. const materialLib = {
  24962. ShadowMaterial,
  24963. SpriteMaterial,
  24964. RawShaderMaterial,
  24965. ShaderMaterial,
  24966. PointsMaterial,
  24967. MeshPhysicalMaterial,
  24968. MeshStandardMaterial,
  24969. MeshPhongMaterial,
  24970. MeshToonMaterial,
  24971. MeshNormalMaterial,
  24972. MeshLambertMaterial,
  24973. MeshDepthMaterial,
  24974. MeshDistanceMaterial,
  24975. MeshBasicMaterial,
  24976. MeshMatcapMaterial,
  24977. LineDashedMaterial,
  24978. LineBasicMaterial,
  24979. Material
  24980. };
  24981. return new materialLib[ type ]();
  24982. }
  24983. }
  24984. class LoaderUtils {
  24985. static decodeText( array ) {
  24986. if ( typeof TextDecoder !== 'undefined' ) {
  24987. return new TextDecoder().decode( array );
  24988. }
  24989. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24990. // throws a "maximum call stack size exceeded" error for large arrays.
  24991. let s = '';
  24992. for ( let i = 0, il = array.length; i < il; i ++ ) {
  24993. // Implicitly assumes little-endian.
  24994. s += String.fromCharCode( array[ i ] );
  24995. }
  24996. try {
  24997. // merges multi-byte utf-8 characters.
  24998. return decodeURIComponent( escape( s ) );
  24999. } catch ( e ) { // see #16358
  25000. return s;
  25001. }
  25002. }
  25003. static extractUrlBase( url ) {
  25004. const index = url.lastIndexOf( '/' );
  25005. if ( index === - 1 ) return './';
  25006. return url.slice( 0, index + 1 );
  25007. }
  25008. static resolveURL( url, path ) {
  25009. // Invalid URL
  25010. if ( typeof url !== 'string' || url === '' ) return '';
  25011. // Host Relative URL
  25012. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  25013. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  25014. }
  25015. // Absolute URL http://,https://,//
  25016. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  25017. // Data URI
  25018. if ( /^data:.*,.*$/i.test( url ) ) return url;
  25019. // Blob URL
  25020. if ( /^blob:.*$/i.test( url ) ) return url;
  25021. // Relative URL
  25022. return path + url;
  25023. }
  25024. }
  25025. class InstancedBufferGeometry extends BufferGeometry {
  25026. constructor() {
  25027. super();
  25028. this.isInstancedBufferGeometry = true;
  25029. this.type = 'InstancedBufferGeometry';
  25030. this.instanceCount = Infinity;
  25031. }
  25032. copy( source ) {
  25033. super.copy( source );
  25034. this.instanceCount = source.instanceCount;
  25035. return this;
  25036. }
  25037. toJSON() {
  25038. const data = super.toJSON();
  25039. data.instanceCount = this.instanceCount;
  25040. data.isInstancedBufferGeometry = true;
  25041. return data;
  25042. }
  25043. }
  25044. class BufferGeometryLoader extends Loader {
  25045. constructor( manager ) {
  25046. super( manager );
  25047. }
  25048. load( url, onLoad, onProgress, onError ) {
  25049. const scope = this;
  25050. const loader = new FileLoader( scope.manager );
  25051. loader.setPath( scope.path );
  25052. loader.setRequestHeader( scope.requestHeader );
  25053. loader.setWithCredentials( scope.withCredentials );
  25054. loader.load( url, function ( text ) {
  25055. try {
  25056. onLoad( scope.parse( JSON.parse( text ) ) );
  25057. } catch ( e ) {
  25058. if ( onError ) {
  25059. onError( e );
  25060. } else {
  25061. console.error( e );
  25062. }
  25063. scope.manager.itemError( url );
  25064. }
  25065. }, onProgress, onError );
  25066. }
  25067. parse( json ) {
  25068. const interleavedBufferMap = {};
  25069. const arrayBufferMap = {};
  25070. function getInterleavedBuffer( json, uuid ) {
  25071. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  25072. const interleavedBuffers = json.interleavedBuffers;
  25073. const interleavedBuffer = interleavedBuffers[ uuid ];
  25074. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  25075. const array = getTypedArray( interleavedBuffer.type, buffer );
  25076. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  25077. ib.uuid = interleavedBuffer.uuid;
  25078. interleavedBufferMap[ uuid ] = ib;
  25079. return ib;
  25080. }
  25081. function getArrayBuffer( json, uuid ) {
  25082. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  25083. const arrayBuffers = json.arrayBuffers;
  25084. const arrayBuffer = arrayBuffers[ uuid ];
  25085. const ab = new Uint32Array( arrayBuffer ).buffer;
  25086. arrayBufferMap[ uuid ] = ab;
  25087. return ab;
  25088. }
  25089. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  25090. const index = json.data.index;
  25091. if ( index !== undefined ) {
  25092. const typedArray = getTypedArray( index.type, index.array );
  25093. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  25094. }
  25095. const attributes = json.data.attributes;
  25096. for ( const key in attributes ) {
  25097. const attribute = attributes[ key ];
  25098. let bufferAttribute;
  25099. if ( attribute.isInterleavedBufferAttribute ) {
  25100. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25101. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25102. } else {
  25103. const typedArray = getTypedArray( attribute.type, attribute.array );
  25104. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  25105. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  25106. }
  25107. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25108. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  25109. if ( attribute.updateRange !== undefined ) {
  25110. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  25111. bufferAttribute.updateRange.count = attribute.updateRange.count;
  25112. }
  25113. geometry.setAttribute( key, bufferAttribute );
  25114. }
  25115. const morphAttributes = json.data.morphAttributes;
  25116. if ( morphAttributes ) {
  25117. for ( const key in morphAttributes ) {
  25118. const attributeArray = morphAttributes[ key ];
  25119. const array = [];
  25120. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  25121. const attribute = attributeArray[ i ];
  25122. let bufferAttribute;
  25123. if ( attribute.isInterleavedBufferAttribute ) {
  25124. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25125. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25126. } else {
  25127. const typedArray = getTypedArray( attribute.type, attribute.array );
  25128. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  25129. }
  25130. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25131. array.push( bufferAttribute );
  25132. }
  25133. geometry.morphAttributes[ key ] = array;
  25134. }
  25135. }
  25136. const morphTargetsRelative = json.data.morphTargetsRelative;
  25137. if ( morphTargetsRelative ) {
  25138. geometry.morphTargetsRelative = true;
  25139. }
  25140. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  25141. if ( groups !== undefined ) {
  25142. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  25143. const group = groups[ i ];
  25144. geometry.addGroup( group.start, group.count, group.materialIndex );
  25145. }
  25146. }
  25147. const boundingSphere = json.data.boundingSphere;
  25148. if ( boundingSphere !== undefined ) {
  25149. const center = new Vector3();
  25150. if ( boundingSphere.center !== undefined ) {
  25151. center.fromArray( boundingSphere.center );
  25152. }
  25153. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  25154. }
  25155. if ( json.name ) geometry.name = json.name;
  25156. if ( json.userData ) geometry.userData = json.userData;
  25157. return geometry;
  25158. }
  25159. }
  25160. class ObjectLoader extends Loader {
  25161. constructor( manager ) {
  25162. super( manager );
  25163. }
  25164. load( url, onLoad, onProgress, onError ) {
  25165. const scope = this;
  25166. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  25167. this.resourcePath = this.resourcePath || path;
  25168. const loader = new FileLoader( this.manager );
  25169. loader.setPath( this.path );
  25170. loader.setRequestHeader( this.requestHeader );
  25171. loader.setWithCredentials( this.withCredentials );
  25172. loader.load( url, function ( text ) {
  25173. let json = null;
  25174. try {
  25175. json = JSON.parse( text );
  25176. } catch ( error ) {
  25177. if ( onError !== undefined ) onError( error );
  25178. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  25179. return;
  25180. }
  25181. const metadata = json.metadata;
  25182. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25183. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  25184. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  25185. return;
  25186. }
  25187. scope.parse( json, onLoad );
  25188. }, onProgress, onError );
  25189. }
  25190. async loadAsync( url, onProgress ) {
  25191. const scope = this;
  25192. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  25193. this.resourcePath = this.resourcePath || path;
  25194. const loader = new FileLoader( this.manager );
  25195. loader.setPath( this.path );
  25196. loader.setRequestHeader( this.requestHeader );
  25197. loader.setWithCredentials( this.withCredentials );
  25198. const text = await loader.loadAsync( url, onProgress );
  25199. const json = JSON.parse( text );
  25200. const metadata = json.metadata;
  25201. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25202. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  25203. }
  25204. return await scope.parseAsync( json );
  25205. }
  25206. parse( json, onLoad ) {
  25207. const animations = this.parseAnimations( json.animations );
  25208. const shapes = this.parseShapes( json.shapes );
  25209. const geometries = this.parseGeometries( json.geometries, shapes );
  25210. const images = this.parseImages( json.images, function () {
  25211. if ( onLoad !== undefined ) onLoad( object );
  25212. } );
  25213. const textures = this.parseTextures( json.textures, images );
  25214. const materials = this.parseMaterials( json.materials, textures );
  25215. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  25216. const skeletons = this.parseSkeletons( json.skeletons, object );
  25217. this.bindSkeletons( object, skeletons );
  25218. //
  25219. if ( onLoad !== undefined ) {
  25220. let hasImages = false;
  25221. for ( const uuid in images ) {
  25222. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  25223. hasImages = true;
  25224. break;
  25225. }
  25226. }
  25227. if ( hasImages === false ) onLoad( object );
  25228. }
  25229. return object;
  25230. }
  25231. async parseAsync( json ) {
  25232. const animations = this.parseAnimations( json.animations );
  25233. const shapes = this.parseShapes( json.shapes );
  25234. const geometries = this.parseGeometries( json.geometries, shapes );
  25235. const images = await this.parseImagesAsync( json.images );
  25236. const textures = this.parseTextures( json.textures, images );
  25237. const materials = this.parseMaterials( json.materials, textures );
  25238. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  25239. const skeletons = this.parseSkeletons( json.skeletons, object );
  25240. this.bindSkeletons( object, skeletons );
  25241. return object;
  25242. }
  25243. parseShapes( json ) {
  25244. const shapes = {};
  25245. if ( json !== undefined ) {
  25246. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25247. const shape = new Shape().fromJSON( json[ i ] );
  25248. shapes[ shape.uuid ] = shape;
  25249. }
  25250. }
  25251. return shapes;
  25252. }
  25253. parseSkeletons( json, object ) {
  25254. const skeletons = {};
  25255. const bones = {};
  25256. // generate bone lookup table
  25257. object.traverse( function ( child ) {
  25258. if ( child.isBone ) bones[ child.uuid ] = child;
  25259. } );
  25260. // create skeletons
  25261. if ( json !== undefined ) {
  25262. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25263. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  25264. skeletons[ skeleton.uuid ] = skeleton;
  25265. }
  25266. }
  25267. return skeletons;
  25268. }
  25269. parseGeometries( json, shapes ) {
  25270. const geometries = {};
  25271. if ( json !== undefined ) {
  25272. const bufferGeometryLoader = new BufferGeometryLoader();
  25273. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25274. let geometry;
  25275. const data = json[ i ];
  25276. switch ( data.type ) {
  25277. case 'BufferGeometry':
  25278. case 'InstancedBufferGeometry':
  25279. geometry = bufferGeometryLoader.parse( data );
  25280. break;
  25281. default:
  25282. if ( data.type in Geometries ) {
  25283. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  25284. } else {
  25285. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  25286. }
  25287. }
  25288. geometry.uuid = data.uuid;
  25289. if ( data.name !== undefined ) geometry.name = data.name;
  25290. if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData;
  25291. geometries[ data.uuid ] = geometry;
  25292. }
  25293. }
  25294. return geometries;
  25295. }
  25296. parseMaterials( json, textures ) {
  25297. const cache = {}; // MultiMaterial
  25298. const materials = {};
  25299. if ( json !== undefined ) {
  25300. const loader = new MaterialLoader();
  25301. loader.setTextures( textures );
  25302. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25303. const data = json[ i ];
  25304. if ( cache[ data.uuid ] === undefined ) {
  25305. cache[ data.uuid ] = loader.parse( data );
  25306. }
  25307. materials[ data.uuid ] = cache[ data.uuid ];
  25308. }
  25309. }
  25310. return materials;
  25311. }
  25312. parseAnimations( json ) {
  25313. const animations = {};
  25314. if ( json !== undefined ) {
  25315. for ( let i = 0; i < json.length; i ++ ) {
  25316. const data = json[ i ];
  25317. const clip = AnimationClip.parse( data );
  25318. animations[ clip.uuid ] = clip;
  25319. }
  25320. }
  25321. return animations;
  25322. }
  25323. parseImages( json, onLoad ) {
  25324. const scope = this;
  25325. const images = {};
  25326. let loader;
  25327. function loadImage( url ) {
  25328. scope.manager.itemStart( url );
  25329. return loader.load( url, function () {
  25330. scope.manager.itemEnd( url );
  25331. }, undefined, function () {
  25332. scope.manager.itemError( url );
  25333. scope.manager.itemEnd( url );
  25334. } );
  25335. }
  25336. function deserializeImage( image ) {
  25337. if ( typeof image === 'string' ) {
  25338. const url = image;
  25339. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25340. return loadImage( path );
  25341. } else {
  25342. if ( image.data ) {
  25343. return {
  25344. data: getTypedArray( image.type, image.data ),
  25345. width: image.width,
  25346. height: image.height
  25347. };
  25348. } else {
  25349. return null;
  25350. }
  25351. }
  25352. }
  25353. if ( json !== undefined && json.length > 0 ) {
  25354. const manager = new LoadingManager( onLoad );
  25355. loader = new ImageLoader( manager );
  25356. loader.setCrossOrigin( this.crossOrigin );
  25357. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25358. const image = json[ i ];
  25359. const url = image.url;
  25360. if ( Array.isArray( url ) ) {
  25361. // load array of images e.g CubeTexture
  25362. const imageArray = [];
  25363. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25364. const currentUrl = url[ j ];
  25365. const deserializedImage = deserializeImage( currentUrl );
  25366. if ( deserializedImage !== null ) {
  25367. if ( deserializedImage instanceof HTMLImageElement ) {
  25368. imageArray.push( deserializedImage );
  25369. } else {
  25370. // special case: handle array of data textures for cube textures
  25371. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25372. }
  25373. }
  25374. }
  25375. images[ image.uuid ] = new Source( imageArray );
  25376. } else {
  25377. // load single image
  25378. const deserializedImage = deserializeImage( image.url );
  25379. images[ image.uuid ] = new Source( deserializedImage );
  25380. }
  25381. }
  25382. }
  25383. return images;
  25384. }
  25385. async parseImagesAsync( json ) {
  25386. const scope = this;
  25387. const images = {};
  25388. let loader;
  25389. async function deserializeImage( image ) {
  25390. if ( typeof image === 'string' ) {
  25391. const url = image;
  25392. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25393. return await loader.loadAsync( path );
  25394. } else {
  25395. if ( image.data ) {
  25396. return {
  25397. data: getTypedArray( image.type, image.data ),
  25398. width: image.width,
  25399. height: image.height
  25400. };
  25401. } else {
  25402. return null;
  25403. }
  25404. }
  25405. }
  25406. if ( json !== undefined && json.length > 0 ) {
  25407. loader = new ImageLoader( this.manager );
  25408. loader.setCrossOrigin( this.crossOrigin );
  25409. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25410. const image = json[ i ];
  25411. const url = image.url;
  25412. if ( Array.isArray( url ) ) {
  25413. // load array of images e.g CubeTexture
  25414. const imageArray = [];
  25415. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25416. const currentUrl = url[ j ];
  25417. const deserializedImage = await deserializeImage( currentUrl );
  25418. if ( deserializedImage !== null ) {
  25419. if ( deserializedImage instanceof HTMLImageElement ) {
  25420. imageArray.push( deserializedImage );
  25421. } else {
  25422. // special case: handle array of data textures for cube textures
  25423. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25424. }
  25425. }
  25426. }
  25427. images[ image.uuid ] = new Source( imageArray );
  25428. } else {
  25429. // load single image
  25430. const deserializedImage = await deserializeImage( image.url );
  25431. images[ image.uuid ] = new Source( deserializedImage );
  25432. }
  25433. }
  25434. }
  25435. return images;
  25436. }
  25437. parseTextures( json, images ) {
  25438. function parseConstant( value, type ) {
  25439. if ( typeof value === 'number' ) return value;
  25440. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  25441. return type[ value ];
  25442. }
  25443. const textures = {};
  25444. if ( json !== undefined ) {
  25445. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25446. const data = json[ i ];
  25447. if ( data.image === undefined ) {
  25448. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  25449. }
  25450. if ( images[ data.image ] === undefined ) {
  25451. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  25452. }
  25453. const source = images[ data.image ];
  25454. const image = source.data;
  25455. let texture;
  25456. if ( Array.isArray( image ) ) {
  25457. texture = new CubeTexture();
  25458. if ( image.length === 6 ) texture.needsUpdate = true;
  25459. } else {
  25460. if ( image && image.data ) {
  25461. texture = new DataTexture();
  25462. } else {
  25463. texture = new Texture();
  25464. }
  25465. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  25466. }
  25467. texture.source = source;
  25468. texture.uuid = data.uuid;
  25469. if ( data.name !== undefined ) texture.name = data.name;
  25470. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  25471. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  25472. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  25473. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  25474. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  25475. if ( data.wrap !== undefined ) {
  25476. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  25477. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  25478. }
  25479. if ( data.format !== undefined ) texture.format = data.format;
  25480. if ( data.type !== undefined ) texture.type = data.type;
  25481. if ( data.encoding !== undefined ) texture.encoding = data.encoding;
  25482. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  25483. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  25484. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  25485. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  25486. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  25487. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  25488. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  25489. if ( data.userData !== undefined ) texture.userData = data.userData;
  25490. textures[ data.uuid ] = texture;
  25491. }
  25492. }
  25493. return textures;
  25494. }
  25495. parseObject( data, geometries, materials, textures, animations ) {
  25496. let object;
  25497. function getGeometry( name ) {
  25498. if ( geometries[ name ] === undefined ) {
  25499. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  25500. }
  25501. return geometries[ name ];
  25502. }
  25503. function getMaterial( name ) {
  25504. if ( name === undefined ) return undefined;
  25505. if ( Array.isArray( name ) ) {
  25506. const array = [];
  25507. for ( let i = 0, l = name.length; i < l; i ++ ) {
  25508. const uuid = name[ i ];
  25509. if ( materials[ uuid ] === undefined ) {
  25510. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  25511. }
  25512. array.push( materials[ uuid ] );
  25513. }
  25514. return array;
  25515. }
  25516. if ( materials[ name ] === undefined ) {
  25517. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  25518. }
  25519. return materials[ name ];
  25520. }
  25521. function getTexture( uuid ) {
  25522. if ( textures[ uuid ] === undefined ) {
  25523. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  25524. }
  25525. return textures[ uuid ];
  25526. }
  25527. let geometry, material;
  25528. switch ( data.type ) {
  25529. case 'Scene':
  25530. object = new Scene();
  25531. if ( data.background !== undefined ) {
  25532. if ( Number.isInteger( data.background ) ) {
  25533. object.background = new Color( data.background );
  25534. } else {
  25535. object.background = getTexture( data.background );
  25536. }
  25537. }
  25538. if ( data.environment !== undefined ) {
  25539. object.environment = getTexture( data.environment );
  25540. }
  25541. if ( data.fog !== undefined ) {
  25542. if ( data.fog.type === 'Fog' ) {
  25543. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  25544. } else if ( data.fog.type === 'FogExp2' ) {
  25545. object.fog = new FogExp2( data.fog.color, data.fog.density );
  25546. }
  25547. }
  25548. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  25549. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  25550. break;
  25551. case 'PerspectiveCamera':
  25552. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  25553. if ( data.focus !== undefined ) object.focus = data.focus;
  25554. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25555. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  25556. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  25557. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25558. break;
  25559. case 'OrthographicCamera':
  25560. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  25561. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25562. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25563. break;
  25564. case 'AmbientLight':
  25565. object = new AmbientLight( data.color, data.intensity );
  25566. break;
  25567. case 'DirectionalLight':
  25568. object = new DirectionalLight( data.color, data.intensity );
  25569. break;
  25570. case 'PointLight':
  25571. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  25572. break;
  25573. case 'RectAreaLight':
  25574. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  25575. break;
  25576. case 'SpotLight':
  25577. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  25578. break;
  25579. case 'HemisphereLight':
  25580. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  25581. break;
  25582. case 'LightProbe':
  25583. object = new LightProbe().fromJSON( data );
  25584. break;
  25585. case 'SkinnedMesh':
  25586. geometry = getGeometry( data.geometry );
  25587. material = getMaterial( data.material );
  25588. object = new SkinnedMesh( geometry, material );
  25589. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  25590. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  25591. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  25592. break;
  25593. case 'Mesh':
  25594. geometry = getGeometry( data.geometry );
  25595. material = getMaterial( data.material );
  25596. object = new Mesh( geometry, material );
  25597. break;
  25598. case 'InstancedMesh':
  25599. geometry = getGeometry( data.geometry );
  25600. material = getMaterial( data.material );
  25601. const count = data.count;
  25602. const instanceMatrix = data.instanceMatrix;
  25603. const instanceColor = data.instanceColor;
  25604. object = new InstancedMesh( geometry, material, count );
  25605. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  25606. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  25607. break;
  25608. case 'LOD':
  25609. object = new LOD();
  25610. break;
  25611. case 'Line':
  25612. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  25613. break;
  25614. case 'LineLoop':
  25615. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  25616. break;
  25617. case 'LineSegments':
  25618. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  25619. break;
  25620. case 'PointCloud':
  25621. case 'Points':
  25622. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  25623. break;
  25624. case 'Sprite':
  25625. object = new Sprite( getMaterial( data.material ) );
  25626. break;
  25627. case 'Group':
  25628. object = new Group();
  25629. break;
  25630. case 'Bone':
  25631. object = new Bone();
  25632. break;
  25633. default:
  25634. object = new Object3D();
  25635. }
  25636. object.uuid = data.uuid;
  25637. if ( data.name !== undefined ) object.name = data.name;
  25638. if ( data.matrix !== undefined ) {
  25639. object.matrix.fromArray( data.matrix );
  25640. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  25641. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  25642. } else {
  25643. if ( data.position !== undefined ) object.position.fromArray( data.position );
  25644. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  25645. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  25646. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  25647. }
  25648. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  25649. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  25650. if ( data.shadow ) {
  25651. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  25652. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  25653. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  25654. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  25655. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  25656. }
  25657. if ( data.visible !== undefined ) object.visible = data.visible;
  25658. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  25659. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  25660. if ( data.userData !== undefined ) object.userData = data.userData;
  25661. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  25662. if ( data.children !== undefined ) {
  25663. const children = data.children;
  25664. for ( let i = 0; i < children.length; i ++ ) {
  25665. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  25666. }
  25667. }
  25668. if ( data.animations !== undefined ) {
  25669. const objectAnimations = data.animations;
  25670. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  25671. const uuid = objectAnimations[ i ];
  25672. object.animations.push( animations[ uuid ] );
  25673. }
  25674. }
  25675. if ( data.type === 'LOD' ) {
  25676. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  25677. const levels = data.levels;
  25678. for ( let l = 0; l < levels.length; l ++ ) {
  25679. const level = levels[ l ];
  25680. const child = object.getObjectByProperty( 'uuid', level.object );
  25681. if ( child !== undefined ) {
  25682. object.addLevel( child, level.distance, level.hysteresis );
  25683. }
  25684. }
  25685. }
  25686. return object;
  25687. }
  25688. bindSkeletons( object, skeletons ) {
  25689. if ( Object.keys( skeletons ).length === 0 ) return;
  25690. object.traverse( function ( child ) {
  25691. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  25692. const skeleton = skeletons[ child.skeleton ];
  25693. if ( skeleton === undefined ) {
  25694. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  25695. } else {
  25696. child.bind( skeleton, child.bindMatrix );
  25697. }
  25698. }
  25699. } );
  25700. }
  25701. }
  25702. const TEXTURE_MAPPING = {
  25703. UVMapping: UVMapping,
  25704. CubeReflectionMapping: CubeReflectionMapping,
  25705. CubeRefractionMapping: CubeRefractionMapping,
  25706. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25707. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25708. CubeUVReflectionMapping: CubeUVReflectionMapping
  25709. };
  25710. const TEXTURE_WRAPPING = {
  25711. RepeatWrapping: RepeatWrapping,
  25712. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25713. MirroredRepeatWrapping: MirroredRepeatWrapping
  25714. };
  25715. const TEXTURE_FILTER = {
  25716. NearestFilter: NearestFilter,
  25717. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  25718. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  25719. LinearFilter: LinearFilter,
  25720. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  25721. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  25722. };
  25723. class ImageBitmapLoader extends Loader {
  25724. constructor( manager ) {
  25725. super( manager );
  25726. this.isImageBitmapLoader = true;
  25727. if ( typeof createImageBitmap === 'undefined' ) {
  25728. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  25729. }
  25730. if ( typeof fetch === 'undefined' ) {
  25731. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  25732. }
  25733. this.options = { premultiplyAlpha: 'none' };
  25734. }
  25735. setOptions( options ) {
  25736. this.options = options;
  25737. return this;
  25738. }
  25739. load( url, onLoad, onProgress, onError ) {
  25740. if ( url === undefined ) url = '';
  25741. if ( this.path !== undefined ) url = this.path + url;
  25742. url = this.manager.resolveURL( url );
  25743. const scope = this;
  25744. const cached = Cache.get( url );
  25745. if ( cached !== undefined ) {
  25746. scope.manager.itemStart( url );
  25747. setTimeout( function () {
  25748. if ( onLoad ) onLoad( cached );
  25749. scope.manager.itemEnd( url );
  25750. }, 0 );
  25751. return cached;
  25752. }
  25753. const fetchOptions = {};
  25754. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  25755. fetchOptions.headers = this.requestHeader;
  25756. fetch( url, fetchOptions ).then( function ( res ) {
  25757. return res.blob();
  25758. } ).then( function ( blob ) {
  25759. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  25760. } ).then( function ( imageBitmap ) {
  25761. Cache.add( url, imageBitmap );
  25762. if ( onLoad ) onLoad( imageBitmap );
  25763. scope.manager.itemEnd( url );
  25764. } ).catch( function ( e ) {
  25765. if ( onError ) onError( e );
  25766. scope.manager.itemError( url );
  25767. scope.manager.itemEnd( url );
  25768. } );
  25769. scope.manager.itemStart( url );
  25770. }
  25771. }
  25772. let _context;
  25773. class AudioContext {
  25774. static getContext() {
  25775. if ( _context === undefined ) {
  25776. _context = new ( window.AudioContext || window.webkitAudioContext )();
  25777. }
  25778. return _context;
  25779. }
  25780. static setContext( value ) {
  25781. _context = value;
  25782. }
  25783. }
  25784. class AudioLoader extends Loader {
  25785. constructor( manager ) {
  25786. super( manager );
  25787. }
  25788. load( url, onLoad, onProgress, onError ) {
  25789. const scope = this;
  25790. const loader = new FileLoader( this.manager );
  25791. loader.setResponseType( 'arraybuffer' );
  25792. loader.setPath( this.path );
  25793. loader.setRequestHeader( this.requestHeader );
  25794. loader.setWithCredentials( this.withCredentials );
  25795. loader.load( url, function ( buffer ) {
  25796. try {
  25797. // Create a copy of the buffer. The `decodeAudioData` method
  25798. // detaches the buffer when complete, preventing reuse.
  25799. const bufferCopy = buffer.slice( 0 );
  25800. const context = AudioContext.getContext();
  25801. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  25802. onLoad( audioBuffer );
  25803. } );
  25804. } catch ( e ) {
  25805. if ( onError ) {
  25806. onError( e );
  25807. } else {
  25808. console.error( e );
  25809. }
  25810. scope.manager.itemError( url );
  25811. }
  25812. }, onProgress, onError );
  25813. }
  25814. }
  25815. class HemisphereLightProbe extends LightProbe {
  25816. constructor( skyColor, groundColor, intensity = 1 ) {
  25817. super( undefined, intensity );
  25818. this.isHemisphereLightProbe = true;
  25819. const color1 = new Color().set( skyColor );
  25820. const color2 = new Color().set( groundColor );
  25821. const sky = new Vector3( color1.r, color1.g, color1.b );
  25822. const ground = new Vector3( color2.r, color2.g, color2.b );
  25823. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  25824. const c0 = Math.sqrt( Math.PI );
  25825. const c1 = c0 * Math.sqrt( 0.75 );
  25826. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  25827. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  25828. }
  25829. }
  25830. class AmbientLightProbe extends LightProbe {
  25831. constructor( color, intensity = 1 ) {
  25832. super( undefined, intensity );
  25833. this.isAmbientLightProbe = true;
  25834. const color1 = new Color().set( color );
  25835. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  25836. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  25837. }
  25838. }
  25839. const _eyeRight = /*@__PURE__*/ new Matrix4();
  25840. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  25841. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  25842. class StereoCamera {
  25843. constructor() {
  25844. this.type = 'StereoCamera';
  25845. this.aspect = 1;
  25846. this.eyeSep = 0.064;
  25847. this.cameraL = new PerspectiveCamera();
  25848. this.cameraL.layers.enable( 1 );
  25849. this.cameraL.matrixAutoUpdate = false;
  25850. this.cameraR = new PerspectiveCamera();
  25851. this.cameraR.layers.enable( 2 );
  25852. this.cameraR.matrixAutoUpdate = false;
  25853. this._cache = {
  25854. focus: null,
  25855. fov: null,
  25856. aspect: null,
  25857. near: null,
  25858. far: null,
  25859. zoom: null,
  25860. eyeSep: null
  25861. };
  25862. }
  25863. update( camera ) {
  25864. const cache = this._cache;
  25865. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  25866. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  25867. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  25868. if ( needsUpdate ) {
  25869. cache.focus = camera.focus;
  25870. cache.fov = camera.fov;
  25871. cache.aspect = camera.aspect * this.aspect;
  25872. cache.near = camera.near;
  25873. cache.far = camera.far;
  25874. cache.zoom = camera.zoom;
  25875. cache.eyeSep = this.eyeSep;
  25876. // Off-axis stereoscopic effect based on
  25877. // http://paulbourke.net/stereographics/stereorender/
  25878. _projectionMatrix.copy( camera.projectionMatrix );
  25879. const eyeSepHalf = cache.eyeSep / 2;
  25880. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25881. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  25882. let xmin, xmax;
  25883. // translate xOffset
  25884. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  25885. _eyeRight.elements[ 12 ] = eyeSepHalf;
  25886. // for left eye
  25887. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  25888. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25889. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25890. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25891. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  25892. // for right eye
  25893. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  25894. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25895. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25896. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25897. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  25898. }
  25899. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  25900. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  25901. }
  25902. }
  25903. class Clock {
  25904. constructor( autoStart = true ) {
  25905. this.autoStart = autoStart;
  25906. this.startTime = 0;
  25907. this.oldTime = 0;
  25908. this.elapsedTime = 0;
  25909. this.running = false;
  25910. }
  25911. start() {
  25912. this.startTime = now();
  25913. this.oldTime = this.startTime;
  25914. this.elapsedTime = 0;
  25915. this.running = true;
  25916. }
  25917. stop() {
  25918. this.getElapsedTime();
  25919. this.running = false;
  25920. this.autoStart = false;
  25921. }
  25922. getElapsedTime() {
  25923. this.getDelta();
  25924. return this.elapsedTime;
  25925. }
  25926. getDelta() {
  25927. let diff = 0;
  25928. if ( this.autoStart && ! this.running ) {
  25929. this.start();
  25930. return 0;
  25931. }
  25932. if ( this.running ) {
  25933. const newTime = now();
  25934. diff = ( newTime - this.oldTime ) / 1000;
  25935. this.oldTime = newTime;
  25936. this.elapsedTime += diff;
  25937. }
  25938. return diff;
  25939. }
  25940. }
  25941. function now() {
  25942. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  25943. }
  25944. const _position$1 = /*@__PURE__*/ new Vector3();
  25945. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  25946. const _scale$1 = /*@__PURE__*/ new Vector3();
  25947. const _orientation$1 = /*@__PURE__*/ new Vector3();
  25948. class AudioListener extends Object3D {
  25949. constructor() {
  25950. super();
  25951. this.type = 'AudioListener';
  25952. this.context = AudioContext.getContext();
  25953. this.gain = this.context.createGain();
  25954. this.gain.connect( this.context.destination );
  25955. this.filter = null;
  25956. this.timeDelta = 0;
  25957. // private
  25958. this._clock = new Clock();
  25959. }
  25960. getInput() {
  25961. return this.gain;
  25962. }
  25963. removeFilter() {
  25964. if ( this.filter !== null ) {
  25965. this.gain.disconnect( this.filter );
  25966. this.filter.disconnect( this.context.destination );
  25967. this.gain.connect( this.context.destination );
  25968. this.filter = null;
  25969. }
  25970. return this;
  25971. }
  25972. getFilter() {
  25973. return this.filter;
  25974. }
  25975. setFilter( value ) {
  25976. if ( this.filter !== null ) {
  25977. this.gain.disconnect( this.filter );
  25978. this.filter.disconnect( this.context.destination );
  25979. } else {
  25980. this.gain.disconnect( this.context.destination );
  25981. }
  25982. this.filter = value;
  25983. this.gain.connect( this.filter );
  25984. this.filter.connect( this.context.destination );
  25985. return this;
  25986. }
  25987. getMasterVolume() {
  25988. return this.gain.gain.value;
  25989. }
  25990. setMasterVolume( value ) {
  25991. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  25992. return this;
  25993. }
  25994. updateMatrixWorld( force ) {
  25995. super.updateMatrixWorld( force );
  25996. const listener = this.context.listener;
  25997. const up = this.up;
  25998. this.timeDelta = this._clock.getDelta();
  25999. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  26000. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  26001. if ( listener.positionX ) {
  26002. // code path for Chrome (see #14393)
  26003. const endTime = this.context.currentTime + this.timeDelta;
  26004. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  26005. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  26006. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  26007. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  26008. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  26009. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  26010. listener.upX.linearRampToValueAtTime( up.x, endTime );
  26011. listener.upY.linearRampToValueAtTime( up.y, endTime );
  26012. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  26013. } else {
  26014. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  26015. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  26016. }
  26017. }
  26018. }
  26019. class Audio extends Object3D {
  26020. constructor( listener ) {
  26021. super();
  26022. this.type = 'Audio';
  26023. this.listener = listener;
  26024. this.context = listener.context;
  26025. this.gain = this.context.createGain();
  26026. this.gain.connect( listener.getInput() );
  26027. this.autoplay = false;
  26028. this.buffer = null;
  26029. this.detune = 0;
  26030. this.loop = false;
  26031. this.loopStart = 0;
  26032. this.loopEnd = 0;
  26033. this.offset = 0;
  26034. this.duration = undefined;
  26035. this.playbackRate = 1;
  26036. this.isPlaying = false;
  26037. this.hasPlaybackControl = true;
  26038. this.source = null;
  26039. this.sourceType = 'empty';
  26040. this._startedAt = 0;
  26041. this._progress = 0;
  26042. this._connected = false;
  26043. this.filters = [];
  26044. }
  26045. getOutput() {
  26046. return this.gain;
  26047. }
  26048. setNodeSource( audioNode ) {
  26049. this.hasPlaybackControl = false;
  26050. this.sourceType = 'audioNode';
  26051. this.source = audioNode;
  26052. this.connect();
  26053. return this;
  26054. }
  26055. setMediaElementSource( mediaElement ) {
  26056. this.hasPlaybackControl = false;
  26057. this.sourceType = 'mediaNode';
  26058. this.source = this.context.createMediaElementSource( mediaElement );
  26059. this.connect();
  26060. return this;
  26061. }
  26062. setMediaStreamSource( mediaStream ) {
  26063. this.hasPlaybackControl = false;
  26064. this.sourceType = 'mediaStreamNode';
  26065. this.source = this.context.createMediaStreamSource( mediaStream );
  26066. this.connect();
  26067. return this;
  26068. }
  26069. setBuffer( audioBuffer ) {
  26070. this.buffer = audioBuffer;
  26071. this.sourceType = 'buffer';
  26072. if ( this.autoplay ) this.play();
  26073. return this;
  26074. }
  26075. play( delay = 0 ) {
  26076. if ( this.isPlaying === true ) {
  26077. console.warn( 'THREE.Audio: Audio is already playing.' );
  26078. return;
  26079. }
  26080. if ( this.hasPlaybackControl === false ) {
  26081. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26082. return;
  26083. }
  26084. this._startedAt = this.context.currentTime + delay;
  26085. const source = this.context.createBufferSource();
  26086. source.buffer = this.buffer;
  26087. source.loop = this.loop;
  26088. source.loopStart = this.loopStart;
  26089. source.loopEnd = this.loopEnd;
  26090. source.onended = this.onEnded.bind( this );
  26091. source.start( this._startedAt, this._progress + this.offset, this.duration );
  26092. this.isPlaying = true;
  26093. this.source = source;
  26094. this.setDetune( this.detune );
  26095. this.setPlaybackRate( this.playbackRate );
  26096. return this.connect();
  26097. }
  26098. pause() {
  26099. if ( this.hasPlaybackControl === false ) {
  26100. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26101. return;
  26102. }
  26103. if ( this.isPlaying === true ) {
  26104. // update current progress
  26105. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  26106. if ( this.loop === true ) {
  26107. // ensure _progress does not exceed duration with looped audios
  26108. this._progress = this._progress % ( this.duration || this.buffer.duration );
  26109. }
  26110. this.source.stop();
  26111. this.source.onended = null;
  26112. this.isPlaying = false;
  26113. }
  26114. return this;
  26115. }
  26116. stop() {
  26117. if ( this.hasPlaybackControl === false ) {
  26118. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26119. return;
  26120. }
  26121. this._progress = 0;
  26122. this.source.stop();
  26123. this.source.onended = null;
  26124. this.isPlaying = false;
  26125. return this;
  26126. }
  26127. connect() {
  26128. if ( this.filters.length > 0 ) {
  26129. this.source.connect( this.filters[ 0 ] );
  26130. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26131. this.filters[ i - 1 ].connect( this.filters[ i ] );
  26132. }
  26133. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  26134. } else {
  26135. this.source.connect( this.getOutput() );
  26136. }
  26137. this._connected = true;
  26138. return this;
  26139. }
  26140. disconnect() {
  26141. if ( this.filters.length > 0 ) {
  26142. this.source.disconnect( this.filters[ 0 ] );
  26143. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26144. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  26145. }
  26146. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  26147. } else {
  26148. this.source.disconnect( this.getOutput() );
  26149. }
  26150. this._connected = false;
  26151. return this;
  26152. }
  26153. getFilters() {
  26154. return this.filters;
  26155. }
  26156. setFilters( value ) {
  26157. if ( ! value ) value = [];
  26158. if ( this._connected === true ) {
  26159. this.disconnect();
  26160. this.filters = value.slice();
  26161. this.connect();
  26162. } else {
  26163. this.filters = value.slice();
  26164. }
  26165. return this;
  26166. }
  26167. setDetune( value ) {
  26168. this.detune = value;
  26169. if ( this.source.detune === undefined ) return; // only set detune when available
  26170. if ( this.isPlaying === true ) {
  26171. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  26172. }
  26173. return this;
  26174. }
  26175. getDetune() {
  26176. return this.detune;
  26177. }
  26178. getFilter() {
  26179. return this.getFilters()[ 0 ];
  26180. }
  26181. setFilter( filter ) {
  26182. return this.setFilters( filter ? [ filter ] : [] );
  26183. }
  26184. setPlaybackRate( value ) {
  26185. if ( this.hasPlaybackControl === false ) {
  26186. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26187. return;
  26188. }
  26189. this.playbackRate = value;
  26190. if ( this.isPlaying === true ) {
  26191. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  26192. }
  26193. return this;
  26194. }
  26195. getPlaybackRate() {
  26196. return this.playbackRate;
  26197. }
  26198. onEnded() {
  26199. this.isPlaying = false;
  26200. }
  26201. getLoop() {
  26202. if ( this.hasPlaybackControl === false ) {
  26203. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26204. return false;
  26205. }
  26206. return this.loop;
  26207. }
  26208. setLoop( value ) {
  26209. if ( this.hasPlaybackControl === false ) {
  26210. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26211. return;
  26212. }
  26213. this.loop = value;
  26214. if ( this.isPlaying === true ) {
  26215. this.source.loop = this.loop;
  26216. }
  26217. return this;
  26218. }
  26219. setLoopStart( value ) {
  26220. this.loopStart = value;
  26221. return this;
  26222. }
  26223. setLoopEnd( value ) {
  26224. this.loopEnd = value;
  26225. return this;
  26226. }
  26227. getVolume() {
  26228. return this.gain.gain.value;
  26229. }
  26230. setVolume( value ) {
  26231. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26232. return this;
  26233. }
  26234. }
  26235. const _position = /*@__PURE__*/ new Vector3();
  26236. const _quaternion = /*@__PURE__*/ new Quaternion();
  26237. const _scale = /*@__PURE__*/ new Vector3();
  26238. const _orientation = /*@__PURE__*/ new Vector3();
  26239. class PositionalAudio extends Audio {
  26240. constructor( listener ) {
  26241. super( listener );
  26242. this.panner = this.context.createPanner();
  26243. this.panner.panningModel = 'HRTF';
  26244. this.panner.connect( this.gain );
  26245. }
  26246. disconnect() {
  26247. super.disconnect();
  26248. this.panner.disconnect( this.gain );
  26249. }
  26250. getOutput() {
  26251. return this.panner;
  26252. }
  26253. getRefDistance() {
  26254. return this.panner.refDistance;
  26255. }
  26256. setRefDistance( value ) {
  26257. this.panner.refDistance = value;
  26258. return this;
  26259. }
  26260. getRolloffFactor() {
  26261. return this.panner.rolloffFactor;
  26262. }
  26263. setRolloffFactor( value ) {
  26264. this.panner.rolloffFactor = value;
  26265. return this;
  26266. }
  26267. getDistanceModel() {
  26268. return this.panner.distanceModel;
  26269. }
  26270. setDistanceModel( value ) {
  26271. this.panner.distanceModel = value;
  26272. return this;
  26273. }
  26274. getMaxDistance() {
  26275. return this.panner.maxDistance;
  26276. }
  26277. setMaxDistance( value ) {
  26278. this.panner.maxDistance = value;
  26279. return this;
  26280. }
  26281. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  26282. this.panner.coneInnerAngle = coneInnerAngle;
  26283. this.panner.coneOuterAngle = coneOuterAngle;
  26284. this.panner.coneOuterGain = coneOuterGain;
  26285. return this;
  26286. }
  26287. updateMatrixWorld( force ) {
  26288. super.updateMatrixWorld( force );
  26289. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  26290. this.matrixWorld.decompose( _position, _quaternion, _scale );
  26291. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  26292. const panner = this.panner;
  26293. if ( panner.positionX ) {
  26294. // code path for Chrome and Firefox (see #14393)
  26295. const endTime = this.context.currentTime + this.listener.timeDelta;
  26296. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  26297. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  26298. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  26299. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  26300. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  26301. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  26302. } else {
  26303. panner.setPosition( _position.x, _position.y, _position.z );
  26304. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  26305. }
  26306. }
  26307. }
  26308. class AudioAnalyser {
  26309. constructor( audio, fftSize = 2048 ) {
  26310. this.analyser = audio.context.createAnalyser();
  26311. this.analyser.fftSize = fftSize;
  26312. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  26313. audio.getOutput().connect( this.analyser );
  26314. }
  26315. getFrequencyData() {
  26316. this.analyser.getByteFrequencyData( this.data );
  26317. return this.data;
  26318. }
  26319. getAverageFrequency() {
  26320. let value = 0;
  26321. const data = this.getFrequencyData();
  26322. for ( let i = 0; i < data.length; i ++ ) {
  26323. value += data[ i ];
  26324. }
  26325. return value / data.length;
  26326. }
  26327. }
  26328. class PropertyMixer {
  26329. constructor( binding, typeName, valueSize ) {
  26330. this.binding = binding;
  26331. this.valueSize = valueSize;
  26332. let mixFunction,
  26333. mixFunctionAdditive,
  26334. setIdentity;
  26335. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  26336. //
  26337. // interpolators can use .buffer as their .result
  26338. // the data then goes to 'incoming'
  26339. //
  26340. // 'accu0' and 'accu1' are used frame-interleaved for
  26341. // the cumulative result and are compared to detect
  26342. // changes
  26343. //
  26344. // 'orig' stores the original state of the property
  26345. //
  26346. // 'add' is used for additive cumulative results
  26347. //
  26348. // 'work' is optional and is only present for quaternion types. It is used
  26349. // to store intermediate quaternion multiplication results
  26350. switch ( typeName ) {
  26351. case 'quaternion':
  26352. mixFunction = this._slerp;
  26353. mixFunctionAdditive = this._slerpAdditive;
  26354. setIdentity = this._setAdditiveIdentityQuaternion;
  26355. this.buffer = new Float64Array( valueSize * 6 );
  26356. this._workIndex = 5;
  26357. break;
  26358. case 'string':
  26359. case 'bool':
  26360. mixFunction = this._select;
  26361. // Use the regular mix function and for additive on these types,
  26362. // additive is not relevant for non-numeric types
  26363. mixFunctionAdditive = this._select;
  26364. setIdentity = this._setAdditiveIdentityOther;
  26365. this.buffer = new Array( valueSize * 5 );
  26366. break;
  26367. default:
  26368. mixFunction = this._lerp;
  26369. mixFunctionAdditive = this._lerpAdditive;
  26370. setIdentity = this._setAdditiveIdentityNumeric;
  26371. this.buffer = new Float64Array( valueSize * 5 );
  26372. }
  26373. this._mixBufferRegion = mixFunction;
  26374. this._mixBufferRegionAdditive = mixFunctionAdditive;
  26375. this._setIdentity = setIdentity;
  26376. this._origIndex = 3;
  26377. this._addIndex = 4;
  26378. this.cumulativeWeight = 0;
  26379. this.cumulativeWeightAdditive = 0;
  26380. this.useCount = 0;
  26381. this.referenceCount = 0;
  26382. }
  26383. // accumulate data in the 'incoming' region into 'accu<i>'
  26384. accumulate( accuIndex, weight ) {
  26385. // note: happily accumulating nothing when weight = 0, the caller knows
  26386. // the weight and shouldn't have made the call in the first place
  26387. const buffer = this.buffer,
  26388. stride = this.valueSize,
  26389. offset = accuIndex * stride + stride;
  26390. let currentWeight = this.cumulativeWeight;
  26391. if ( currentWeight === 0 ) {
  26392. // accuN := incoming * weight
  26393. for ( let i = 0; i !== stride; ++ i ) {
  26394. buffer[ offset + i ] = buffer[ i ];
  26395. }
  26396. currentWeight = weight;
  26397. } else {
  26398. // accuN := accuN + incoming * weight
  26399. currentWeight += weight;
  26400. const mix = weight / currentWeight;
  26401. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  26402. }
  26403. this.cumulativeWeight = currentWeight;
  26404. }
  26405. // accumulate data in the 'incoming' region into 'add'
  26406. accumulateAdditive( weight ) {
  26407. const buffer = this.buffer,
  26408. stride = this.valueSize,
  26409. offset = stride * this._addIndex;
  26410. if ( this.cumulativeWeightAdditive === 0 ) {
  26411. // add = identity
  26412. this._setIdentity();
  26413. }
  26414. // add := add + incoming * weight
  26415. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  26416. this.cumulativeWeightAdditive += weight;
  26417. }
  26418. // apply the state of 'accu<i>' to the binding when accus differ
  26419. apply( accuIndex ) {
  26420. const stride = this.valueSize,
  26421. buffer = this.buffer,
  26422. offset = accuIndex * stride + stride,
  26423. weight = this.cumulativeWeight,
  26424. weightAdditive = this.cumulativeWeightAdditive,
  26425. binding = this.binding;
  26426. this.cumulativeWeight = 0;
  26427. this.cumulativeWeightAdditive = 0;
  26428. if ( weight < 1 ) {
  26429. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26430. const originalValueOffset = stride * this._origIndex;
  26431. this._mixBufferRegion(
  26432. buffer, offset, originalValueOffset, 1 - weight, stride );
  26433. }
  26434. if ( weightAdditive > 0 ) {
  26435. // accuN := accuN + additive accuN
  26436. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  26437. }
  26438. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  26439. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  26440. // value has changed -> update scene graph
  26441. binding.setValue( buffer, offset );
  26442. break;
  26443. }
  26444. }
  26445. }
  26446. // remember the state of the bound property and copy it to both accus
  26447. saveOriginalState() {
  26448. const binding = this.binding;
  26449. const buffer = this.buffer,
  26450. stride = this.valueSize,
  26451. originalValueOffset = stride * this._origIndex;
  26452. binding.getValue( buffer, originalValueOffset );
  26453. // accu[0..1] := orig -- initially detect changes against the original
  26454. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  26455. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  26456. }
  26457. // Add to identity for additive
  26458. this._setIdentity();
  26459. this.cumulativeWeight = 0;
  26460. this.cumulativeWeightAdditive = 0;
  26461. }
  26462. // apply the state previously taken via 'saveOriginalState' to the binding
  26463. restoreOriginalState() {
  26464. const originalValueOffset = this.valueSize * 3;
  26465. this.binding.setValue( this.buffer, originalValueOffset );
  26466. }
  26467. _setAdditiveIdentityNumeric() {
  26468. const startIndex = this._addIndex * this.valueSize;
  26469. const endIndex = startIndex + this.valueSize;
  26470. for ( let i = startIndex; i < endIndex; i ++ ) {
  26471. this.buffer[ i ] = 0;
  26472. }
  26473. }
  26474. _setAdditiveIdentityQuaternion() {
  26475. this._setAdditiveIdentityNumeric();
  26476. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  26477. }
  26478. _setAdditiveIdentityOther() {
  26479. const startIndex = this._origIndex * this.valueSize;
  26480. const targetIndex = this._addIndex * this.valueSize;
  26481. for ( let i = 0; i < this.valueSize; i ++ ) {
  26482. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  26483. }
  26484. }
  26485. // mix functions
  26486. _select( buffer, dstOffset, srcOffset, t, stride ) {
  26487. if ( t >= 0.5 ) {
  26488. for ( let i = 0; i !== stride; ++ i ) {
  26489. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  26490. }
  26491. }
  26492. }
  26493. _slerp( buffer, dstOffset, srcOffset, t ) {
  26494. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  26495. }
  26496. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  26497. const workOffset = this._workIndex * stride;
  26498. // Store result in intermediate buffer offset
  26499. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  26500. // Slerp to the intermediate result
  26501. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  26502. }
  26503. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  26504. const s = 1 - t;
  26505. for ( let i = 0; i !== stride; ++ i ) {
  26506. const j = dstOffset + i;
  26507. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  26508. }
  26509. }
  26510. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  26511. for ( let i = 0; i !== stride; ++ i ) {
  26512. const j = dstOffset + i;
  26513. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  26514. }
  26515. }
  26516. }
  26517. // Characters [].:/ are reserved for track binding syntax.
  26518. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  26519. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  26520. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  26521. // only latin characters, and the unicode \p{L} is not yet supported. So
  26522. // instead, we exclude reserved characters and match everything else.
  26523. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  26524. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  26525. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  26526. // be matched to parse the rest of the track name.
  26527. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  26528. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  26529. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  26530. // Object on target node, and accessor. May not contain reserved
  26531. // characters. Accessor may contain any character except closing bracket.
  26532. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  26533. // Property and accessor. May not contain reserved characters. Accessor may
  26534. // contain any non-bracket characters.
  26535. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  26536. const _trackRe = new RegExp( ''
  26537. + '^'
  26538. + _directoryRe
  26539. + _nodeRe
  26540. + _objectRe
  26541. + _propertyRe
  26542. + '$'
  26543. );
  26544. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  26545. class Composite {
  26546. constructor( targetGroup, path, optionalParsedPath ) {
  26547. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  26548. this._targetGroup = targetGroup;
  26549. this._bindings = targetGroup.subscribe_( path, parsedPath );
  26550. }
  26551. getValue( array, offset ) {
  26552. this.bind(); // bind all binding
  26553. const firstValidIndex = this._targetGroup.nCachedObjects_,
  26554. binding = this._bindings[ firstValidIndex ];
  26555. // and only call .getValue on the first
  26556. if ( binding !== undefined ) binding.getValue( array, offset );
  26557. }
  26558. setValue( array, offset ) {
  26559. const bindings = this._bindings;
  26560. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26561. bindings[ i ].setValue( array, offset );
  26562. }
  26563. }
  26564. bind() {
  26565. const bindings = this._bindings;
  26566. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26567. bindings[ i ].bind();
  26568. }
  26569. }
  26570. unbind() {
  26571. const bindings = this._bindings;
  26572. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26573. bindings[ i ].unbind();
  26574. }
  26575. }
  26576. }
  26577. // Note: This class uses a State pattern on a per-method basis:
  26578. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  26579. // prototype version of these methods with one that represents
  26580. // the bound state. When the property is not found, the methods
  26581. // become no-ops.
  26582. class PropertyBinding {
  26583. constructor( rootNode, path, parsedPath ) {
  26584. this.path = path;
  26585. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  26586. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  26587. this.rootNode = rootNode;
  26588. // initial state of these methods that calls 'bind'
  26589. this.getValue = this._getValue_unbound;
  26590. this.setValue = this._setValue_unbound;
  26591. }
  26592. static create( root, path, parsedPath ) {
  26593. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  26594. return new PropertyBinding( root, path, parsedPath );
  26595. } else {
  26596. return new PropertyBinding.Composite( root, path, parsedPath );
  26597. }
  26598. }
  26599. /**
  26600. * Replaces spaces with underscores and removes unsupported characters from
  26601. * node names, to ensure compatibility with parseTrackName().
  26602. *
  26603. * @param {string} name Node name to be sanitized.
  26604. * @return {string}
  26605. */
  26606. static sanitizeNodeName( name ) {
  26607. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  26608. }
  26609. static parseTrackName( trackName ) {
  26610. const matches = _trackRe.exec( trackName );
  26611. if ( matches === null ) {
  26612. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  26613. }
  26614. const results = {
  26615. // directoryName: matches[ 1 ], // (tschw) currently unused
  26616. nodeName: matches[ 2 ],
  26617. objectName: matches[ 3 ],
  26618. objectIndex: matches[ 4 ],
  26619. propertyName: matches[ 5 ], // required
  26620. propertyIndex: matches[ 6 ]
  26621. };
  26622. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  26623. if ( lastDot !== undefined && lastDot !== - 1 ) {
  26624. const objectName = results.nodeName.substring( lastDot + 1 );
  26625. // Object names must be checked against an allowlist. Otherwise, there
  26626. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26627. // 'bar' could be the objectName, or part of a nodeName (which can
  26628. // include '.' characters).
  26629. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  26630. results.nodeName = results.nodeName.substring( 0, lastDot );
  26631. results.objectName = objectName;
  26632. }
  26633. }
  26634. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  26635. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  26636. }
  26637. return results;
  26638. }
  26639. static findNode( root, nodeName ) {
  26640. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  26641. return root;
  26642. }
  26643. // search into skeleton bones.
  26644. if ( root.skeleton ) {
  26645. const bone = root.skeleton.getBoneByName( nodeName );
  26646. if ( bone !== undefined ) {
  26647. return bone;
  26648. }
  26649. }
  26650. // search into node subtree.
  26651. if ( root.children ) {
  26652. const searchNodeSubtree = function ( children ) {
  26653. for ( let i = 0; i < children.length; i ++ ) {
  26654. const childNode = children[ i ];
  26655. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  26656. return childNode;
  26657. }
  26658. const result = searchNodeSubtree( childNode.children );
  26659. if ( result ) return result;
  26660. }
  26661. return null;
  26662. };
  26663. const subTreeNode = searchNodeSubtree( root.children );
  26664. if ( subTreeNode ) {
  26665. return subTreeNode;
  26666. }
  26667. }
  26668. return null;
  26669. }
  26670. // these are used to "bind" a nonexistent property
  26671. _getValue_unavailable() {}
  26672. _setValue_unavailable() {}
  26673. // Getters
  26674. _getValue_direct( buffer, offset ) {
  26675. buffer[ offset ] = this.targetObject[ this.propertyName ];
  26676. }
  26677. _getValue_array( buffer, offset ) {
  26678. const source = this.resolvedProperty;
  26679. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  26680. buffer[ offset ++ ] = source[ i ];
  26681. }
  26682. }
  26683. _getValue_arrayElement( buffer, offset ) {
  26684. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  26685. }
  26686. _getValue_toArray( buffer, offset ) {
  26687. this.resolvedProperty.toArray( buffer, offset );
  26688. }
  26689. // Direct
  26690. _setValue_direct( buffer, offset ) {
  26691. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26692. }
  26693. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  26694. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26695. this.targetObject.needsUpdate = true;
  26696. }
  26697. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26698. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26699. this.targetObject.matrixWorldNeedsUpdate = true;
  26700. }
  26701. // EntireArray
  26702. _setValue_array( buffer, offset ) {
  26703. const dest = this.resolvedProperty;
  26704. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26705. dest[ i ] = buffer[ offset ++ ];
  26706. }
  26707. }
  26708. _setValue_array_setNeedsUpdate( buffer, offset ) {
  26709. const dest = this.resolvedProperty;
  26710. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26711. dest[ i ] = buffer[ offset ++ ];
  26712. }
  26713. this.targetObject.needsUpdate = true;
  26714. }
  26715. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26716. const dest = this.resolvedProperty;
  26717. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26718. dest[ i ] = buffer[ offset ++ ];
  26719. }
  26720. this.targetObject.matrixWorldNeedsUpdate = true;
  26721. }
  26722. // ArrayElement
  26723. _setValue_arrayElement( buffer, offset ) {
  26724. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26725. }
  26726. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  26727. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26728. this.targetObject.needsUpdate = true;
  26729. }
  26730. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26731. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26732. this.targetObject.matrixWorldNeedsUpdate = true;
  26733. }
  26734. // HasToFromArray
  26735. _setValue_fromArray( buffer, offset ) {
  26736. this.resolvedProperty.fromArray( buffer, offset );
  26737. }
  26738. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  26739. this.resolvedProperty.fromArray( buffer, offset );
  26740. this.targetObject.needsUpdate = true;
  26741. }
  26742. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26743. this.resolvedProperty.fromArray( buffer, offset );
  26744. this.targetObject.matrixWorldNeedsUpdate = true;
  26745. }
  26746. _getValue_unbound( targetArray, offset ) {
  26747. this.bind();
  26748. this.getValue( targetArray, offset );
  26749. }
  26750. _setValue_unbound( sourceArray, offset ) {
  26751. this.bind();
  26752. this.setValue( sourceArray, offset );
  26753. }
  26754. // create getter / setter pair for a property in the scene graph
  26755. bind() {
  26756. let targetObject = this.node;
  26757. const parsedPath = this.parsedPath;
  26758. const objectName = parsedPath.objectName;
  26759. const propertyName = parsedPath.propertyName;
  26760. let propertyIndex = parsedPath.propertyIndex;
  26761. if ( ! targetObject ) {
  26762. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  26763. this.node = targetObject;
  26764. }
  26765. // set fail state so we can just 'return' on error
  26766. this.getValue = this._getValue_unavailable;
  26767. this.setValue = this._setValue_unavailable;
  26768. // ensure there is a value node
  26769. if ( ! targetObject ) {
  26770. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  26771. return;
  26772. }
  26773. if ( objectName ) {
  26774. let objectIndex = parsedPath.objectIndex;
  26775. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  26776. switch ( objectName ) {
  26777. case 'materials':
  26778. if ( ! targetObject.material ) {
  26779. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  26780. return;
  26781. }
  26782. if ( ! targetObject.material.materials ) {
  26783. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  26784. return;
  26785. }
  26786. targetObject = targetObject.material.materials;
  26787. break;
  26788. case 'bones':
  26789. if ( ! targetObject.skeleton ) {
  26790. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  26791. return;
  26792. }
  26793. // potential future optimization: skip this if propertyIndex is already an integer
  26794. // and convert the integer string to a true integer.
  26795. targetObject = targetObject.skeleton.bones;
  26796. // support resolving morphTarget names into indices.
  26797. for ( let i = 0; i < targetObject.length; i ++ ) {
  26798. if ( targetObject[ i ].name === objectIndex ) {
  26799. objectIndex = i;
  26800. break;
  26801. }
  26802. }
  26803. break;
  26804. case 'map':
  26805. if ( 'map' in targetObject ) {
  26806. targetObject = targetObject.map;
  26807. break;
  26808. }
  26809. if ( ! targetObject.material ) {
  26810. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  26811. return;
  26812. }
  26813. if ( ! targetObject.material.map ) {
  26814. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  26815. return;
  26816. }
  26817. targetObject = targetObject.material.map;
  26818. break;
  26819. default:
  26820. if ( targetObject[ objectName ] === undefined ) {
  26821. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  26822. return;
  26823. }
  26824. targetObject = targetObject[ objectName ];
  26825. }
  26826. if ( objectIndex !== undefined ) {
  26827. if ( targetObject[ objectIndex ] === undefined ) {
  26828. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  26829. return;
  26830. }
  26831. targetObject = targetObject[ objectIndex ];
  26832. }
  26833. }
  26834. // resolve property
  26835. const nodeProperty = targetObject[ propertyName ];
  26836. if ( nodeProperty === undefined ) {
  26837. const nodeName = parsedPath.nodeName;
  26838. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  26839. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  26840. return;
  26841. }
  26842. // determine versioning scheme
  26843. let versioning = this.Versioning.None;
  26844. this.targetObject = targetObject;
  26845. if ( targetObject.needsUpdate !== undefined ) { // material
  26846. versioning = this.Versioning.NeedsUpdate;
  26847. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  26848. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26849. }
  26850. // determine how the property gets bound
  26851. let bindingType = this.BindingType.Direct;
  26852. if ( propertyIndex !== undefined ) {
  26853. // access a sub element of the property array (only primitives are supported right now)
  26854. if ( propertyName === 'morphTargetInfluences' ) {
  26855. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26856. // support resolving morphTarget names into indices.
  26857. if ( ! targetObject.geometry ) {
  26858. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  26859. return;
  26860. }
  26861. if ( ! targetObject.geometry.morphAttributes ) {
  26862. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  26863. return;
  26864. }
  26865. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  26866. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  26867. }
  26868. }
  26869. bindingType = this.BindingType.ArrayElement;
  26870. this.resolvedProperty = nodeProperty;
  26871. this.propertyIndex = propertyIndex;
  26872. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  26873. // must use copy for Object3D.Euler/Quaternion
  26874. bindingType = this.BindingType.HasFromToArray;
  26875. this.resolvedProperty = nodeProperty;
  26876. } else if ( Array.isArray( nodeProperty ) ) {
  26877. bindingType = this.BindingType.EntireArray;
  26878. this.resolvedProperty = nodeProperty;
  26879. } else {
  26880. this.propertyName = propertyName;
  26881. }
  26882. // select getter / setter
  26883. this.getValue = this.GetterByBindingType[ bindingType ];
  26884. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  26885. }
  26886. unbind() {
  26887. this.node = null;
  26888. // back to the prototype version of getValue / setValue
  26889. // note: avoiding to mutate the shape of 'this' via 'delete'
  26890. this.getValue = this._getValue_unbound;
  26891. this.setValue = this._setValue_unbound;
  26892. }
  26893. }
  26894. PropertyBinding.Composite = Composite;
  26895. PropertyBinding.prototype.BindingType = {
  26896. Direct: 0,
  26897. EntireArray: 1,
  26898. ArrayElement: 2,
  26899. HasFromToArray: 3
  26900. };
  26901. PropertyBinding.prototype.Versioning = {
  26902. None: 0,
  26903. NeedsUpdate: 1,
  26904. MatrixWorldNeedsUpdate: 2
  26905. };
  26906. PropertyBinding.prototype.GetterByBindingType = [
  26907. PropertyBinding.prototype._getValue_direct,
  26908. PropertyBinding.prototype._getValue_array,
  26909. PropertyBinding.prototype._getValue_arrayElement,
  26910. PropertyBinding.prototype._getValue_toArray,
  26911. ];
  26912. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  26913. [
  26914. // Direct
  26915. PropertyBinding.prototype._setValue_direct,
  26916. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  26917. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  26918. ], [
  26919. // EntireArray
  26920. PropertyBinding.prototype._setValue_array,
  26921. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  26922. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  26923. ], [
  26924. // ArrayElement
  26925. PropertyBinding.prototype._setValue_arrayElement,
  26926. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  26927. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  26928. ], [
  26929. // HasToFromArray
  26930. PropertyBinding.prototype._setValue_fromArray,
  26931. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  26932. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  26933. ]
  26934. ];
  26935. /**
  26936. *
  26937. * A group of objects that receives a shared animation state.
  26938. *
  26939. * Usage:
  26940. *
  26941. * - Add objects you would otherwise pass as 'root' to the
  26942. * constructor or the .clipAction method of AnimationMixer.
  26943. *
  26944. * - Instead pass this object as 'root'.
  26945. *
  26946. * - You can also add and remove objects later when the mixer
  26947. * is running.
  26948. *
  26949. * Note:
  26950. *
  26951. * Objects of this class appear as one object to the mixer,
  26952. * so cache control of the individual objects must be done
  26953. * on the group.
  26954. *
  26955. * Limitation:
  26956. *
  26957. * - The animated properties must be compatible among the
  26958. * all objects in the group.
  26959. *
  26960. * - A single property can either be controlled through a
  26961. * target group or directly, but not both.
  26962. */
  26963. class AnimationObjectGroup {
  26964. constructor() {
  26965. this.isAnimationObjectGroup = true;
  26966. this.uuid = generateUUID();
  26967. // cached objects followed by the active ones
  26968. this._objects = Array.prototype.slice.call( arguments );
  26969. this.nCachedObjects_ = 0; // threshold
  26970. // note: read by PropertyBinding.Composite
  26971. const indices = {};
  26972. this._indicesByUUID = indices; // for bookkeeping
  26973. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26974. indices[ arguments[ i ].uuid ] = i;
  26975. }
  26976. this._paths = []; // inside: string
  26977. this._parsedPaths = []; // inside: { we don't care, here }
  26978. this._bindings = []; // inside: Array< PropertyBinding >
  26979. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26980. const scope = this;
  26981. this.stats = {
  26982. objects: {
  26983. get total() {
  26984. return scope._objects.length;
  26985. },
  26986. get inUse() {
  26987. return this.total - scope.nCachedObjects_;
  26988. }
  26989. },
  26990. get bindingsPerObject() {
  26991. return scope._bindings.length;
  26992. }
  26993. };
  26994. }
  26995. add() {
  26996. const objects = this._objects,
  26997. indicesByUUID = this._indicesByUUID,
  26998. paths = this._paths,
  26999. parsedPaths = this._parsedPaths,
  27000. bindings = this._bindings,
  27001. nBindings = bindings.length;
  27002. let knownObject = undefined,
  27003. nObjects = objects.length,
  27004. nCachedObjects = this.nCachedObjects_;
  27005. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27006. const object = arguments[ i ],
  27007. uuid = object.uuid;
  27008. let index = indicesByUUID[ uuid ];
  27009. if ( index === undefined ) {
  27010. // unknown object -> add it to the ACTIVE region
  27011. index = nObjects ++;
  27012. indicesByUUID[ uuid ] = index;
  27013. objects.push( object );
  27014. // accounting is done, now do the same for all bindings
  27015. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27016. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  27017. }
  27018. } else if ( index < nCachedObjects ) {
  27019. knownObject = objects[ index ];
  27020. // move existing object to the ACTIVE region
  27021. const firstActiveIndex = -- nCachedObjects,
  27022. lastCachedObject = objects[ firstActiveIndex ];
  27023. indicesByUUID[ lastCachedObject.uuid ] = index;
  27024. objects[ index ] = lastCachedObject;
  27025. indicesByUUID[ uuid ] = firstActiveIndex;
  27026. objects[ firstActiveIndex ] = object;
  27027. // accounting is done, now do the same for all bindings
  27028. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27029. const bindingsForPath = bindings[ j ],
  27030. lastCached = bindingsForPath[ firstActiveIndex ];
  27031. let binding = bindingsForPath[ index ];
  27032. bindingsForPath[ index ] = lastCached;
  27033. if ( binding === undefined ) {
  27034. // since we do not bother to create new bindings
  27035. // for objects that are cached, the binding may
  27036. // or may not exist
  27037. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  27038. }
  27039. bindingsForPath[ firstActiveIndex ] = binding;
  27040. }
  27041. } else if ( objects[ index ] !== knownObject ) {
  27042. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  27043. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  27044. } // else the object is already where we want it to be
  27045. } // for arguments
  27046. this.nCachedObjects_ = nCachedObjects;
  27047. }
  27048. remove() {
  27049. const objects = this._objects,
  27050. indicesByUUID = this._indicesByUUID,
  27051. bindings = this._bindings,
  27052. nBindings = bindings.length;
  27053. let nCachedObjects = this.nCachedObjects_;
  27054. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27055. const object = arguments[ i ],
  27056. uuid = object.uuid,
  27057. index = indicesByUUID[ uuid ];
  27058. if ( index !== undefined && index >= nCachedObjects ) {
  27059. // move existing object into the CACHED region
  27060. const lastCachedIndex = nCachedObjects ++,
  27061. firstActiveObject = objects[ lastCachedIndex ];
  27062. indicesByUUID[ firstActiveObject.uuid ] = index;
  27063. objects[ index ] = firstActiveObject;
  27064. indicesByUUID[ uuid ] = lastCachedIndex;
  27065. objects[ lastCachedIndex ] = object;
  27066. // accounting is done, now do the same for all bindings
  27067. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27068. const bindingsForPath = bindings[ j ],
  27069. firstActive = bindingsForPath[ lastCachedIndex ],
  27070. binding = bindingsForPath[ index ];
  27071. bindingsForPath[ index ] = firstActive;
  27072. bindingsForPath[ lastCachedIndex ] = binding;
  27073. }
  27074. }
  27075. } // for arguments
  27076. this.nCachedObjects_ = nCachedObjects;
  27077. }
  27078. // remove & forget
  27079. uncache() {
  27080. const objects = this._objects,
  27081. indicesByUUID = this._indicesByUUID,
  27082. bindings = this._bindings,
  27083. nBindings = bindings.length;
  27084. let nCachedObjects = this.nCachedObjects_,
  27085. nObjects = objects.length;
  27086. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27087. const object = arguments[ i ],
  27088. uuid = object.uuid,
  27089. index = indicesByUUID[ uuid ];
  27090. if ( index !== undefined ) {
  27091. delete indicesByUUID[ uuid ];
  27092. if ( index < nCachedObjects ) {
  27093. // object is cached, shrink the CACHED region
  27094. const firstActiveIndex = -- nCachedObjects,
  27095. lastCachedObject = objects[ firstActiveIndex ],
  27096. lastIndex = -- nObjects,
  27097. lastObject = objects[ lastIndex ];
  27098. // last cached object takes this object's place
  27099. indicesByUUID[ lastCachedObject.uuid ] = index;
  27100. objects[ index ] = lastCachedObject;
  27101. // last object goes to the activated slot and pop
  27102. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  27103. objects[ firstActiveIndex ] = lastObject;
  27104. objects.pop();
  27105. // accounting is done, now do the same for all bindings
  27106. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27107. const bindingsForPath = bindings[ j ],
  27108. lastCached = bindingsForPath[ firstActiveIndex ],
  27109. last = bindingsForPath[ lastIndex ];
  27110. bindingsForPath[ index ] = lastCached;
  27111. bindingsForPath[ firstActiveIndex ] = last;
  27112. bindingsForPath.pop();
  27113. }
  27114. } else {
  27115. // object is active, just swap with the last and pop
  27116. const lastIndex = -- nObjects,
  27117. lastObject = objects[ lastIndex ];
  27118. if ( lastIndex > 0 ) {
  27119. indicesByUUID[ lastObject.uuid ] = index;
  27120. }
  27121. objects[ index ] = lastObject;
  27122. objects.pop();
  27123. // accounting is done, now do the same for all bindings
  27124. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27125. const bindingsForPath = bindings[ j ];
  27126. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  27127. bindingsForPath.pop();
  27128. }
  27129. } // cached or active
  27130. } // if object is known
  27131. } // for arguments
  27132. this.nCachedObjects_ = nCachedObjects;
  27133. }
  27134. // Internal interface used by befriended PropertyBinding.Composite:
  27135. subscribe_( path, parsedPath ) {
  27136. // returns an array of bindings for the given path that is changed
  27137. // according to the contained objects in the group
  27138. const indicesByPath = this._bindingsIndicesByPath;
  27139. let index = indicesByPath[ path ];
  27140. const bindings = this._bindings;
  27141. if ( index !== undefined ) return bindings[ index ];
  27142. const paths = this._paths,
  27143. parsedPaths = this._parsedPaths,
  27144. objects = this._objects,
  27145. nObjects = objects.length,
  27146. nCachedObjects = this.nCachedObjects_,
  27147. bindingsForPath = new Array( nObjects );
  27148. index = bindings.length;
  27149. indicesByPath[ path ] = index;
  27150. paths.push( path );
  27151. parsedPaths.push( parsedPath );
  27152. bindings.push( bindingsForPath );
  27153. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  27154. const object = objects[ i ];
  27155. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  27156. }
  27157. return bindingsForPath;
  27158. }
  27159. unsubscribe_( path ) {
  27160. // tells the group to forget about a property path and no longer
  27161. // update the array previously obtained with 'subscribe_'
  27162. const indicesByPath = this._bindingsIndicesByPath,
  27163. index = indicesByPath[ path ];
  27164. if ( index !== undefined ) {
  27165. const paths = this._paths,
  27166. parsedPaths = this._parsedPaths,
  27167. bindings = this._bindings,
  27168. lastBindingsIndex = bindings.length - 1,
  27169. lastBindings = bindings[ lastBindingsIndex ],
  27170. lastBindingsPath = path[ lastBindingsIndex ];
  27171. indicesByPath[ lastBindingsPath ] = index;
  27172. bindings[ index ] = lastBindings;
  27173. bindings.pop();
  27174. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  27175. parsedPaths.pop();
  27176. paths[ index ] = paths[ lastBindingsIndex ];
  27177. paths.pop();
  27178. }
  27179. }
  27180. }
  27181. class AnimationAction {
  27182. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  27183. this._mixer = mixer;
  27184. this._clip = clip;
  27185. this._localRoot = localRoot;
  27186. this.blendMode = blendMode;
  27187. const tracks = clip.tracks,
  27188. nTracks = tracks.length,
  27189. interpolants = new Array( nTracks );
  27190. const interpolantSettings = {
  27191. endingStart: ZeroCurvatureEnding,
  27192. endingEnd: ZeroCurvatureEnding
  27193. };
  27194. for ( let i = 0; i !== nTracks; ++ i ) {
  27195. const interpolant = tracks[ i ].createInterpolant( null );
  27196. interpolants[ i ] = interpolant;
  27197. interpolant.settings = interpolantSettings;
  27198. }
  27199. this._interpolantSettings = interpolantSettings;
  27200. this._interpolants = interpolants; // bound by the mixer
  27201. // inside: PropertyMixer (managed by the mixer)
  27202. this._propertyBindings = new Array( nTracks );
  27203. this._cacheIndex = null; // for the memory manager
  27204. this._byClipCacheIndex = null; // for the memory manager
  27205. this._timeScaleInterpolant = null;
  27206. this._weightInterpolant = null;
  27207. this.loop = LoopRepeat;
  27208. this._loopCount = - 1;
  27209. // global mixer time when the action is to be started
  27210. // it's set back to 'null' upon start of the action
  27211. this._startTime = null;
  27212. // scaled local time of the action
  27213. // gets clamped or wrapped to 0..clip.duration according to loop
  27214. this.time = 0;
  27215. this.timeScale = 1;
  27216. this._effectiveTimeScale = 1;
  27217. this.weight = 1;
  27218. this._effectiveWeight = 1;
  27219. this.repetitions = Infinity; // no. of repetitions when looping
  27220. this.paused = false; // true -> zero effective time scale
  27221. this.enabled = true; // false -> zero effective weight
  27222. this.clampWhenFinished = false;// keep feeding the last frame?
  27223. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  27224. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  27225. }
  27226. // State & Scheduling
  27227. play() {
  27228. this._mixer._activateAction( this );
  27229. return this;
  27230. }
  27231. stop() {
  27232. this._mixer._deactivateAction( this );
  27233. return this.reset();
  27234. }
  27235. reset() {
  27236. this.paused = false;
  27237. this.enabled = true;
  27238. this.time = 0; // restart clip
  27239. this._loopCount = - 1;// forget previous loops
  27240. this._startTime = null;// forget scheduling
  27241. return this.stopFading().stopWarping();
  27242. }
  27243. isRunning() {
  27244. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  27245. this._startTime === null && this._mixer._isActiveAction( this );
  27246. }
  27247. // return true when play has been called
  27248. isScheduled() {
  27249. return this._mixer._isActiveAction( this );
  27250. }
  27251. startAt( time ) {
  27252. this._startTime = time;
  27253. return this;
  27254. }
  27255. setLoop( mode, repetitions ) {
  27256. this.loop = mode;
  27257. this.repetitions = repetitions;
  27258. return this;
  27259. }
  27260. // Weight
  27261. // set the weight stopping any scheduled fading
  27262. // although .enabled = false yields an effective weight of zero, this
  27263. // method does *not* change .enabled, because it would be confusing
  27264. setEffectiveWeight( weight ) {
  27265. this.weight = weight;
  27266. // note: same logic as when updated at runtime
  27267. this._effectiveWeight = this.enabled ? weight : 0;
  27268. return this.stopFading();
  27269. }
  27270. // return the weight considering fading and .enabled
  27271. getEffectiveWeight() {
  27272. return this._effectiveWeight;
  27273. }
  27274. fadeIn( duration ) {
  27275. return this._scheduleFading( duration, 0, 1 );
  27276. }
  27277. fadeOut( duration ) {
  27278. return this._scheduleFading( duration, 1, 0 );
  27279. }
  27280. crossFadeFrom( fadeOutAction, duration, warp ) {
  27281. fadeOutAction.fadeOut( duration );
  27282. this.fadeIn( duration );
  27283. if ( warp ) {
  27284. const fadeInDuration = this._clip.duration,
  27285. fadeOutDuration = fadeOutAction._clip.duration,
  27286. startEndRatio = fadeOutDuration / fadeInDuration,
  27287. endStartRatio = fadeInDuration / fadeOutDuration;
  27288. fadeOutAction.warp( 1.0, startEndRatio, duration );
  27289. this.warp( endStartRatio, 1.0, duration );
  27290. }
  27291. return this;
  27292. }
  27293. crossFadeTo( fadeInAction, duration, warp ) {
  27294. return fadeInAction.crossFadeFrom( this, duration, warp );
  27295. }
  27296. stopFading() {
  27297. const weightInterpolant = this._weightInterpolant;
  27298. if ( weightInterpolant !== null ) {
  27299. this._weightInterpolant = null;
  27300. this._mixer._takeBackControlInterpolant( weightInterpolant );
  27301. }
  27302. return this;
  27303. }
  27304. // Time Scale Control
  27305. // set the time scale stopping any scheduled warping
  27306. // although .paused = true yields an effective time scale of zero, this
  27307. // method does *not* change .paused, because it would be confusing
  27308. setEffectiveTimeScale( timeScale ) {
  27309. this.timeScale = timeScale;
  27310. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  27311. return this.stopWarping();
  27312. }
  27313. // return the time scale considering warping and .paused
  27314. getEffectiveTimeScale() {
  27315. return this._effectiveTimeScale;
  27316. }
  27317. setDuration( duration ) {
  27318. this.timeScale = this._clip.duration / duration;
  27319. return this.stopWarping();
  27320. }
  27321. syncWith( action ) {
  27322. this.time = action.time;
  27323. this.timeScale = action.timeScale;
  27324. return this.stopWarping();
  27325. }
  27326. halt( duration ) {
  27327. return this.warp( this._effectiveTimeScale, 0, duration );
  27328. }
  27329. warp( startTimeScale, endTimeScale, duration ) {
  27330. const mixer = this._mixer,
  27331. now = mixer.time,
  27332. timeScale = this.timeScale;
  27333. let interpolant = this._timeScaleInterpolant;
  27334. if ( interpolant === null ) {
  27335. interpolant = mixer._lendControlInterpolant();
  27336. this._timeScaleInterpolant = interpolant;
  27337. }
  27338. const times = interpolant.parameterPositions,
  27339. values = interpolant.sampleValues;
  27340. times[ 0 ] = now;
  27341. times[ 1 ] = now + duration;
  27342. values[ 0 ] = startTimeScale / timeScale;
  27343. values[ 1 ] = endTimeScale / timeScale;
  27344. return this;
  27345. }
  27346. stopWarping() {
  27347. const timeScaleInterpolant = this._timeScaleInterpolant;
  27348. if ( timeScaleInterpolant !== null ) {
  27349. this._timeScaleInterpolant = null;
  27350. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  27351. }
  27352. return this;
  27353. }
  27354. // Object Accessors
  27355. getMixer() {
  27356. return this._mixer;
  27357. }
  27358. getClip() {
  27359. return this._clip;
  27360. }
  27361. getRoot() {
  27362. return this._localRoot || this._mixer._root;
  27363. }
  27364. // Interna
  27365. _update( time, deltaTime, timeDirection, accuIndex ) {
  27366. // called by the mixer
  27367. if ( ! this.enabled ) {
  27368. // call ._updateWeight() to update ._effectiveWeight
  27369. this._updateWeight( time );
  27370. return;
  27371. }
  27372. const startTime = this._startTime;
  27373. if ( startTime !== null ) {
  27374. // check for scheduled start of action
  27375. const timeRunning = ( time - startTime ) * timeDirection;
  27376. if ( timeRunning < 0 || timeDirection === 0 ) {
  27377. deltaTime = 0;
  27378. } else {
  27379. this._startTime = null; // unschedule
  27380. deltaTime = timeDirection * timeRunning;
  27381. }
  27382. }
  27383. // apply time scale and advance time
  27384. deltaTime *= this._updateTimeScale( time );
  27385. const clipTime = this._updateTime( deltaTime );
  27386. // note: _updateTime may disable the action resulting in
  27387. // an effective weight of 0
  27388. const weight = this._updateWeight( time );
  27389. if ( weight > 0 ) {
  27390. const interpolants = this._interpolants;
  27391. const propertyMixers = this._propertyBindings;
  27392. switch ( this.blendMode ) {
  27393. case AdditiveAnimationBlendMode:
  27394. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27395. interpolants[ j ].evaluate( clipTime );
  27396. propertyMixers[ j ].accumulateAdditive( weight );
  27397. }
  27398. break;
  27399. case NormalAnimationBlendMode:
  27400. default:
  27401. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27402. interpolants[ j ].evaluate( clipTime );
  27403. propertyMixers[ j ].accumulate( accuIndex, weight );
  27404. }
  27405. }
  27406. }
  27407. }
  27408. _updateWeight( time ) {
  27409. let weight = 0;
  27410. if ( this.enabled ) {
  27411. weight = this.weight;
  27412. const interpolant = this._weightInterpolant;
  27413. if ( interpolant !== null ) {
  27414. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27415. weight *= interpolantValue;
  27416. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27417. this.stopFading();
  27418. if ( interpolantValue === 0 ) {
  27419. // faded out, disable
  27420. this.enabled = false;
  27421. }
  27422. }
  27423. }
  27424. }
  27425. this._effectiveWeight = weight;
  27426. return weight;
  27427. }
  27428. _updateTimeScale( time ) {
  27429. let timeScale = 0;
  27430. if ( ! this.paused ) {
  27431. timeScale = this.timeScale;
  27432. const interpolant = this._timeScaleInterpolant;
  27433. if ( interpolant !== null ) {
  27434. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27435. timeScale *= interpolantValue;
  27436. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27437. this.stopWarping();
  27438. if ( timeScale === 0 ) {
  27439. // motion has halted, pause
  27440. this.paused = true;
  27441. } else {
  27442. // warp done - apply final time scale
  27443. this.timeScale = timeScale;
  27444. }
  27445. }
  27446. }
  27447. }
  27448. this._effectiveTimeScale = timeScale;
  27449. return timeScale;
  27450. }
  27451. _updateTime( deltaTime ) {
  27452. const duration = this._clip.duration;
  27453. const loop = this.loop;
  27454. let time = this.time + deltaTime;
  27455. let loopCount = this._loopCount;
  27456. const pingPong = ( loop === LoopPingPong );
  27457. if ( deltaTime === 0 ) {
  27458. if ( loopCount === - 1 ) return time;
  27459. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  27460. }
  27461. if ( loop === LoopOnce ) {
  27462. if ( loopCount === - 1 ) {
  27463. // just started
  27464. this._loopCount = 0;
  27465. this._setEndings( true, true, false );
  27466. }
  27467. handle_stop: {
  27468. if ( time >= duration ) {
  27469. time = duration;
  27470. } else if ( time < 0 ) {
  27471. time = 0;
  27472. } else {
  27473. this.time = time;
  27474. break handle_stop;
  27475. }
  27476. if ( this.clampWhenFinished ) this.paused = true;
  27477. else this.enabled = false;
  27478. this.time = time;
  27479. this._mixer.dispatchEvent( {
  27480. type: 'finished', action: this,
  27481. direction: deltaTime < 0 ? - 1 : 1
  27482. } );
  27483. }
  27484. } else { // repetitive Repeat or PingPong
  27485. if ( loopCount === - 1 ) {
  27486. // just started
  27487. if ( deltaTime >= 0 ) {
  27488. loopCount = 0;
  27489. this._setEndings( true, this.repetitions === 0, pingPong );
  27490. } else {
  27491. // when looping in reverse direction, the initial
  27492. // transition through zero counts as a repetition,
  27493. // so leave loopCount at -1
  27494. this._setEndings( this.repetitions === 0, true, pingPong );
  27495. }
  27496. }
  27497. if ( time >= duration || time < 0 ) {
  27498. // wrap around
  27499. const loopDelta = Math.floor( time / duration ); // signed
  27500. time -= duration * loopDelta;
  27501. loopCount += Math.abs( loopDelta );
  27502. const pending = this.repetitions - loopCount;
  27503. if ( pending <= 0 ) {
  27504. // have to stop (switch state, clamp time, fire event)
  27505. if ( this.clampWhenFinished ) this.paused = true;
  27506. else this.enabled = false;
  27507. time = deltaTime > 0 ? duration : 0;
  27508. this.time = time;
  27509. this._mixer.dispatchEvent( {
  27510. type: 'finished', action: this,
  27511. direction: deltaTime > 0 ? 1 : - 1
  27512. } );
  27513. } else {
  27514. // keep running
  27515. if ( pending === 1 ) {
  27516. // entering the last round
  27517. const atStart = deltaTime < 0;
  27518. this._setEndings( atStart, ! atStart, pingPong );
  27519. } else {
  27520. this._setEndings( false, false, pingPong );
  27521. }
  27522. this._loopCount = loopCount;
  27523. this.time = time;
  27524. this._mixer.dispatchEvent( {
  27525. type: 'loop', action: this, loopDelta: loopDelta
  27526. } );
  27527. }
  27528. } else {
  27529. this.time = time;
  27530. }
  27531. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  27532. // invert time for the "pong round"
  27533. return duration - time;
  27534. }
  27535. }
  27536. return time;
  27537. }
  27538. _setEndings( atStart, atEnd, pingPong ) {
  27539. const settings = this._interpolantSettings;
  27540. if ( pingPong ) {
  27541. settings.endingStart = ZeroSlopeEnding;
  27542. settings.endingEnd = ZeroSlopeEnding;
  27543. } else {
  27544. // assuming for LoopOnce atStart == atEnd == true
  27545. if ( atStart ) {
  27546. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27547. } else {
  27548. settings.endingStart = WrapAroundEnding;
  27549. }
  27550. if ( atEnd ) {
  27551. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27552. } else {
  27553. settings.endingEnd = WrapAroundEnding;
  27554. }
  27555. }
  27556. }
  27557. _scheduleFading( duration, weightNow, weightThen ) {
  27558. const mixer = this._mixer, now = mixer.time;
  27559. let interpolant = this._weightInterpolant;
  27560. if ( interpolant === null ) {
  27561. interpolant = mixer._lendControlInterpolant();
  27562. this._weightInterpolant = interpolant;
  27563. }
  27564. const times = interpolant.parameterPositions,
  27565. values = interpolant.sampleValues;
  27566. times[ 0 ] = now;
  27567. values[ 0 ] = weightNow;
  27568. times[ 1 ] = now + duration;
  27569. values[ 1 ] = weightThen;
  27570. return this;
  27571. }
  27572. }
  27573. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  27574. class AnimationMixer extends EventDispatcher {
  27575. constructor( root ) {
  27576. super();
  27577. this._root = root;
  27578. this._initMemoryManager();
  27579. this._accuIndex = 0;
  27580. this.time = 0;
  27581. this.timeScale = 1.0;
  27582. }
  27583. _bindAction( action, prototypeAction ) {
  27584. const root = action._localRoot || this._root,
  27585. tracks = action._clip.tracks,
  27586. nTracks = tracks.length,
  27587. bindings = action._propertyBindings,
  27588. interpolants = action._interpolants,
  27589. rootUuid = root.uuid,
  27590. bindingsByRoot = this._bindingsByRootAndName;
  27591. let bindingsByName = bindingsByRoot[ rootUuid ];
  27592. if ( bindingsByName === undefined ) {
  27593. bindingsByName = {};
  27594. bindingsByRoot[ rootUuid ] = bindingsByName;
  27595. }
  27596. for ( let i = 0; i !== nTracks; ++ i ) {
  27597. const track = tracks[ i ],
  27598. trackName = track.name;
  27599. let binding = bindingsByName[ trackName ];
  27600. if ( binding !== undefined ) {
  27601. ++ binding.referenceCount;
  27602. bindings[ i ] = binding;
  27603. } else {
  27604. binding = bindings[ i ];
  27605. if ( binding !== undefined ) {
  27606. // existing binding, make sure the cache knows
  27607. if ( binding._cacheIndex === null ) {
  27608. ++ binding.referenceCount;
  27609. this._addInactiveBinding( binding, rootUuid, trackName );
  27610. }
  27611. continue;
  27612. }
  27613. const path = prototypeAction && prototypeAction.
  27614. _propertyBindings[ i ].binding.parsedPath;
  27615. binding = new PropertyMixer(
  27616. PropertyBinding.create( root, trackName, path ),
  27617. track.ValueTypeName, track.getValueSize() );
  27618. ++ binding.referenceCount;
  27619. this._addInactiveBinding( binding, rootUuid, trackName );
  27620. bindings[ i ] = binding;
  27621. }
  27622. interpolants[ i ].resultBuffer = binding.buffer;
  27623. }
  27624. }
  27625. _activateAction( action ) {
  27626. if ( ! this._isActiveAction( action ) ) {
  27627. if ( action._cacheIndex === null ) {
  27628. // this action has been forgotten by the cache, but the user
  27629. // appears to be still using it -> rebind
  27630. const rootUuid = ( action._localRoot || this._root ).uuid,
  27631. clipUuid = action._clip.uuid,
  27632. actionsForClip = this._actionsByClip[ clipUuid ];
  27633. this._bindAction( action,
  27634. actionsForClip && actionsForClip.knownActions[ 0 ] );
  27635. this._addInactiveAction( action, clipUuid, rootUuid );
  27636. }
  27637. const bindings = action._propertyBindings;
  27638. // increment reference counts / sort out state
  27639. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27640. const binding = bindings[ i ];
  27641. if ( binding.useCount ++ === 0 ) {
  27642. this._lendBinding( binding );
  27643. binding.saveOriginalState();
  27644. }
  27645. }
  27646. this._lendAction( action );
  27647. }
  27648. }
  27649. _deactivateAction( action ) {
  27650. if ( this._isActiveAction( action ) ) {
  27651. const bindings = action._propertyBindings;
  27652. // decrement reference counts / sort out state
  27653. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27654. const binding = bindings[ i ];
  27655. if ( -- binding.useCount === 0 ) {
  27656. binding.restoreOriginalState();
  27657. this._takeBackBinding( binding );
  27658. }
  27659. }
  27660. this._takeBackAction( action );
  27661. }
  27662. }
  27663. // Memory manager
  27664. _initMemoryManager() {
  27665. this._actions = []; // 'nActiveActions' followed by inactive ones
  27666. this._nActiveActions = 0;
  27667. this._actionsByClip = {};
  27668. // inside:
  27669. // {
  27670. // knownActions: Array< AnimationAction > - used as prototypes
  27671. // actionByRoot: AnimationAction - lookup
  27672. // }
  27673. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27674. this._nActiveBindings = 0;
  27675. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27676. this._controlInterpolants = []; // same game as above
  27677. this._nActiveControlInterpolants = 0;
  27678. const scope = this;
  27679. this.stats = {
  27680. actions: {
  27681. get total() {
  27682. return scope._actions.length;
  27683. },
  27684. get inUse() {
  27685. return scope._nActiveActions;
  27686. }
  27687. },
  27688. bindings: {
  27689. get total() {
  27690. return scope._bindings.length;
  27691. },
  27692. get inUse() {
  27693. return scope._nActiveBindings;
  27694. }
  27695. },
  27696. controlInterpolants: {
  27697. get total() {
  27698. return scope._controlInterpolants.length;
  27699. },
  27700. get inUse() {
  27701. return scope._nActiveControlInterpolants;
  27702. }
  27703. }
  27704. };
  27705. }
  27706. // Memory management for AnimationAction objects
  27707. _isActiveAction( action ) {
  27708. const index = action._cacheIndex;
  27709. return index !== null && index < this._nActiveActions;
  27710. }
  27711. _addInactiveAction( action, clipUuid, rootUuid ) {
  27712. const actions = this._actions,
  27713. actionsByClip = this._actionsByClip;
  27714. let actionsForClip = actionsByClip[ clipUuid ];
  27715. if ( actionsForClip === undefined ) {
  27716. actionsForClip = {
  27717. knownActions: [ action ],
  27718. actionByRoot: {}
  27719. };
  27720. action._byClipCacheIndex = 0;
  27721. actionsByClip[ clipUuid ] = actionsForClip;
  27722. } else {
  27723. const knownActions = actionsForClip.knownActions;
  27724. action._byClipCacheIndex = knownActions.length;
  27725. knownActions.push( action );
  27726. }
  27727. action._cacheIndex = actions.length;
  27728. actions.push( action );
  27729. actionsForClip.actionByRoot[ rootUuid ] = action;
  27730. }
  27731. _removeInactiveAction( action ) {
  27732. const actions = this._actions,
  27733. lastInactiveAction = actions[ actions.length - 1 ],
  27734. cacheIndex = action._cacheIndex;
  27735. lastInactiveAction._cacheIndex = cacheIndex;
  27736. actions[ cacheIndex ] = lastInactiveAction;
  27737. actions.pop();
  27738. action._cacheIndex = null;
  27739. const clipUuid = action._clip.uuid,
  27740. actionsByClip = this._actionsByClip,
  27741. actionsForClip = actionsByClip[ clipUuid ],
  27742. knownActionsForClip = actionsForClip.knownActions,
  27743. lastKnownAction =
  27744. knownActionsForClip[ knownActionsForClip.length - 1 ],
  27745. byClipCacheIndex = action._byClipCacheIndex;
  27746. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27747. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  27748. knownActionsForClip.pop();
  27749. action._byClipCacheIndex = null;
  27750. const actionByRoot = actionsForClip.actionByRoot,
  27751. rootUuid = ( action._localRoot || this._root ).uuid;
  27752. delete actionByRoot[ rootUuid ];
  27753. if ( knownActionsForClip.length === 0 ) {
  27754. delete actionsByClip[ clipUuid ];
  27755. }
  27756. this._removeInactiveBindingsForAction( action );
  27757. }
  27758. _removeInactiveBindingsForAction( action ) {
  27759. const bindings = action._propertyBindings;
  27760. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27761. const binding = bindings[ i ];
  27762. if ( -- binding.referenceCount === 0 ) {
  27763. this._removeInactiveBinding( binding );
  27764. }
  27765. }
  27766. }
  27767. _lendAction( action ) {
  27768. // [ active actions | inactive actions ]
  27769. // [ active actions >| inactive actions ]
  27770. // s a
  27771. // <-swap->
  27772. // a s
  27773. const actions = this._actions,
  27774. prevIndex = action._cacheIndex,
  27775. lastActiveIndex = this._nActiveActions ++,
  27776. firstInactiveAction = actions[ lastActiveIndex ];
  27777. action._cacheIndex = lastActiveIndex;
  27778. actions[ lastActiveIndex ] = action;
  27779. firstInactiveAction._cacheIndex = prevIndex;
  27780. actions[ prevIndex ] = firstInactiveAction;
  27781. }
  27782. _takeBackAction( action ) {
  27783. // [ active actions | inactive actions ]
  27784. // [ active actions |< inactive actions ]
  27785. // a s
  27786. // <-swap->
  27787. // s a
  27788. const actions = this._actions,
  27789. prevIndex = action._cacheIndex,
  27790. firstInactiveIndex = -- this._nActiveActions,
  27791. lastActiveAction = actions[ firstInactiveIndex ];
  27792. action._cacheIndex = firstInactiveIndex;
  27793. actions[ firstInactiveIndex ] = action;
  27794. lastActiveAction._cacheIndex = prevIndex;
  27795. actions[ prevIndex ] = lastActiveAction;
  27796. }
  27797. // Memory management for PropertyMixer objects
  27798. _addInactiveBinding( binding, rootUuid, trackName ) {
  27799. const bindingsByRoot = this._bindingsByRootAndName,
  27800. bindings = this._bindings;
  27801. let bindingByName = bindingsByRoot[ rootUuid ];
  27802. if ( bindingByName === undefined ) {
  27803. bindingByName = {};
  27804. bindingsByRoot[ rootUuid ] = bindingByName;
  27805. }
  27806. bindingByName[ trackName ] = binding;
  27807. binding._cacheIndex = bindings.length;
  27808. bindings.push( binding );
  27809. }
  27810. _removeInactiveBinding( binding ) {
  27811. const bindings = this._bindings,
  27812. propBinding = binding.binding,
  27813. rootUuid = propBinding.rootNode.uuid,
  27814. trackName = propBinding.path,
  27815. bindingsByRoot = this._bindingsByRootAndName,
  27816. bindingByName = bindingsByRoot[ rootUuid ],
  27817. lastInactiveBinding = bindings[ bindings.length - 1 ],
  27818. cacheIndex = binding._cacheIndex;
  27819. lastInactiveBinding._cacheIndex = cacheIndex;
  27820. bindings[ cacheIndex ] = lastInactiveBinding;
  27821. bindings.pop();
  27822. delete bindingByName[ trackName ];
  27823. if ( Object.keys( bindingByName ).length === 0 ) {
  27824. delete bindingsByRoot[ rootUuid ];
  27825. }
  27826. }
  27827. _lendBinding( binding ) {
  27828. const bindings = this._bindings,
  27829. prevIndex = binding._cacheIndex,
  27830. lastActiveIndex = this._nActiveBindings ++,
  27831. firstInactiveBinding = bindings[ lastActiveIndex ];
  27832. binding._cacheIndex = lastActiveIndex;
  27833. bindings[ lastActiveIndex ] = binding;
  27834. firstInactiveBinding._cacheIndex = prevIndex;
  27835. bindings[ prevIndex ] = firstInactiveBinding;
  27836. }
  27837. _takeBackBinding( binding ) {
  27838. const bindings = this._bindings,
  27839. prevIndex = binding._cacheIndex,
  27840. firstInactiveIndex = -- this._nActiveBindings,
  27841. lastActiveBinding = bindings[ firstInactiveIndex ];
  27842. binding._cacheIndex = firstInactiveIndex;
  27843. bindings[ firstInactiveIndex ] = binding;
  27844. lastActiveBinding._cacheIndex = prevIndex;
  27845. bindings[ prevIndex ] = lastActiveBinding;
  27846. }
  27847. // Memory management of Interpolants for weight and time scale
  27848. _lendControlInterpolant() {
  27849. const interpolants = this._controlInterpolants,
  27850. lastActiveIndex = this._nActiveControlInterpolants ++;
  27851. let interpolant = interpolants[ lastActiveIndex ];
  27852. if ( interpolant === undefined ) {
  27853. interpolant = new LinearInterpolant(
  27854. new Float32Array( 2 ), new Float32Array( 2 ),
  27855. 1, _controlInterpolantsResultBuffer );
  27856. interpolant.__cacheIndex = lastActiveIndex;
  27857. interpolants[ lastActiveIndex ] = interpolant;
  27858. }
  27859. return interpolant;
  27860. }
  27861. _takeBackControlInterpolant( interpolant ) {
  27862. const interpolants = this._controlInterpolants,
  27863. prevIndex = interpolant.__cacheIndex,
  27864. firstInactiveIndex = -- this._nActiveControlInterpolants,
  27865. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  27866. interpolant.__cacheIndex = firstInactiveIndex;
  27867. interpolants[ firstInactiveIndex ] = interpolant;
  27868. lastActiveInterpolant.__cacheIndex = prevIndex;
  27869. interpolants[ prevIndex ] = lastActiveInterpolant;
  27870. }
  27871. // return an action for a clip optionally using a custom root target
  27872. // object (this method allocates a lot of dynamic memory in case a
  27873. // previously unknown clip/root combination is specified)
  27874. clipAction( clip, optionalRoot, blendMode ) {
  27875. const root = optionalRoot || this._root,
  27876. rootUuid = root.uuid;
  27877. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  27878. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  27879. const actionsForClip = this._actionsByClip[ clipUuid ];
  27880. let prototypeAction = null;
  27881. if ( blendMode === undefined ) {
  27882. if ( clipObject !== null ) {
  27883. blendMode = clipObject.blendMode;
  27884. } else {
  27885. blendMode = NormalAnimationBlendMode;
  27886. }
  27887. }
  27888. if ( actionsForClip !== undefined ) {
  27889. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  27890. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  27891. return existingAction;
  27892. }
  27893. // we know the clip, so we don't have to parse all
  27894. // the bindings again but can just copy
  27895. prototypeAction = actionsForClip.knownActions[ 0 ];
  27896. // also, take the clip from the prototype action
  27897. if ( clipObject === null )
  27898. clipObject = prototypeAction._clip;
  27899. }
  27900. // clip must be known when specified via string
  27901. if ( clipObject === null ) return null;
  27902. // allocate all resources required to run it
  27903. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  27904. this._bindAction( newAction, prototypeAction );
  27905. // and make the action known to the memory manager
  27906. this._addInactiveAction( newAction, clipUuid, rootUuid );
  27907. return newAction;
  27908. }
  27909. // get an existing action
  27910. existingAction( clip, optionalRoot ) {
  27911. const root = optionalRoot || this._root,
  27912. rootUuid = root.uuid,
  27913. clipObject = typeof clip === 'string' ?
  27914. AnimationClip.findByName( root, clip ) : clip,
  27915. clipUuid = clipObject ? clipObject.uuid : clip,
  27916. actionsForClip = this._actionsByClip[ clipUuid ];
  27917. if ( actionsForClip !== undefined ) {
  27918. return actionsForClip.actionByRoot[ rootUuid ] || null;
  27919. }
  27920. return null;
  27921. }
  27922. // deactivates all previously scheduled actions
  27923. stopAllAction() {
  27924. const actions = this._actions,
  27925. nActions = this._nActiveActions;
  27926. for ( let i = nActions - 1; i >= 0; -- i ) {
  27927. actions[ i ].stop();
  27928. }
  27929. return this;
  27930. }
  27931. // advance the time and update apply the animation
  27932. update( deltaTime ) {
  27933. deltaTime *= this.timeScale;
  27934. const actions = this._actions,
  27935. nActions = this._nActiveActions,
  27936. time = this.time += deltaTime,
  27937. timeDirection = Math.sign( deltaTime ),
  27938. accuIndex = this._accuIndex ^= 1;
  27939. // run active actions
  27940. for ( let i = 0; i !== nActions; ++ i ) {
  27941. const action = actions[ i ];
  27942. action._update( time, deltaTime, timeDirection, accuIndex );
  27943. }
  27944. // update scene graph
  27945. const bindings = this._bindings,
  27946. nBindings = this._nActiveBindings;
  27947. for ( let i = 0; i !== nBindings; ++ i ) {
  27948. bindings[ i ].apply( accuIndex );
  27949. }
  27950. return this;
  27951. }
  27952. // Allows you to seek to a specific time in an animation.
  27953. setTime( timeInSeconds ) {
  27954. this.time = 0; // Zero out time attribute for AnimationMixer object;
  27955. for ( let i = 0; i < this._actions.length; i ++ ) {
  27956. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  27957. }
  27958. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  27959. }
  27960. // return this mixer's root target object
  27961. getRoot() {
  27962. return this._root;
  27963. }
  27964. // free all resources specific to a particular clip
  27965. uncacheClip( clip ) {
  27966. const actions = this._actions,
  27967. clipUuid = clip.uuid,
  27968. actionsByClip = this._actionsByClip,
  27969. actionsForClip = actionsByClip[ clipUuid ];
  27970. if ( actionsForClip !== undefined ) {
  27971. // note: just calling _removeInactiveAction would mess up the
  27972. // iteration state and also require updating the state we can
  27973. // just throw away
  27974. const actionsToRemove = actionsForClip.knownActions;
  27975. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  27976. const action = actionsToRemove[ i ];
  27977. this._deactivateAction( action );
  27978. const cacheIndex = action._cacheIndex,
  27979. lastInactiveAction = actions[ actions.length - 1 ];
  27980. action._cacheIndex = null;
  27981. action._byClipCacheIndex = null;
  27982. lastInactiveAction._cacheIndex = cacheIndex;
  27983. actions[ cacheIndex ] = lastInactiveAction;
  27984. actions.pop();
  27985. this._removeInactiveBindingsForAction( action );
  27986. }
  27987. delete actionsByClip[ clipUuid ];
  27988. }
  27989. }
  27990. // free all resources specific to a particular root target object
  27991. uncacheRoot( root ) {
  27992. const rootUuid = root.uuid,
  27993. actionsByClip = this._actionsByClip;
  27994. for ( const clipUuid in actionsByClip ) {
  27995. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  27996. action = actionByRoot[ rootUuid ];
  27997. if ( action !== undefined ) {
  27998. this._deactivateAction( action );
  27999. this._removeInactiveAction( action );
  28000. }
  28001. }
  28002. const bindingsByRoot = this._bindingsByRootAndName,
  28003. bindingByName = bindingsByRoot[ rootUuid ];
  28004. if ( bindingByName !== undefined ) {
  28005. for ( const trackName in bindingByName ) {
  28006. const binding = bindingByName[ trackName ];
  28007. binding.restoreOriginalState();
  28008. this._removeInactiveBinding( binding );
  28009. }
  28010. }
  28011. }
  28012. // remove a targeted clip from the cache
  28013. uncacheAction( clip, optionalRoot ) {
  28014. const action = this.existingAction( clip, optionalRoot );
  28015. if ( action !== null ) {
  28016. this._deactivateAction( action );
  28017. this._removeInactiveAction( action );
  28018. }
  28019. }
  28020. }
  28021. class Uniform {
  28022. constructor( value ) {
  28023. this.value = value;
  28024. }
  28025. clone() {
  28026. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  28027. }
  28028. }
  28029. let id = 0;
  28030. class UniformsGroup extends EventDispatcher {
  28031. constructor() {
  28032. super();
  28033. this.isUniformsGroup = true;
  28034. Object.defineProperty( this, 'id', { value: id ++ } );
  28035. this.name = '';
  28036. this.usage = StaticDrawUsage;
  28037. this.uniforms = [];
  28038. }
  28039. add( uniform ) {
  28040. this.uniforms.push( uniform );
  28041. return this;
  28042. }
  28043. remove( uniform ) {
  28044. const index = this.uniforms.indexOf( uniform );
  28045. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  28046. return this;
  28047. }
  28048. setName( name ) {
  28049. this.name = name;
  28050. return this;
  28051. }
  28052. setUsage( value ) {
  28053. this.usage = value;
  28054. return this;
  28055. }
  28056. dispose() {
  28057. this.dispatchEvent( { type: 'dispose' } );
  28058. return this;
  28059. }
  28060. copy( source ) {
  28061. this.name = source.name;
  28062. this.usage = source.usage;
  28063. const uniformsSource = source.uniforms;
  28064. this.uniforms.length = 0;
  28065. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  28066. this.uniforms.push( uniformsSource[ i ].clone() );
  28067. }
  28068. return this;
  28069. }
  28070. clone() {
  28071. return new this.constructor().copy( this );
  28072. }
  28073. }
  28074. class InstancedInterleavedBuffer extends InterleavedBuffer {
  28075. constructor( array, stride, meshPerAttribute = 1 ) {
  28076. super( array, stride );
  28077. this.isInstancedInterleavedBuffer = true;
  28078. this.meshPerAttribute = meshPerAttribute;
  28079. }
  28080. copy( source ) {
  28081. super.copy( source );
  28082. this.meshPerAttribute = source.meshPerAttribute;
  28083. return this;
  28084. }
  28085. clone( data ) {
  28086. const ib = super.clone( data );
  28087. ib.meshPerAttribute = this.meshPerAttribute;
  28088. return ib;
  28089. }
  28090. toJSON( data ) {
  28091. const json = super.toJSON( data );
  28092. json.isInstancedInterleavedBuffer = true;
  28093. json.meshPerAttribute = this.meshPerAttribute;
  28094. return json;
  28095. }
  28096. }
  28097. class GLBufferAttribute {
  28098. constructor( buffer, type, itemSize, elementSize, count ) {
  28099. this.isGLBufferAttribute = true;
  28100. this.name = '';
  28101. this.buffer = buffer;
  28102. this.type = type;
  28103. this.itemSize = itemSize;
  28104. this.elementSize = elementSize;
  28105. this.count = count;
  28106. this.version = 0;
  28107. }
  28108. set needsUpdate( value ) {
  28109. if ( value === true ) this.version ++;
  28110. }
  28111. setBuffer( buffer ) {
  28112. this.buffer = buffer;
  28113. return this;
  28114. }
  28115. setType( type, elementSize ) {
  28116. this.type = type;
  28117. this.elementSize = elementSize;
  28118. return this;
  28119. }
  28120. setItemSize( itemSize ) {
  28121. this.itemSize = itemSize;
  28122. return this;
  28123. }
  28124. setCount( count ) {
  28125. this.count = count;
  28126. return this;
  28127. }
  28128. }
  28129. class Raycaster {
  28130. constructor( origin, direction, near = 0, far = Infinity ) {
  28131. this.ray = new Ray( origin, direction );
  28132. // direction is assumed to be normalized (for accurate distance calculations)
  28133. this.near = near;
  28134. this.far = far;
  28135. this.camera = null;
  28136. this.layers = new Layers();
  28137. this.params = {
  28138. Mesh: {},
  28139. Line: { threshold: 1 },
  28140. LOD: {},
  28141. Points: { threshold: 1 },
  28142. Sprite: {}
  28143. };
  28144. }
  28145. set( origin, direction ) {
  28146. // direction is assumed to be normalized (for accurate distance calculations)
  28147. this.ray.set( origin, direction );
  28148. }
  28149. setFromCamera( coords, camera ) {
  28150. if ( camera.isPerspectiveCamera ) {
  28151. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  28152. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  28153. this.camera = camera;
  28154. } else if ( camera.isOrthographicCamera ) {
  28155. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  28156. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  28157. this.camera = camera;
  28158. } else {
  28159. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  28160. }
  28161. }
  28162. intersectObject( object, recursive = true, intersects = [] ) {
  28163. intersectObject( object, this, intersects, recursive );
  28164. intersects.sort( ascSort );
  28165. return intersects;
  28166. }
  28167. intersectObjects( objects, recursive = true, intersects = [] ) {
  28168. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  28169. intersectObject( objects[ i ], this, intersects, recursive );
  28170. }
  28171. intersects.sort( ascSort );
  28172. return intersects;
  28173. }
  28174. }
  28175. function ascSort( a, b ) {
  28176. return a.distance - b.distance;
  28177. }
  28178. function intersectObject( object, raycaster, intersects, recursive ) {
  28179. if ( object.layers.test( raycaster.layers ) ) {
  28180. object.raycast( raycaster, intersects );
  28181. }
  28182. if ( recursive === true ) {
  28183. const children = object.children;
  28184. for ( let i = 0, l = children.length; i < l; i ++ ) {
  28185. intersectObject( children[ i ], raycaster, intersects, true );
  28186. }
  28187. }
  28188. }
  28189. /**
  28190. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  28191. *
  28192. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  28193. * The azimuthal angle (theta) is measured from the positive z-axis.
  28194. */
  28195. class Spherical {
  28196. constructor( radius = 1, phi = 0, theta = 0 ) {
  28197. this.radius = radius;
  28198. this.phi = phi; // polar angle
  28199. this.theta = theta; // azimuthal angle
  28200. return this;
  28201. }
  28202. set( radius, phi, theta ) {
  28203. this.radius = radius;
  28204. this.phi = phi;
  28205. this.theta = theta;
  28206. return this;
  28207. }
  28208. copy( other ) {
  28209. this.radius = other.radius;
  28210. this.phi = other.phi;
  28211. this.theta = other.theta;
  28212. return this;
  28213. }
  28214. // restrict phi to be between EPS and PI-EPS
  28215. makeSafe() {
  28216. const EPS = 0.000001;
  28217. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  28218. return this;
  28219. }
  28220. setFromVector3( v ) {
  28221. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28222. }
  28223. setFromCartesianCoords( x, y, z ) {
  28224. this.radius = Math.sqrt( x * x + y * y + z * z );
  28225. if ( this.radius === 0 ) {
  28226. this.theta = 0;
  28227. this.phi = 0;
  28228. } else {
  28229. this.theta = Math.atan2( x, z );
  28230. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  28231. }
  28232. return this;
  28233. }
  28234. clone() {
  28235. return new this.constructor().copy( this );
  28236. }
  28237. }
  28238. /**
  28239. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  28240. */
  28241. class Cylindrical {
  28242. constructor( radius = 1, theta = 0, y = 0 ) {
  28243. this.radius = radius; // distance from the origin to a point in the x-z plane
  28244. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  28245. this.y = y; // height above the x-z plane
  28246. return this;
  28247. }
  28248. set( radius, theta, y ) {
  28249. this.radius = radius;
  28250. this.theta = theta;
  28251. this.y = y;
  28252. return this;
  28253. }
  28254. copy( other ) {
  28255. this.radius = other.radius;
  28256. this.theta = other.theta;
  28257. this.y = other.y;
  28258. return this;
  28259. }
  28260. setFromVector3( v ) {
  28261. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28262. }
  28263. setFromCartesianCoords( x, y, z ) {
  28264. this.radius = Math.sqrt( x * x + z * z );
  28265. this.theta = Math.atan2( x, z );
  28266. this.y = y;
  28267. return this;
  28268. }
  28269. clone() {
  28270. return new this.constructor().copy( this );
  28271. }
  28272. }
  28273. const _vector$4 = /*@__PURE__*/ new Vector2();
  28274. class Box2 {
  28275. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  28276. this.isBox2 = true;
  28277. this.min = min;
  28278. this.max = max;
  28279. }
  28280. set( min, max ) {
  28281. this.min.copy( min );
  28282. this.max.copy( max );
  28283. return this;
  28284. }
  28285. setFromPoints( points ) {
  28286. this.makeEmpty();
  28287. for ( let i = 0, il = points.length; i < il; i ++ ) {
  28288. this.expandByPoint( points[ i ] );
  28289. }
  28290. return this;
  28291. }
  28292. setFromCenterAndSize( center, size ) {
  28293. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  28294. this.min.copy( center ).sub( halfSize );
  28295. this.max.copy( center ).add( halfSize );
  28296. return this;
  28297. }
  28298. clone() {
  28299. return new this.constructor().copy( this );
  28300. }
  28301. copy( box ) {
  28302. this.min.copy( box.min );
  28303. this.max.copy( box.max );
  28304. return this;
  28305. }
  28306. makeEmpty() {
  28307. this.min.x = this.min.y = + Infinity;
  28308. this.max.x = this.max.y = - Infinity;
  28309. return this;
  28310. }
  28311. isEmpty() {
  28312. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  28313. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  28314. }
  28315. getCenter( target ) {
  28316. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  28317. }
  28318. getSize( target ) {
  28319. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  28320. }
  28321. expandByPoint( point ) {
  28322. this.min.min( point );
  28323. this.max.max( point );
  28324. return this;
  28325. }
  28326. expandByVector( vector ) {
  28327. this.min.sub( vector );
  28328. this.max.add( vector );
  28329. return this;
  28330. }
  28331. expandByScalar( scalar ) {
  28332. this.min.addScalar( - scalar );
  28333. this.max.addScalar( scalar );
  28334. return this;
  28335. }
  28336. containsPoint( point ) {
  28337. return point.x < this.min.x || point.x > this.max.x ||
  28338. point.y < this.min.y || point.y > this.max.y ? false : true;
  28339. }
  28340. containsBox( box ) {
  28341. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  28342. this.min.y <= box.min.y && box.max.y <= this.max.y;
  28343. }
  28344. getParameter( point, target ) {
  28345. // This can potentially have a divide by zero if the box
  28346. // has a size dimension of 0.
  28347. return target.set(
  28348. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  28349. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  28350. );
  28351. }
  28352. intersectsBox( box ) {
  28353. // using 4 splitting planes to rule out intersections
  28354. return box.max.x < this.min.x || box.min.x > this.max.x ||
  28355. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  28356. }
  28357. clampPoint( point, target ) {
  28358. return target.copy( point ).clamp( this.min, this.max );
  28359. }
  28360. distanceToPoint( point ) {
  28361. const clampedPoint = _vector$4.copy( point ).clamp( this.min, this.max );
  28362. return clampedPoint.sub( point ).length();
  28363. }
  28364. intersect( box ) {
  28365. this.min.max( box.min );
  28366. this.max.min( box.max );
  28367. return this;
  28368. }
  28369. union( box ) {
  28370. this.min.min( box.min );
  28371. this.max.max( box.max );
  28372. return this;
  28373. }
  28374. translate( offset ) {
  28375. this.min.add( offset );
  28376. this.max.add( offset );
  28377. return this;
  28378. }
  28379. equals( box ) {
  28380. return box.min.equals( this.min ) && box.max.equals( this.max );
  28381. }
  28382. }
  28383. const _startP = /*@__PURE__*/ new Vector3();
  28384. const _startEnd = /*@__PURE__*/ new Vector3();
  28385. class Line3 {
  28386. constructor( start = new Vector3(), end = new Vector3() ) {
  28387. this.start = start;
  28388. this.end = end;
  28389. }
  28390. set( start, end ) {
  28391. this.start.copy( start );
  28392. this.end.copy( end );
  28393. return this;
  28394. }
  28395. copy( line ) {
  28396. this.start.copy( line.start );
  28397. this.end.copy( line.end );
  28398. return this;
  28399. }
  28400. getCenter( target ) {
  28401. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  28402. }
  28403. delta( target ) {
  28404. return target.subVectors( this.end, this.start );
  28405. }
  28406. distanceSq() {
  28407. return this.start.distanceToSquared( this.end );
  28408. }
  28409. distance() {
  28410. return this.start.distanceTo( this.end );
  28411. }
  28412. at( t, target ) {
  28413. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28414. }
  28415. closestPointToPointParameter( point, clampToLine ) {
  28416. _startP.subVectors( point, this.start );
  28417. _startEnd.subVectors( this.end, this.start );
  28418. const startEnd2 = _startEnd.dot( _startEnd );
  28419. const startEnd_startP = _startEnd.dot( _startP );
  28420. let t = startEnd_startP / startEnd2;
  28421. if ( clampToLine ) {
  28422. t = clamp( t, 0, 1 );
  28423. }
  28424. return t;
  28425. }
  28426. closestPointToPoint( point, clampToLine, target ) {
  28427. const t = this.closestPointToPointParameter( point, clampToLine );
  28428. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28429. }
  28430. applyMatrix4( matrix ) {
  28431. this.start.applyMatrix4( matrix );
  28432. this.end.applyMatrix4( matrix );
  28433. return this;
  28434. }
  28435. equals( line ) {
  28436. return line.start.equals( this.start ) && line.end.equals( this.end );
  28437. }
  28438. clone() {
  28439. return new this.constructor().copy( this );
  28440. }
  28441. }
  28442. const _vector$3 = /*@__PURE__*/ new Vector3();
  28443. class SpotLightHelper extends Object3D {
  28444. constructor( light, color ) {
  28445. super();
  28446. this.light = light;
  28447. this.matrix = light.matrixWorld;
  28448. this.matrixAutoUpdate = false;
  28449. this.color = color;
  28450. this.type = 'SpotLightHelper';
  28451. const geometry = new BufferGeometry();
  28452. const positions = [
  28453. 0, 0, 0, 0, 0, 1,
  28454. 0, 0, 0, 1, 0, 1,
  28455. 0, 0, 0, - 1, 0, 1,
  28456. 0, 0, 0, 0, 1, 1,
  28457. 0, 0, 0, 0, - 1, 1
  28458. ];
  28459. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  28460. const p1 = ( i / l ) * Math.PI * 2;
  28461. const p2 = ( j / l ) * Math.PI * 2;
  28462. positions.push(
  28463. Math.cos( p1 ), Math.sin( p1 ), 1,
  28464. Math.cos( p2 ), Math.sin( p2 ), 1
  28465. );
  28466. }
  28467. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28468. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28469. this.cone = new LineSegments( geometry, material );
  28470. this.add( this.cone );
  28471. this.update();
  28472. }
  28473. dispose() {
  28474. this.cone.geometry.dispose();
  28475. this.cone.material.dispose();
  28476. }
  28477. update() {
  28478. this.light.updateWorldMatrix( true, false );
  28479. this.light.target.updateWorldMatrix( true, false );
  28480. const coneLength = this.light.distance ? this.light.distance : 1000;
  28481. const coneWidth = coneLength * Math.tan( this.light.angle );
  28482. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  28483. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  28484. this.cone.lookAt( _vector$3 );
  28485. if ( this.color !== undefined ) {
  28486. this.cone.material.color.set( this.color );
  28487. } else {
  28488. this.cone.material.color.copy( this.light.color );
  28489. }
  28490. }
  28491. }
  28492. const _vector$2 = /*@__PURE__*/ new Vector3();
  28493. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  28494. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  28495. class SkeletonHelper extends LineSegments {
  28496. constructor( object ) {
  28497. const bones = getBoneList( object );
  28498. const geometry = new BufferGeometry();
  28499. const vertices = [];
  28500. const colors = [];
  28501. const color1 = new Color( 0, 0, 1 );
  28502. const color2 = new Color( 0, 1, 0 );
  28503. for ( let i = 0; i < bones.length; i ++ ) {
  28504. const bone = bones[ i ];
  28505. if ( bone.parent && bone.parent.isBone ) {
  28506. vertices.push( 0, 0, 0 );
  28507. vertices.push( 0, 0, 0 );
  28508. colors.push( color1.r, color1.g, color1.b );
  28509. colors.push( color2.r, color2.g, color2.b );
  28510. }
  28511. }
  28512. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28513. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28514. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  28515. super( geometry, material );
  28516. this.isSkeletonHelper = true;
  28517. this.type = 'SkeletonHelper';
  28518. this.root = object;
  28519. this.bones = bones;
  28520. this.matrix = object.matrixWorld;
  28521. this.matrixAutoUpdate = false;
  28522. }
  28523. updateMatrixWorld( force ) {
  28524. const bones = this.bones;
  28525. const geometry = this.geometry;
  28526. const position = geometry.getAttribute( 'position' );
  28527. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  28528. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  28529. const bone = bones[ i ];
  28530. if ( bone.parent && bone.parent.isBone ) {
  28531. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  28532. _vector$2.setFromMatrixPosition( _boneMatrix );
  28533. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  28534. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  28535. _vector$2.setFromMatrixPosition( _boneMatrix );
  28536. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  28537. j += 2;
  28538. }
  28539. }
  28540. geometry.getAttribute( 'position' ).needsUpdate = true;
  28541. super.updateMatrixWorld( force );
  28542. }
  28543. dispose() {
  28544. this.geometry.dispose();
  28545. this.material.dispose();
  28546. }
  28547. }
  28548. function getBoneList( object ) {
  28549. const boneList = [];
  28550. if ( object.isBone === true ) {
  28551. boneList.push( object );
  28552. }
  28553. for ( let i = 0; i < object.children.length; i ++ ) {
  28554. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  28555. }
  28556. return boneList;
  28557. }
  28558. class PointLightHelper extends Mesh {
  28559. constructor( light, sphereSize, color ) {
  28560. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  28561. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28562. super( geometry, material );
  28563. this.light = light;
  28564. this.color = color;
  28565. this.type = 'PointLightHelper';
  28566. this.matrix = this.light.matrixWorld;
  28567. this.matrixAutoUpdate = false;
  28568. this.update();
  28569. /*
  28570. // TODO: delete this comment?
  28571. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  28572. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28573. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28574. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28575. const d = light.distance;
  28576. if ( d === 0.0 ) {
  28577. this.lightDistance.visible = false;
  28578. } else {
  28579. this.lightDistance.scale.set( d, d, d );
  28580. }
  28581. this.add( this.lightDistance );
  28582. */
  28583. }
  28584. dispose() {
  28585. this.geometry.dispose();
  28586. this.material.dispose();
  28587. }
  28588. update() {
  28589. this.light.updateWorldMatrix( true, false );
  28590. if ( this.color !== undefined ) {
  28591. this.material.color.set( this.color );
  28592. } else {
  28593. this.material.color.copy( this.light.color );
  28594. }
  28595. /*
  28596. const d = this.light.distance;
  28597. if ( d === 0.0 ) {
  28598. this.lightDistance.visible = false;
  28599. } else {
  28600. this.lightDistance.visible = true;
  28601. this.lightDistance.scale.set( d, d, d );
  28602. }
  28603. */
  28604. }
  28605. }
  28606. const _vector$1 = /*@__PURE__*/ new Vector3();
  28607. const _color1 = /*@__PURE__*/ new Color();
  28608. const _color2 = /*@__PURE__*/ new Color();
  28609. class HemisphereLightHelper extends Object3D {
  28610. constructor( light, size, color ) {
  28611. super();
  28612. this.light = light;
  28613. this.matrix = light.matrixWorld;
  28614. this.matrixAutoUpdate = false;
  28615. this.color = color;
  28616. this.type = 'HemisphereLightHelper';
  28617. const geometry = new OctahedronGeometry( size );
  28618. geometry.rotateY( Math.PI * 0.5 );
  28619. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28620. if ( this.color === undefined ) this.material.vertexColors = true;
  28621. const position = geometry.getAttribute( 'position' );
  28622. const colors = new Float32Array( position.count * 3 );
  28623. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  28624. this.add( new Mesh( geometry, this.material ) );
  28625. this.update();
  28626. }
  28627. dispose() {
  28628. this.children[ 0 ].geometry.dispose();
  28629. this.children[ 0 ].material.dispose();
  28630. }
  28631. update() {
  28632. const mesh = this.children[ 0 ];
  28633. if ( this.color !== undefined ) {
  28634. this.material.color.set( this.color );
  28635. } else {
  28636. const colors = mesh.geometry.getAttribute( 'color' );
  28637. _color1.copy( this.light.color );
  28638. _color2.copy( this.light.groundColor );
  28639. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  28640. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  28641. colors.setXYZ( i, color.r, color.g, color.b );
  28642. }
  28643. colors.needsUpdate = true;
  28644. }
  28645. this.light.updateWorldMatrix( true, false );
  28646. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  28647. }
  28648. }
  28649. class GridHelper extends LineSegments {
  28650. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  28651. color1 = new Color( color1 );
  28652. color2 = new Color( color2 );
  28653. const center = divisions / 2;
  28654. const step = size / divisions;
  28655. const halfSize = size / 2;
  28656. const vertices = [], colors = [];
  28657. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  28658. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  28659. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  28660. const color = i === center ? color1 : color2;
  28661. color.toArray( colors, j ); j += 3;
  28662. color.toArray( colors, j ); j += 3;
  28663. color.toArray( colors, j ); j += 3;
  28664. color.toArray( colors, j ); j += 3;
  28665. }
  28666. const geometry = new BufferGeometry();
  28667. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28668. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28669. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28670. super( geometry, material );
  28671. this.type = 'GridHelper';
  28672. }
  28673. dispose() {
  28674. this.geometry.dispose();
  28675. this.material.dispose();
  28676. }
  28677. }
  28678. class PolarGridHelper extends LineSegments {
  28679. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  28680. color1 = new Color( color1 );
  28681. color2 = new Color( color2 );
  28682. const vertices = [];
  28683. const colors = [];
  28684. // create the sectors
  28685. if ( sectors > 1 ) {
  28686. for ( let i = 0; i < sectors; i ++ ) {
  28687. const v = ( i / sectors ) * ( Math.PI * 2 );
  28688. const x = Math.sin( v ) * radius;
  28689. const z = Math.cos( v ) * radius;
  28690. vertices.push( 0, 0, 0 );
  28691. vertices.push( x, 0, z );
  28692. const color = ( i & 1 ) ? color1 : color2;
  28693. colors.push( color.r, color.g, color.b );
  28694. colors.push( color.r, color.g, color.b );
  28695. }
  28696. }
  28697. // create the rings
  28698. for ( let i = 0; i < rings; i ++ ) {
  28699. const color = ( i & 1 ) ? color1 : color2;
  28700. const r = radius - ( radius / rings * i );
  28701. for ( let j = 0; j < divisions; j ++ ) {
  28702. // first vertex
  28703. let v = ( j / divisions ) * ( Math.PI * 2 );
  28704. let x = Math.sin( v ) * r;
  28705. let z = Math.cos( v ) * r;
  28706. vertices.push( x, 0, z );
  28707. colors.push( color.r, color.g, color.b );
  28708. // second vertex
  28709. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  28710. x = Math.sin( v ) * r;
  28711. z = Math.cos( v ) * r;
  28712. vertices.push( x, 0, z );
  28713. colors.push( color.r, color.g, color.b );
  28714. }
  28715. }
  28716. const geometry = new BufferGeometry();
  28717. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28718. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28719. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28720. super( geometry, material );
  28721. this.type = 'PolarGridHelper';
  28722. }
  28723. dispose() {
  28724. this.geometry.dispose();
  28725. this.material.dispose();
  28726. }
  28727. }
  28728. const _v1 = /*@__PURE__*/ new Vector3();
  28729. const _v2 = /*@__PURE__*/ new Vector3();
  28730. const _v3 = /*@__PURE__*/ new Vector3();
  28731. class DirectionalLightHelper extends Object3D {
  28732. constructor( light, size, color ) {
  28733. super();
  28734. this.light = light;
  28735. this.matrix = light.matrixWorld;
  28736. this.matrixAutoUpdate = false;
  28737. this.color = color;
  28738. this.type = 'DirectionalLightHelper';
  28739. if ( size === undefined ) size = 1;
  28740. let geometry = new BufferGeometry();
  28741. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  28742. - size, size, 0,
  28743. size, size, 0,
  28744. size, - size, 0,
  28745. - size, - size, 0,
  28746. - size, size, 0
  28747. ], 3 ) );
  28748. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28749. this.lightPlane = new Line( geometry, material );
  28750. this.add( this.lightPlane );
  28751. geometry = new BufferGeometry();
  28752. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  28753. this.targetLine = new Line( geometry, material );
  28754. this.add( this.targetLine );
  28755. this.update();
  28756. }
  28757. dispose() {
  28758. this.lightPlane.geometry.dispose();
  28759. this.lightPlane.material.dispose();
  28760. this.targetLine.geometry.dispose();
  28761. this.targetLine.material.dispose();
  28762. }
  28763. update() {
  28764. this.light.updateWorldMatrix( true, false );
  28765. this.light.target.updateWorldMatrix( true, false );
  28766. _v1.setFromMatrixPosition( this.light.matrixWorld );
  28767. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  28768. _v3.subVectors( _v2, _v1 );
  28769. this.lightPlane.lookAt( _v2 );
  28770. if ( this.color !== undefined ) {
  28771. this.lightPlane.material.color.set( this.color );
  28772. this.targetLine.material.color.set( this.color );
  28773. } else {
  28774. this.lightPlane.material.color.copy( this.light.color );
  28775. this.targetLine.material.color.copy( this.light.color );
  28776. }
  28777. this.targetLine.lookAt( _v2 );
  28778. this.targetLine.scale.z = _v3.length();
  28779. }
  28780. }
  28781. const _vector = /*@__PURE__*/ new Vector3();
  28782. const _camera = /*@__PURE__*/ new Camera();
  28783. /**
  28784. * - shows frustum, line of sight and up of the camera
  28785. * - suitable for fast updates
  28786. * - based on frustum visualization in lightgl.js shadowmap example
  28787. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  28788. */
  28789. class CameraHelper extends LineSegments {
  28790. constructor( camera ) {
  28791. const geometry = new BufferGeometry();
  28792. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  28793. const vertices = [];
  28794. const colors = [];
  28795. const pointMap = {};
  28796. // near
  28797. addLine( 'n1', 'n2' );
  28798. addLine( 'n2', 'n4' );
  28799. addLine( 'n4', 'n3' );
  28800. addLine( 'n3', 'n1' );
  28801. // far
  28802. addLine( 'f1', 'f2' );
  28803. addLine( 'f2', 'f4' );
  28804. addLine( 'f4', 'f3' );
  28805. addLine( 'f3', 'f1' );
  28806. // sides
  28807. addLine( 'n1', 'f1' );
  28808. addLine( 'n2', 'f2' );
  28809. addLine( 'n3', 'f3' );
  28810. addLine( 'n4', 'f4' );
  28811. // cone
  28812. addLine( 'p', 'n1' );
  28813. addLine( 'p', 'n2' );
  28814. addLine( 'p', 'n3' );
  28815. addLine( 'p', 'n4' );
  28816. // up
  28817. addLine( 'u1', 'u2' );
  28818. addLine( 'u2', 'u3' );
  28819. addLine( 'u3', 'u1' );
  28820. // target
  28821. addLine( 'c', 't' );
  28822. addLine( 'p', 'c' );
  28823. // cross
  28824. addLine( 'cn1', 'cn2' );
  28825. addLine( 'cn3', 'cn4' );
  28826. addLine( 'cf1', 'cf2' );
  28827. addLine( 'cf3', 'cf4' );
  28828. function addLine( a, b ) {
  28829. addPoint( a );
  28830. addPoint( b );
  28831. }
  28832. function addPoint( id ) {
  28833. vertices.push( 0, 0, 0 );
  28834. colors.push( 0, 0, 0 );
  28835. if ( pointMap[ id ] === undefined ) {
  28836. pointMap[ id ] = [];
  28837. }
  28838. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  28839. }
  28840. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28841. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28842. super( geometry, material );
  28843. this.type = 'CameraHelper';
  28844. this.camera = camera;
  28845. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  28846. this.matrix = camera.matrixWorld;
  28847. this.matrixAutoUpdate = false;
  28848. this.pointMap = pointMap;
  28849. this.update();
  28850. // colors
  28851. const colorFrustum = new Color( 0xffaa00 );
  28852. const colorCone = new Color( 0xff0000 );
  28853. const colorUp = new Color( 0x00aaff );
  28854. const colorTarget = new Color( 0xffffff );
  28855. const colorCross = new Color( 0x333333 );
  28856. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  28857. }
  28858. setColors( frustum, cone, up, target, cross ) {
  28859. const geometry = this.geometry;
  28860. const colorAttribute = geometry.getAttribute( 'color' );
  28861. // near
  28862. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  28863. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  28864. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  28865. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  28866. // far
  28867. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  28868. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  28869. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  28870. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  28871. // sides
  28872. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  28873. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  28874. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  28875. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  28876. // cone
  28877. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  28878. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  28879. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  28880. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  28881. // up
  28882. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  28883. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  28884. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  28885. // target
  28886. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  28887. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  28888. // cross
  28889. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  28890. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  28891. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  28892. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  28893. colorAttribute.needsUpdate = true;
  28894. }
  28895. update() {
  28896. const geometry = this.geometry;
  28897. const pointMap = this.pointMap;
  28898. const w = 1, h = 1;
  28899. // we need just camera projection matrix inverse
  28900. // world matrix must be identity
  28901. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  28902. // center / target
  28903. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  28904. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  28905. // near
  28906. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  28907. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  28908. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  28909. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  28910. // far
  28911. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  28912. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  28913. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  28914. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  28915. // up
  28916. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  28917. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  28918. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  28919. // cross
  28920. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  28921. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  28922. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  28923. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  28924. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  28925. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  28926. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  28927. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  28928. geometry.getAttribute( 'position' ).needsUpdate = true;
  28929. }
  28930. dispose() {
  28931. this.geometry.dispose();
  28932. this.material.dispose();
  28933. }
  28934. }
  28935. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  28936. _vector.set( x, y, z ).unproject( camera );
  28937. const points = pointMap[ point ];
  28938. if ( points !== undefined ) {
  28939. const position = geometry.getAttribute( 'position' );
  28940. for ( let i = 0, l = points.length; i < l; i ++ ) {
  28941. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  28942. }
  28943. }
  28944. }
  28945. const _box = /*@__PURE__*/ new Box3();
  28946. class BoxHelper extends LineSegments {
  28947. constructor( object, color = 0xffff00 ) {
  28948. 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 ] );
  28949. const positions = new Float32Array( 8 * 3 );
  28950. const geometry = new BufferGeometry();
  28951. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  28952. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  28953. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28954. this.object = object;
  28955. this.type = 'BoxHelper';
  28956. this.matrixAutoUpdate = false;
  28957. this.update();
  28958. }
  28959. update( object ) {
  28960. if ( object !== undefined ) {
  28961. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  28962. }
  28963. if ( this.object !== undefined ) {
  28964. _box.setFromObject( this.object );
  28965. }
  28966. if ( _box.isEmpty() ) return;
  28967. const min = _box.min;
  28968. const max = _box.max;
  28969. /*
  28970. 5____4
  28971. 1/___0/|
  28972. | 6__|_7
  28973. 2/___3/
  28974. 0: max.x, max.y, max.z
  28975. 1: min.x, max.y, max.z
  28976. 2: min.x, min.y, max.z
  28977. 3: max.x, min.y, max.z
  28978. 4: max.x, max.y, min.z
  28979. 5: min.x, max.y, min.z
  28980. 6: min.x, min.y, min.z
  28981. 7: max.x, min.y, min.z
  28982. */
  28983. const position = this.geometry.attributes.position;
  28984. const array = position.array;
  28985. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  28986. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  28987. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  28988. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  28989. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  28990. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  28991. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  28992. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  28993. position.needsUpdate = true;
  28994. this.geometry.computeBoundingSphere();
  28995. }
  28996. setFromObject( object ) {
  28997. this.object = object;
  28998. this.update();
  28999. return this;
  29000. }
  29001. copy( source, recursive ) {
  29002. super.copy( source, recursive );
  29003. this.object = source.object;
  29004. return this;
  29005. }
  29006. dispose() {
  29007. this.geometry.dispose();
  29008. this.material.dispose();
  29009. }
  29010. }
  29011. class Box3Helper extends LineSegments {
  29012. constructor( box, color = 0xffff00 ) {
  29013. 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 ] );
  29014. 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 ];
  29015. const geometry = new BufferGeometry();
  29016. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29017. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29018. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29019. this.box = box;
  29020. this.type = 'Box3Helper';
  29021. this.geometry.computeBoundingSphere();
  29022. }
  29023. updateMatrixWorld( force ) {
  29024. const box = this.box;
  29025. if ( box.isEmpty() ) return;
  29026. box.getCenter( this.position );
  29027. box.getSize( this.scale );
  29028. this.scale.multiplyScalar( 0.5 );
  29029. super.updateMatrixWorld( force );
  29030. }
  29031. dispose() {
  29032. this.geometry.dispose();
  29033. this.material.dispose();
  29034. }
  29035. }
  29036. class PlaneHelper extends Line {
  29037. constructor( plane, size = 1, hex = 0xffff00 ) {
  29038. const color = hex;
  29039. 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 ];
  29040. const geometry = new BufferGeometry();
  29041. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29042. geometry.computeBoundingSphere();
  29043. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29044. this.type = 'PlaneHelper';
  29045. this.plane = plane;
  29046. this.size = size;
  29047. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  29048. const geometry2 = new BufferGeometry();
  29049. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  29050. geometry2.computeBoundingSphere();
  29051. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  29052. }
  29053. updateMatrixWorld( force ) {
  29054. this.position.set( 0, 0, 0 );
  29055. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  29056. this.lookAt( this.plane.normal );
  29057. this.translateZ( - this.plane.constant );
  29058. super.updateMatrixWorld( force );
  29059. }
  29060. dispose() {
  29061. this.geometry.dispose();
  29062. this.material.dispose();
  29063. this.children[ 0 ].geometry.dispose();
  29064. this.children[ 0 ].material.dispose();
  29065. }
  29066. }
  29067. const _axis = /*@__PURE__*/ new Vector3();
  29068. let _lineGeometry, _coneGeometry;
  29069. class ArrowHelper extends Object3D {
  29070. // dir is assumed to be normalized
  29071. 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 ) {
  29072. super();
  29073. this.type = 'ArrowHelper';
  29074. if ( _lineGeometry === undefined ) {
  29075. _lineGeometry = new BufferGeometry();
  29076. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  29077. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  29078. _coneGeometry.translate( 0, - 0.5, 0 );
  29079. }
  29080. this.position.copy( origin );
  29081. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29082. this.line.matrixAutoUpdate = false;
  29083. this.add( this.line );
  29084. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  29085. this.cone.matrixAutoUpdate = false;
  29086. this.add( this.cone );
  29087. this.setDirection( dir );
  29088. this.setLength( length, headLength, headWidth );
  29089. }
  29090. setDirection( dir ) {
  29091. // dir is assumed to be normalized
  29092. if ( dir.y > 0.99999 ) {
  29093. this.quaternion.set( 0, 0, 0, 1 );
  29094. } else if ( dir.y < - 0.99999 ) {
  29095. this.quaternion.set( 1, 0, 0, 0 );
  29096. } else {
  29097. _axis.set( dir.z, 0, - dir.x ).normalize();
  29098. const radians = Math.acos( dir.y );
  29099. this.quaternion.setFromAxisAngle( _axis, radians );
  29100. }
  29101. }
  29102. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  29103. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  29104. this.line.updateMatrix();
  29105. this.cone.scale.set( headWidth, headLength, headWidth );
  29106. this.cone.position.y = length;
  29107. this.cone.updateMatrix();
  29108. }
  29109. setColor( color ) {
  29110. this.line.material.color.set( color );
  29111. this.cone.material.color.set( color );
  29112. }
  29113. copy( source ) {
  29114. super.copy( source, false );
  29115. this.line.copy( source.line );
  29116. this.cone.copy( source.cone );
  29117. return this;
  29118. }
  29119. dispose() {
  29120. this.line.geometry.dispose();
  29121. this.line.material.dispose();
  29122. this.cone.geometry.dispose();
  29123. this.cone.material.dispose();
  29124. }
  29125. }
  29126. class AxesHelper extends LineSegments {
  29127. constructor( size = 1 ) {
  29128. const vertices = [
  29129. 0, 0, 0, size, 0, 0,
  29130. 0, 0, 0, 0, size, 0,
  29131. 0, 0, 0, 0, 0, size
  29132. ];
  29133. const colors = [
  29134. 1, 0, 0, 1, 0.6, 0,
  29135. 0, 1, 0, 0.6, 1, 0,
  29136. 0, 0, 1, 0, 0.6, 1
  29137. ];
  29138. const geometry = new BufferGeometry();
  29139. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29140. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29141. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29142. super( geometry, material );
  29143. this.type = 'AxesHelper';
  29144. }
  29145. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  29146. const color = new Color();
  29147. const array = this.geometry.attributes.color.array;
  29148. color.set( xAxisColor );
  29149. color.toArray( array, 0 );
  29150. color.toArray( array, 3 );
  29151. color.set( yAxisColor );
  29152. color.toArray( array, 6 );
  29153. color.toArray( array, 9 );
  29154. color.set( zAxisColor );
  29155. color.toArray( array, 12 );
  29156. color.toArray( array, 15 );
  29157. this.geometry.attributes.color.needsUpdate = true;
  29158. return this;
  29159. }
  29160. dispose() {
  29161. this.geometry.dispose();
  29162. this.material.dispose();
  29163. }
  29164. }
  29165. class ShapePath {
  29166. constructor() {
  29167. this.type = 'ShapePath';
  29168. this.color = new Color();
  29169. this.subPaths = [];
  29170. this.currentPath = null;
  29171. }
  29172. moveTo( x, y ) {
  29173. this.currentPath = new Path();
  29174. this.subPaths.push( this.currentPath );
  29175. this.currentPath.moveTo( x, y );
  29176. return this;
  29177. }
  29178. lineTo( x, y ) {
  29179. this.currentPath.lineTo( x, y );
  29180. return this;
  29181. }
  29182. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  29183. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  29184. return this;
  29185. }
  29186. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  29187. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  29188. return this;
  29189. }
  29190. splineThru( pts ) {
  29191. this.currentPath.splineThru( pts );
  29192. return this;
  29193. }
  29194. toShapes( isCCW ) {
  29195. function toShapesNoHoles( inSubpaths ) {
  29196. const shapes = [];
  29197. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  29198. const tmpPath = inSubpaths[ i ];
  29199. const tmpShape = new Shape();
  29200. tmpShape.curves = tmpPath.curves;
  29201. shapes.push( tmpShape );
  29202. }
  29203. return shapes;
  29204. }
  29205. function isPointInsidePolygon( inPt, inPolygon ) {
  29206. const polyLen = inPolygon.length;
  29207. // inPt on polygon contour => immediate success or
  29208. // toggling of inside/outside at every single! intersection point of an edge
  29209. // with the horizontal line through inPt, left of inPt
  29210. // not counting lowerY endpoints of edges and whole edges on that line
  29211. let inside = false;
  29212. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  29213. let edgeLowPt = inPolygon[ p ];
  29214. let edgeHighPt = inPolygon[ q ];
  29215. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  29216. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  29217. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  29218. // not parallel
  29219. if ( edgeDy < 0 ) {
  29220. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  29221. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  29222. }
  29223. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  29224. if ( inPt.y === edgeLowPt.y ) {
  29225. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  29226. // continue; // no intersection or edgeLowPt => doesn't count !!!
  29227. } else {
  29228. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  29229. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  29230. if ( perpEdge < 0 ) continue;
  29231. inside = ! inside; // true intersection left of inPt
  29232. }
  29233. } else {
  29234. // parallel or collinear
  29235. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  29236. // edge lies on the same horizontal line as inPt
  29237. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  29238. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  29239. // continue;
  29240. }
  29241. }
  29242. return inside;
  29243. }
  29244. const isClockWise = ShapeUtils.isClockWise;
  29245. const subPaths = this.subPaths;
  29246. if ( subPaths.length === 0 ) return [];
  29247. let solid, tmpPath, tmpShape;
  29248. const shapes = [];
  29249. if ( subPaths.length === 1 ) {
  29250. tmpPath = subPaths[ 0 ];
  29251. tmpShape = new Shape();
  29252. tmpShape.curves = tmpPath.curves;
  29253. shapes.push( tmpShape );
  29254. return shapes;
  29255. }
  29256. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  29257. holesFirst = isCCW ? ! holesFirst : holesFirst;
  29258. // console.log("Holes first", holesFirst);
  29259. const betterShapeHoles = [];
  29260. const newShapes = [];
  29261. let newShapeHoles = [];
  29262. let mainIdx = 0;
  29263. let tmpPoints;
  29264. newShapes[ mainIdx ] = undefined;
  29265. newShapeHoles[ mainIdx ] = [];
  29266. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  29267. tmpPath = subPaths[ i ];
  29268. tmpPoints = tmpPath.getPoints();
  29269. solid = isClockWise( tmpPoints );
  29270. solid = isCCW ? ! solid : solid;
  29271. if ( solid ) {
  29272. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  29273. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  29274. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  29275. if ( holesFirst ) mainIdx ++;
  29276. newShapeHoles[ mainIdx ] = [];
  29277. //console.log('cw', i);
  29278. } else {
  29279. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  29280. //console.log('ccw', i);
  29281. }
  29282. }
  29283. // only Holes? -> probably all Shapes with wrong orientation
  29284. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  29285. if ( newShapes.length > 1 ) {
  29286. let ambiguous = false;
  29287. let toChange = 0;
  29288. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29289. betterShapeHoles[ sIdx ] = [];
  29290. }
  29291. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29292. const sho = newShapeHoles[ sIdx ];
  29293. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  29294. const ho = sho[ hIdx ];
  29295. let hole_unassigned = true;
  29296. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  29297. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  29298. if ( sIdx !== s2Idx ) toChange ++;
  29299. if ( hole_unassigned ) {
  29300. hole_unassigned = false;
  29301. betterShapeHoles[ s2Idx ].push( ho );
  29302. } else {
  29303. ambiguous = true;
  29304. }
  29305. }
  29306. }
  29307. if ( hole_unassigned ) {
  29308. betterShapeHoles[ sIdx ].push( ho );
  29309. }
  29310. }
  29311. }
  29312. if ( toChange > 0 && ambiguous === false ) {
  29313. newShapeHoles = betterShapeHoles;
  29314. }
  29315. }
  29316. let tmpHoles;
  29317. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  29318. tmpShape = newShapes[ i ].s;
  29319. shapes.push( tmpShape );
  29320. tmpHoles = newShapeHoles[ i ];
  29321. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  29322. tmpShape.holes.push( tmpHoles[ j ].h );
  29323. }
  29324. }
  29325. //console.log("shape", shapes);
  29326. return shapes;
  29327. }
  29328. }
  29329. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  29330. const _tables = /*@__PURE__*/ _generateTables();
  29331. function _generateTables() {
  29332. // float32 to float16 helpers
  29333. const buffer = new ArrayBuffer( 4 );
  29334. const floatView = new Float32Array( buffer );
  29335. const uint32View = new Uint32Array( buffer );
  29336. const baseTable = new Uint32Array( 512 );
  29337. const shiftTable = new Uint32Array( 512 );
  29338. for ( let i = 0; i < 256; ++ i ) {
  29339. const e = i - 127;
  29340. // very small number (0, -0)
  29341. if ( e < - 27 ) {
  29342. baseTable[ i ] = 0x0000;
  29343. baseTable[ i | 0x100 ] = 0x8000;
  29344. shiftTable[ i ] = 24;
  29345. shiftTable[ i | 0x100 ] = 24;
  29346. // small number (denorm)
  29347. } else if ( e < - 14 ) {
  29348. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  29349. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  29350. shiftTable[ i ] = - e - 1;
  29351. shiftTable[ i | 0x100 ] = - e - 1;
  29352. // normal number
  29353. } else if ( e <= 15 ) {
  29354. baseTable[ i ] = ( e + 15 ) << 10;
  29355. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  29356. shiftTable[ i ] = 13;
  29357. shiftTable[ i | 0x100 ] = 13;
  29358. // large number (Infinity, -Infinity)
  29359. } else if ( e < 128 ) {
  29360. baseTable[ i ] = 0x7c00;
  29361. baseTable[ i | 0x100 ] = 0xfc00;
  29362. shiftTable[ i ] = 24;
  29363. shiftTable[ i | 0x100 ] = 24;
  29364. // stay (NaN, Infinity, -Infinity)
  29365. } else {
  29366. baseTable[ i ] = 0x7c00;
  29367. baseTable[ i | 0x100 ] = 0xfc00;
  29368. shiftTable[ i ] = 13;
  29369. shiftTable[ i | 0x100 ] = 13;
  29370. }
  29371. }
  29372. // float16 to float32 helpers
  29373. const mantissaTable = new Uint32Array( 2048 );
  29374. const exponentTable = new Uint32Array( 64 );
  29375. const offsetTable = new Uint32Array( 64 );
  29376. for ( let i = 1; i < 1024; ++ i ) {
  29377. let m = i << 13; // zero pad mantissa bits
  29378. let e = 0; // zero exponent
  29379. // normalized
  29380. while ( ( m & 0x00800000 ) === 0 ) {
  29381. m <<= 1;
  29382. e -= 0x00800000; // decrement exponent
  29383. }
  29384. m &= ~ 0x00800000; // clear leading 1 bit
  29385. e += 0x38800000; // adjust bias
  29386. mantissaTable[ i ] = m | e;
  29387. }
  29388. for ( let i = 1024; i < 2048; ++ i ) {
  29389. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  29390. }
  29391. for ( let i = 1; i < 31; ++ i ) {
  29392. exponentTable[ i ] = i << 23;
  29393. }
  29394. exponentTable[ 31 ] = 0x47800000;
  29395. exponentTable[ 32 ] = 0x80000000;
  29396. for ( let i = 33; i < 63; ++ i ) {
  29397. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  29398. }
  29399. exponentTable[ 63 ] = 0xc7800000;
  29400. for ( let i = 1; i < 64; ++ i ) {
  29401. if ( i !== 32 ) {
  29402. offsetTable[ i ] = 1024;
  29403. }
  29404. }
  29405. return {
  29406. floatView: floatView,
  29407. uint32View: uint32View,
  29408. baseTable: baseTable,
  29409. shiftTable: shiftTable,
  29410. mantissaTable: mantissaTable,
  29411. exponentTable: exponentTable,
  29412. offsetTable: offsetTable
  29413. };
  29414. }
  29415. // float32 to float16
  29416. function toHalfFloat( val ) {
  29417. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  29418. val = clamp( val, - 65504, 65504 );
  29419. _tables.floatView[ 0 ] = val;
  29420. const f = _tables.uint32View[ 0 ];
  29421. const e = ( f >> 23 ) & 0x1ff;
  29422. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  29423. }
  29424. // float16 to float32
  29425. function fromHalfFloat( val ) {
  29426. const m = val >> 10;
  29427. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  29428. return _tables.floatView[ 0 ];
  29429. }
  29430. var DataUtils = /*#__PURE__*/Object.freeze({
  29431. __proto__: null,
  29432. fromHalfFloat: fromHalfFloat,
  29433. toHalfFloat: toHalfFloat
  29434. });
  29435. // r144
  29436. class BoxBufferGeometry extends BoxGeometry {
  29437. constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  29438. console.warn( 'THREE.BoxBufferGeometry has been renamed to THREE.BoxGeometry.' );
  29439. super( width, height, depth, widthSegments, heightSegments, depthSegments );
  29440. }
  29441. }
  29442. // r144
  29443. class CapsuleBufferGeometry extends CapsuleGeometry {
  29444. constructor( radius, length, capSegments, radialSegments ) {
  29445. console.warn( 'THREE.CapsuleBufferGeometry has been renamed to THREE.CapsuleGeometry.' );
  29446. super( radius, length, capSegments, radialSegments );
  29447. }
  29448. }
  29449. // r144
  29450. class CircleBufferGeometry extends CircleGeometry {
  29451. constructor( radius, segments, thetaStart, thetaLength ) {
  29452. console.warn( 'THREE.CircleBufferGeometry has been renamed to THREE.CircleGeometry.' );
  29453. super( radius, segments, thetaStart, thetaLength );
  29454. }
  29455. }
  29456. // r144
  29457. class ConeBufferGeometry extends ConeGeometry {
  29458. constructor( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  29459. console.warn( 'THREE.ConeBufferGeometry has been renamed to THREE.ConeGeometry.' );
  29460. super( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  29461. }
  29462. }
  29463. // r144
  29464. class CylinderBufferGeometry extends CylinderGeometry {
  29465. constructor( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  29466. console.warn( 'THREE.CylinderBufferGeometry has been renamed to THREE.CylinderGeometry.' );
  29467. super( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  29468. }
  29469. }
  29470. // r144
  29471. class DodecahedronBufferGeometry extends DodecahedronGeometry {
  29472. constructor( radius, detail ) {
  29473. console.warn( 'THREE.DodecahedronBufferGeometry has been renamed to THREE.DodecahedronGeometry.' );
  29474. super( radius, detail );
  29475. }
  29476. }
  29477. // r144
  29478. class ExtrudeBufferGeometry extends ExtrudeGeometry {
  29479. constructor( shapes, options ) {
  29480. console.warn( 'THREE.ExtrudeBufferGeometry has been renamed to THREE.ExtrudeGeometry.' );
  29481. super( shapes, options );
  29482. }
  29483. }
  29484. // r144
  29485. class IcosahedronBufferGeometry extends IcosahedronGeometry {
  29486. constructor( radius, detail ) {
  29487. console.warn( 'THREE.IcosahedronBufferGeometry has been renamed to THREE.IcosahedronGeometry.' );
  29488. super( radius, detail );
  29489. }
  29490. }
  29491. // r144
  29492. class LatheBufferGeometry extends LatheGeometry {
  29493. constructor( points, segments, phiStart, phiLength ) {
  29494. console.warn( 'THREE.LatheBufferGeometry has been renamed to THREE.LatheGeometry.' );
  29495. super( points, segments, phiStart, phiLength );
  29496. }
  29497. }
  29498. // r144
  29499. class OctahedronBufferGeometry extends OctahedronGeometry {
  29500. constructor( radius, detail ) {
  29501. console.warn( 'THREE.OctahedronBufferGeometry has been renamed to THREE.OctahedronGeometry.' );
  29502. super( radius, detail );
  29503. }
  29504. }
  29505. // r144
  29506. class PlaneBufferGeometry extends PlaneGeometry {
  29507. constructor( width, height, widthSegments, heightSegments ) {
  29508. console.warn( 'THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry.' );
  29509. super( width, height, widthSegments, heightSegments );
  29510. }
  29511. }
  29512. // r144
  29513. class PolyhedronBufferGeometry extends PolyhedronGeometry {
  29514. constructor( vertices, indices, radius, detail ) {
  29515. console.warn( 'THREE.PolyhedronBufferGeometry has been renamed to THREE.PolyhedronGeometry.' );
  29516. super( vertices, indices, radius, detail );
  29517. }
  29518. }
  29519. // r144
  29520. class RingBufferGeometry extends RingGeometry {
  29521. constructor( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  29522. console.warn( 'THREE.RingBufferGeometry has been renamed to THREE.RingGeometry.' );
  29523. super( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength );
  29524. }
  29525. }
  29526. // r144
  29527. class ShapeBufferGeometry extends ShapeGeometry {
  29528. constructor( shapes, curveSegments ) {
  29529. console.warn( 'THREE.ShapeBufferGeometry has been renamed to THREE.ShapeGeometry.' );
  29530. super( shapes, curveSegments );
  29531. }
  29532. }
  29533. // r144
  29534. class SphereBufferGeometry extends SphereGeometry {
  29535. constructor( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  29536. console.warn( 'THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry.' );
  29537. super( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength );
  29538. }
  29539. }
  29540. // r144
  29541. class TetrahedronBufferGeometry extends TetrahedronGeometry {
  29542. constructor( radius, detail ) {
  29543. console.warn( 'THREE.TetrahedronBufferGeometry has been renamed to THREE.TetrahedronGeometry.' );
  29544. super( radius, detail );
  29545. }
  29546. }
  29547. // r144
  29548. class TorusBufferGeometry extends TorusGeometry {
  29549. constructor( radius, tube, radialSegments, tubularSegments, arc ) {
  29550. console.warn( 'THREE.TorusBufferGeometry has been renamed to THREE.TorusGeometry.' );
  29551. super( radius, tube, radialSegments, tubularSegments, arc );
  29552. }
  29553. }
  29554. // r144
  29555. class TorusKnotBufferGeometry extends TorusKnotGeometry {
  29556. constructor( radius, tube, tubularSegments, radialSegments, p, q ) {
  29557. console.warn( 'THREE.TorusKnotBufferGeometry has been renamed to THREE.TorusKnotGeometry.' );
  29558. super( radius, tube, tubularSegments, radialSegments, p, q );
  29559. }
  29560. }
  29561. // r144
  29562. class TubeBufferGeometry extends TubeGeometry {
  29563. constructor( path, tubularSegments, radius, radialSegments, closed ) {
  29564. console.warn( 'THREE.TubeBufferGeometry has been renamed to THREE.TubeGeometry.' );
  29565. super( path, tubularSegments, radius, radialSegments, closed );
  29566. }
  29567. }
  29568. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  29569. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  29570. revision: REVISION,
  29571. } } ) );
  29572. }
  29573. if ( typeof window !== 'undefined' ) {
  29574. if ( window.__THREE__ ) {
  29575. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  29576. } else {
  29577. window.__THREE__ = REVISION;
  29578. }
  29579. }
  29580. export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AlphaFormat, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightProbe, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BackSide, BasicDepthPacking, BasicShadowMap, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxBufferGeometry, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasTexture, CapsuleBufferGeometry, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleBufferGeometry, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, ColorManagement, CompressedArrayTexture, CompressedTexture, CompressedTextureLoader, ConeBufferGeometry, ConeGeometry, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderBufferGeometry, CylinderGeometry, Cylindrical, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DodecahedronBufferGeometry, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeBufferGeometry, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Float32BufferAttribute, Float64BufferAttribute, FloatType, Fog, FogExp2, FramebufferTexture, FrontSide, Frustum, GLBufferAttribute, GLSL1, GLSL3, GreaterDepth, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightProbe, IcosahedronBufferGeometry, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, KeepStencilOp, KeyframeTrack, LOD, LatheBufferGeometry, LatheGeometry, Layers, LessDepth, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LineSegments, LinearEncoding, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, Loader, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, Material, MaterialLoader, MathUtils, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronBufferGeometry, OctahedronGeometry, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, PMREMGenerator, Path, PerspectiveCamera, Plane, PlaneBufferGeometry, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronBufferGeometry, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingBufferGeometry, RingGeometry, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, Scene, ShaderChunk, ShaderLib, ShaderMaterial, ShadowMaterial, Shape, ShapeBufferGeometry, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, SphereBufferGeometry, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronBufferGeometry, TetrahedronGeometry, Texture, TextureLoader, TorusBufferGeometry, TorusGeometry, TorusKnotBufferGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeBufferGeometry, TubeGeometry, TwoPassDoubleSide, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, UniformsLib, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, VideoTexture, WebGL1Renderer, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLRenderTarget, WebGLRenderer, WebGLUtils, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, _SRGBAFormat, sRGBEncoding };