three.module.js 1.2 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250
  1. /**
  2. * @license
  3. * Copyright 2010-2023 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '154';
  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. /** @deprecated Use LinearSRGBColorSpace or NoColorSpace in three.js r152+. */
  146. const LinearEncoding = 3000;
  147. /** @deprecated Use SRGBColorSpace in three.js r152+. */
  148. const sRGBEncoding = 3001;
  149. const BasicDepthPacking = 3200;
  150. const RGBADepthPacking = 3201;
  151. const TangentSpaceNormalMap = 0;
  152. const ObjectSpaceNormalMap = 1;
  153. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  154. const NoColorSpace = '';
  155. const SRGBColorSpace = 'srgb';
  156. const LinearSRGBColorSpace = 'srgb-linear';
  157. const DisplayP3ColorSpace = 'display-p3';
  158. const ZeroStencilOp = 0;
  159. const KeepStencilOp = 7680;
  160. const ReplaceStencilOp = 7681;
  161. const IncrementStencilOp = 7682;
  162. const DecrementStencilOp = 7683;
  163. const IncrementWrapStencilOp = 34055;
  164. const DecrementWrapStencilOp = 34056;
  165. const InvertStencilOp = 5386;
  166. const NeverStencilFunc = 512;
  167. const LessStencilFunc = 513;
  168. const EqualStencilFunc = 514;
  169. const LessEqualStencilFunc = 515;
  170. const GreaterStencilFunc = 516;
  171. const NotEqualStencilFunc = 517;
  172. const GreaterEqualStencilFunc = 518;
  173. const AlwaysStencilFunc = 519;
  174. const NeverCompare = 512;
  175. const LessCompare = 513;
  176. const EqualCompare = 514;
  177. const LessEqualCompare = 515;
  178. const GreaterCompare = 516;
  179. const NotEqualCompare = 517;
  180. const GreaterEqualCompare = 518;
  181. const AlwaysCompare = 519;
  182. const StaticDrawUsage = 35044;
  183. const DynamicDrawUsage = 35048;
  184. const StreamDrawUsage = 35040;
  185. const StaticReadUsage = 35045;
  186. const DynamicReadUsage = 35049;
  187. const StreamReadUsage = 35041;
  188. const StaticCopyUsage = 35046;
  189. const DynamicCopyUsage = 35050;
  190. const StreamCopyUsage = 35042;
  191. const GLSL1 = '100';
  192. const GLSL3 = '300 es';
  193. const _SRGBAFormat = 1035; // fallback for WebGL 1
  194. const WebGLCoordinateSystem = 2000;
  195. const WebGPUCoordinateSystem = 2001;
  196. /**
  197. * https://github.com/mrdoob/eventdispatcher.js/
  198. */
  199. class EventDispatcher {
  200. addEventListener( type, listener ) {
  201. if ( this._listeners === undefined ) this._listeners = {};
  202. const listeners = this._listeners;
  203. if ( listeners[ type ] === undefined ) {
  204. listeners[ type ] = [];
  205. }
  206. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  207. listeners[ type ].push( listener );
  208. }
  209. }
  210. hasEventListener( type, listener ) {
  211. if ( this._listeners === undefined ) return false;
  212. const listeners = this._listeners;
  213. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  214. }
  215. removeEventListener( type, listener ) {
  216. if ( this._listeners === undefined ) return;
  217. const listeners = this._listeners;
  218. const listenerArray = listeners[ type ];
  219. if ( listenerArray !== undefined ) {
  220. const index = listenerArray.indexOf( listener );
  221. if ( index !== - 1 ) {
  222. listenerArray.splice( index, 1 );
  223. }
  224. }
  225. }
  226. dispatchEvent( event ) {
  227. if ( this._listeners === undefined ) return;
  228. const listeners = this._listeners;
  229. const listenerArray = listeners[ event.type ];
  230. if ( listenerArray !== undefined ) {
  231. event.target = this;
  232. // Make a copy, in case listeners are removed while iterating.
  233. const array = listenerArray.slice( 0 );
  234. for ( let i = 0, l = array.length; i < l; i ++ ) {
  235. array[ i ].call( this, event );
  236. }
  237. event.target = null;
  238. }
  239. }
  240. }
  241. 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' ];
  242. let _seed = 1234567;
  243. const DEG2RAD = Math.PI / 180;
  244. const RAD2DEG = 180 / Math.PI;
  245. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  246. function generateUUID() {
  247. const d0 = Math.random() * 0xffffffff | 0;
  248. const d1 = Math.random() * 0xffffffff | 0;
  249. const d2 = Math.random() * 0xffffffff | 0;
  250. const d3 = Math.random() * 0xffffffff | 0;
  251. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  252. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  253. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  254. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  255. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  256. return uuid.toLowerCase();
  257. }
  258. function clamp( value, min, max ) {
  259. return Math.max( min, Math.min( max, value ) );
  260. }
  261. // compute euclidean modulo of m % n
  262. // https://en.wikipedia.org/wiki/Modulo_operation
  263. function euclideanModulo( n, m ) {
  264. return ( ( n % m ) + m ) % m;
  265. }
  266. // Linear mapping from range <a1, a2> to range <b1, b2>
  267. function mapLinear( x, a1, a2, b1, b2 ) {
  268. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  269. }
  270. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  271. function inverseLerp( x, y, value ) {
  272. if ( x !== y ) {
  273. return ( value - x ) / ( y - x );
  274. } else {
  275. return 0;
  276. }
  277. }
  278. // https://en.wikipedia.org/wiki/Linear_interpolation
  279. function lerp( x, y, t ) {
  280. return ( 1 - t ) * x + t * y;
  281. }
  282. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  283. function damp( x, y, lambda, dt ) {
  284. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  285. }
  286. // https://www.desmos.com/calculator/vcsjnyz7x4
  287. function pingpong( x, length = 1 ) {
  288. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  289. }
  290. // http://en.wikipedia.org/wiki/Smoothstep
  291. function smoothstep( x, min, max ) {
  292. if ( x <= min ) return 0;
  293. if ( x >= max ) return 1;
  294. x = ( x - min ) / ( max - min );
  295. return x * x * ( 3 - 2 * x );
  296. }
  297. function smootherstep( x, min, max ) {
  298. if ( x <= min ) return 0;
  299. if ( x >= max ) return 1;
  300. x = ( x - min ) / ( max - min );
  301. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  302. }
  303. // Random integer from <low, high> interval
  304. function randInt( low, high ) {
  305. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  306. }
  307. // Random float from <low, high> interval
  308. function randFloat( low, high ) {
  309. return low + Math.random() * ( high - low );
  310. }
  311. // Random float from <-range/2, range/2> interval
  312. function randFloatSpread( range ) {
  313. return range * ( 0.5 - Math.random() );
  314. }
  315. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  316. function seededRandom( s ) {
  317. if ( s !== undefined ) _seed = s;
  318. // Mulberry32 generator
  319. let t = _seed += 0x6D2B79F5;
  320. t = Math.imul( t ^ t >>> 15, t | 1 );
  321. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  322. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  323. }
  324. function degToRad( degrees ) {
  325. return degrees * DEG2RAD;
  326. }
  327. function radToDeg( radians ) {
  328. return radians * RAD2DEG;
  329. }
  330. function isPowerOfTwo( value ) {
  331. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  332. }
  333. function ceilPowerOfTwo( value ) {
  334. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  335. }
  336. function floorPowerOfTwo( value ) {
  337. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  338. }
  339. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  340. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  341. // rotations are applied to the axes in the order specified by 'order'
  342. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  343. // angles are in radians
  344. const cos = Math.cos;
  345. const sin = Math.sin;
  346. const c2 = cos( b / 2 );
  347. const s2 = sin( b / 2 );
  348. const c13 = cos( ( a + c ) / 2 );
  349. const s13 = sin( ( a + c ) / 2 );
  350. const c1_3 = cos( ( a - c ) / 2 );
  351. const s1_3 = sin( ( a - c ) / 2 );
  352. const c3_1 = cos( ( c - a ) / 2 );
  353. const s3_1 = sin( ( c - a ) / 2 );
  354. switch ( order ) {
  355. case 'XYX':
  356. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  357. break;
  358. case 'YZY':
  359. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  360. break;
  361. case 'ZXZ':
  362. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  363. break;
  364. case 'XZX':
  365. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  366. break;
  367. case 'YXY':
  368. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  369. break;
  370. case 'ZYZ':
  371. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  372. break;
  373. default:
  374. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  375. }
  376. }
  377. function denormalize( value, array ) {
  378. switch ( array.constructor ) {
  379. case Float32Array:
  380. return value;
  381. case Uint32Array:
  382. return value / 4294967295.0;
  383. case Uint16Array:
  384. return value / 65535.0;
  385. case Uint8Array:
  386. return value / 255.0;
  387. case Int32Array:
  388. return Math.max( value / 2147483647.0, - 1.0 );
  389. case Int16Array:
  390. return Math.max( value / 32767.0, - 1.0 );
  391. case Int8Array:
  392. return Math.max( value / 127.0, - 1.0 );
  393. default:
  394. throw new Error( 'Invalid component type.' );
  395. }
  396. }
  397. function normalize( value, array ) {
  398. switch ( array.constructor ) {
  399. case Float32Array:
  400. return value;
  401. case Uint32Array:
  402. return Math.round( value * 4294967295.0 );
  403. case Uint16Array:
  404. return Math.round( value * 65535.0 );
  405. case Uint8Array:
  406. return Math.round( value * 255.0 );
  407. case Int32Array:
  408. return Math.round( value * 2147483647.0 );
  409. case Int16Array:
  410. return Math.round( value * 32767.0 );
  411. case Int8Array:
  412. return Math.round( value * 127.0 );
  413. default:
  414. throw new Error( 'Invalid component type.' );
  415. }
  416. }
  417. const MathUtils = {
  418. DEG2RAD: DEG2RAD,
  419. RAD2DEG: RAD2DEG,
  420. generateUUID: generateUUID,
  421. clamp: clamp,
  422. euclideanModulo: euclideanModulo,
  423. mapLinear: mapLinear,
  424. inverseLerp: inverseLerp,
  425. lerp: lerp,
  426. damp: damp,
  427. pingpong: pingpong,
  428. smoothstep: smoothstep,
  429. smootherstep: smootherstep,
  430. randInt: randInt,
  431. randFloat: randFloat,
  432. randFloatSpread: randFloatSpread,
  433. seededRandom: seededRandom,
  434. degToRad: degToRad,
  435. radToDeg: radToDeg,
  436. isPowerOfTwo: isPowerOfTwo,
  437. ceilPowerOfTwo: ceilPowerOfTwo,
  438. floorPowerOfTwo: floorPowerOfTwo,
  439. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  440. normalize: normalize,
  441. denormalize: denormalize
  442. };
  443. class Vector2 {
  444. constructor( x = 0, y = 0 ) {
  445. Vector2.prototype.isVector2 = true;
  446. this.x = x;
  447. this.y = y;
  448. }
  449. get width() {
  450. return this.x;
  451. }
  452. set width( value ) {
  453. this.x = value;
  454. }
  455. get height() {
  456. return this.y;
  457. }
  458. set height( value ) {
  459. this.y = value;
  460. }
  461. set( x, y ) {
  462. this.x = x;
  463. this.y = y;
  464. return this;
  465. }
  466. setScalar( scalar ) {
  467. this.x = scalar;
  468. this.y = scalar;
  469. return this;
  470. }
  471. setX( x ) {
  472. this.x = x;
  473. return this;
  474. }
  475. setY( y ) {
  476. this.y = y;
  477. return this;
  478. }
  479. setComponent( index, value ) {
  480. switch ( index ) {
  481. case 0: this.x = value; break;
  482. case 1: this.y = value; break;
  483. default: throw new Error( 'index is out of range: ' + index );
  484. }
  485. return this;
  486. }
  487. getComponent( index ) {
  488. switch ( index ) {
  489. case 0: return this.x;
  490. case 1: return this.y;
  491. default: throw new Error( 'index is out of range: ' + index );
  492. }
  493. }
  494. clone() {
  495. return new this.constructor( this.x, this.y );
  496. }
  497. copy( v ) {
  498. this.x = v.x;
  499. this.y = v.y;
  500. return this;
  501. }
  502. add( v ) {
  503. this.x += v.x;
  504. this.y += v.y;
  505. return this;
  506. }
  507. addScalar( s ) {
  508. this.x += s;
  509. this.y += s;
  510. return this;
  511. }
  512. addVectors( a, b ) {
  513. this.x = a.x + b.x;
  514. this.y = a.y + b.y;
  515. return this;
  516. }
  517. addScaledVector( v, s ) {
  518. this.x += v.x * s;
  519. this.y += v.y * s;
  520. return this;
  521. }
  522. sub( v ) {
  523. this.x -= v.x;
  524. this.y -= v.y;
  525. return this;
  526. }
  527. subScalar( s ) {
  528. this.x -= s;
  529. this.y -= s;
  530. return this;
  531. }
  532. subVectors( a, b ) {
  533. this.x = a.x - b.x;
  534. this.y = a.y - b.y;
  535. return this;
  536. }
  537. multiply( v ) {
  538. this.x *= v.x;
  539. this.y *= v.y;
  540. return this;
  541. }
  542. multiplyScalar( scalar ) {
  543. this.x *= scalar;
  544. this.y *= scalar;
  545. return this;
  546. }
  547. divide( v ) {
  548. this.x /= v.x;
  549. this.y /= v.y;
  550. return this;
  551. }
  552. divideScalar( scalar ) {
  553. return this.multiplyScalar( 1 / scalar );
  554. }
  555. applyMatrix3( m ) {
  556. const x = this.x, y = this.y;
  557. const e = m.elements;
  558. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  559. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  560. return this;
  561. }
  562. min( v ) {
  563. this.x = Math.min( this.x, v.x );
  564. this.y = Math.min( this.y, v.y );
  565. return this;
  566. }
  567. max( v ) {
  568. this.x = Math.max( this.x, v.x );
  569. this.y = Math.max( this.y, v.y );
  570. return this;
  571. }
  572. clamp( min, max ) {
  573. // assumes min < max, componentwise
  574. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  575. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  576. return this;
  577. }
  578. clampScalar( minVal, maxVal ) {
  579. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  580. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  581. return this;
  582. }
  583. clampLength( min, max ) {
  584. const length = this.length();
  585. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  586. }
  587. floor() {
  588. this.x = Math.floor( this.x );
  589. this.y = Math.floor( this.y );
  590. return this;
  591. }
  592. ceil() {
  593. this.x = Math.ceil( this.x );
  594. this.y = Math.ceil( this.y );
  595. return this;
  596. }
  597. round() {
  598. this.x = Math.round( this.x );
  599. this.y = Math.round( this.y );
  600. return this;
  601. }
  602. roundToZero() {
  603. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  604. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  605. return this;
  606. }
  607. negate() {
  608. this.x = - this.x;
  609. this.y = - this.y;
  610. return this;
  611. }
  612. dot( v ) {
  613. return this.x * v.x + this.y * v.y;
  614. }
  615. cross( v ) {
  616. return this.x * v.y - this.y * v.x;
  617. }
  618. lengthSq() {
  619. return this.x * this.x + this.y * this.y;
  620. }
  621. length() {
  622. return Math.sqrt( this.x * this.x + this.y * this.y );
  623. }
  624. manhattanLength() {
  625. return Math.abs( this.x ) + Math.abs( this.y );
  626. }
  627. normalize() {
  628. return this.divideScalar( this.length() || 1 );
  629. }
  630. angle() {
  631. // computes the angle in radians with respect to the positive x-axis
  632. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  633. return angle;
  634. }
  635. angleTo( v ) {
  636. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  637. if ( denominator === 0 ) return Math.PI / 2;
  638. const theta = this.dot( v ) / denominator;
  639. // clamp, to handle numerical problems
  640. return Math.acos( clamp( theta, - 1, 1 ) );
  641. }
  642. distanceTo( v ) {
  643. return Math.sqrt( this.distanceToSquared( v ) );
  644. }
  645. distanceToSquared( v ) {
  646. const dx = this.x - v.x, dy = this.y - v.y;
  647. return dx * dx + dy * dy;
  648. }
  649. manhattanDistanceTo( v ) {
  650. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  651. }
  652. setLength( length ) {
  653. return this.normalize().multiplyScalar( length );
  654. }
  655. lerp( v, alpha ) {
  656. this.x += ( v.x - this.x ) * alpha;
  657. this.y += ( v.y - this.y ) * alpha;
  658. return this;
  659. }
  660. lerpVectors( v1, v2, alpha ) {
  661. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  662. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  663. return this;
  664. }
  665. equals( v ) {
  666. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  667. }
  668. fromArray( array, offset = 0 ) {
  669. this.x = array[ offset ];
  670. this.y = array[ offset + 1 ];
  671. return this;
  672. }
  673. toArray( array = [], offset = 0 ) {
  674. array[ offset ] = this.x;
  675. array[ offset + 1 ] = this.y;
  676. return array;
  677. }
  678. fromBufferAttribute( attribute, index ) {
  679. this.x = attribute.getX( index );
  680. this.y = attribute.getY( index );
  681. return this;
  682. }
  683. rotateAround( center, angle ) {
  684. const c = Math.cos( angle ), s = Math.sin( angle );
  685. const x = this.x - center.x;
  686. const y = this.y - center.y;
  687. this.x = x * c - y * s + center.x;
  688. this.y = x * s + y * c + center.y;
  689. return this;
  690. }
  691. random() {
  692. this.x = Math.random();
  693. this.y = Math.random();
  694. return this;
  695. }
  696. *[ Symbol.iterator ]() {
  697. yield this.x;
  698. yield this.y;
  699. }
  700. }
  701. class Matrix3 {
  702. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  703. Matrix3.prototype.isMatrix3 = true;
  704. this.elements = [
  705. 1, 0, 0,
  706. 0, 1, 0,
  707. 0, 0, 1
  708. ];
  709. if ( n11 !== undefined ) {
  710. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  711. }
  712. }
  713. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  714. const te = this.elements;
  715. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  716. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  717. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  718. return this;
  719. }
  720. identity() {
  721. this.set(
  722. 1, 0, 0,
  723. 0, 1, 0,
  724. 0, 0, 1
  725. );
  726. return this;
  727. }
  728. copy( m ) {
  729. const te = this.elements;
  730. const me = m.elements;
  731. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  732. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  733. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  734. return this;
  735. }
  736. extractBasis( xAxis, yAxis, zAxis ) {
  737. xAxis.setFromMatrix3Column( this, 0 );
  738. yAxis.setFromMatrix3Column( this, 1 );
  739. zAxis.setFromMatrix3Column( this, 2 );
  740. return this;
  741. }
  742. setFromMatrix4( m ) {
  743. const me = m.elements;
  744. this.set(
  745. me[ 0 ], me[ 4 ], me[ 8 ],
  746. me[ 1 ], me[ 5 ], me[ 9 ],
  747. me[ 2 ], me[ 6 ], me[ 10 ]
  748. );
  749. return this;
  750. }
  751. multiply( m ) {
  752. return this.multiplyMatrices( this, m );
  753. }
  754. premultiply( m ) {
  755. return this.multiplyMatrices( m, this );
  756. }
  757. multiplyMatrices( a, b ) {
  758. const ae = a.elements;
  759. const be = b.elements;
  760. const te = this.elements;
  761. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  762. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  763. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  764. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  765. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  766. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  767. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  768. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  769. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  770. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  771. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  772. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  773. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  774. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  775. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  776. return this;
  777. }
  778. multiplyScalar( s ) {
  779. const te = this.elements;
  780. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  781. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  782. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  783. return this;
  784. }
  785. determinant() {
  786. const te = this.elements;
  787. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  788. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  789. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  790. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  791. }
  792. invert() {
  793. const te = this.elements,
  794. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  795. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  796. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  797. t11 = n33 * n22 - n32 * n23,
  798. t12 = n32 * n13 - n33 * n12,
  799. t13 = n23 * n12 - n22 * n13,
  800. det = n11 * t11 + n21 * t12 + n31 * t13;
  801. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  802. const detInv = 1 / det;
  803. te[ 0 ] = t11 * detInv;
  804. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  805. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  806. te[ 3 ] = t12 * detInv;
  807. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  808. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  809. te[ 6 ] = t13 * detInv;
  810. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  811. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  812. return this;
  813. }
  814. transpose() {
  815. let tmp;
  816. const m = this.elements;
  817. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  818. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  819. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  820. return this;
  821. }
  822. getNormalMatrix( matrix4 ) {
  823. return this.setFromMatrix4( matrix4 ).invert().transpose();
  824. }
  825. transposeIntoArray( r ) {
  826. const m = this.elements;
  827. r[ 0 ] = m[ 0 ];
  828. r[ 1 ] = m[ 3 ];
  829. r[ 2 ] = m[ 6 ];
  830. r[ 3 ] = m[ 1 ];
  831. r[ 4 ] = m[ 4 ];
  832. r[ 5 ] = m[ 7 ];
  833. r[ 6 ] = m[ 2 ];
  834. r[ 7 ] = m[ 5 ];
  835. r[ 8 ] = m[ 8 ];
  836. return this;
  837. }
  838. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  839. const c = Math.cos( rotation );
  840. const s = Math.sin( rotation );
  841. this.set(
  842. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  843. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  844. 0, 0, 1
  845. );
  846. return this;
  847. }
  848. //
  849. scale( sx, sy ) {
  850. this.premultiply( _m3.makeScale( sx, sy ) );
  851. return this;
  852. }
  853. rotate( theta ) {
  854. this.premultiply( _m3.makeRotation( - theta ) );
  855. return this;
  856. }
  857. translate( tx, ty ) {
  858. this.premultiply( _m3.makeTranslation( tx, ty ) );
  859. return this;
  860. }
  861. // for 2D Transforms
  862. makeTranslation( x, y ) {
  863. if ( x.isVector2 ) {
  864. this.set(
  865. 1, 0, x.x,
  866. 0, 1, x.y,
  867. 0, 0, 1
  868. );
  869. } else {
  870. this.set(
  871. 1, 0, x,
  872. 0, 1, y,
  873. 0, 0, 1
  874. );
  875. }
  876. return this;
  877. }
  878. makeRotation( theta ) {
  879. // counterclockwise
  880. const c = Math.cos( theta );
  881. const s = Math.sin( theta );
  882. this.set(
  883. c, - s, 0,
  884. s, c, 0,
  885. 0, 0, 1
  886. );
  887. return this;
  888. }
  889. makeScale( x, y ) {
  890. this.set(
  891. x, 0, 0,
  892. 0, y, 0,
  893. 0, 0, 1
  894. );
  895. return this;
  896. }
  897. //
  898. equals( matrix ) {
  899. const te = this.elements;
  900. const me = matrix.elements;
  901. for ( let i = 0; i < 9; i ++ ) {
  902. if ( te[ i ] !== me[ i ] ) return false;
  903. }
  904. return true;
  905. }
  906. fromArray( array, offset = 0 ) {
  907. for ( let i = 0; i < 9; i ++ ) {
  908. this.elements[ i ] = array[ i + offset ];
  909. }
  910. return this;
  911. }
  912. toArray( array = [], offset = 0 ) {
  913. const te = this.elements;
  914. array[ offset ] = te[ 0 ];
  915. array[ offset + 1 ] = te[ 1 ];
  916. array[ offset + 2 ] = te[ 2 ];
  917. array[ offset + 3 ] = te[ 3 ];
  918. array[ offset + 4 ] = te[ 4 ];
  919. array[ offset + 5 ] = te[ 5 ];
  920. array[ offset + 6 ] = te[ 6 ];
  921. array[ offset + 7 ] = te[ 7 ];
  922. array[ offset + 8 ] = te[ 8 ];
  923. return array;
  924. }
  925. clone() {
  926. return new this.constructor().fromArray( this.elements );
  927. }
  928. }
  929. const _m3 = /*@__PURE__*/ new Matrix3();
  930. function arrayNeedsUint32( array ) {
  931. // assumes larger values usually on last
  932. for ( let i = array.length - 1; i >= 0; -- i ) {
  933. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  934. }
  935. return false;
  936. }
  937. const TYPED_ARRAYS = {
  938. Int8Array: Int8Array,
  939. Uint8Array: Uint8Array,
  940. Uint8ClampedArray: Uint8ClampedArray,
  941. Int16Array: Int16Array,
  942. Uint16Array: Uint16Array,
  943. Int32Array: Int32Array,
  944. Uint32Array: Uint32Array,
  945. Float32Array: Float32Array,
  946. Float64Array: Float64Array
  947. };
  948. function getTypedArray( type, buffer ) {
  949. return new TYPED_ARRAYS[ type ]( buffer );
  950. }
  951. function createElementNS( name ) {
  952. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  953. }
  954. const _cache = {};
  955. function warnOnce( message ) {
  956. if ( message in _cache ) return;
  957. _cache[ message ] = true;
  958. console.warn( message );
  959. }
  960. function SRGBToLinear( c ) {
  961. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  962. }
  963. function LinearToSRGB( c ) {
  964. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  965. }
  966. /**
  967. * Matrices converting P3 <-> Rec. 709 primaries, without gamut mapping
  968. * or clipping. Based on W3C specifications for sRGB and Display P3,
  969. * and ICC specifications for the D50 connection space. Values in/out
  970. * are _linear_ sRGB and _linear_ Display P3.
  971. *
  972. * Note that both sRGB and Display P3 use the sRGB transfer functions.
  973. *
  974. * Reference:
  975. * - http://www.russellcottrell.com/photo/matrixCalculator.htm
  976. */
  977. const LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = /*@__PURE__*/ new Matrix3().fromArray( [
  978. 0.8224621, 0.0331941, 0.0170827,
  979. 0.1775380, 0.9668058, 0.0723974,
  980. - 0.0000001, 0.0000001, 0.9105199
  981. ] );
  982. const LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = /*@__PURE__*/ new Matrix3().fromArray( [
  983. 1.2249401, - 0.0420569, - 0.0196376,
  984. - 0.2249404, 1.0420571, - 0.0786361,
  985. 0.0000001, 0.0000000, 1.0982735
  986. ] );
  987. function DisplayP3ToLinearSRGB( color ) {
  988. // Display P3 uses the sRGB transfer functions
  989. return color.convertSRGBToLinear().applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB );
  990. }
  991. function LinearSRGBToDisplayP3( color ) {
  992. // Display P3 uses the sRGB transfer functions
  993. return color.applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 ).convertLinearToSRGB();
  994. }
  995. // Conversions from <source> to Linear-sRGB reference space.
  996. const TO_LINEAR = {
  997. [ LinearSRGBColorSpace ]: ( color ) => color,
  998. [ SRGBColorSpace ]: ( color ) => color.convertSRGBToLinear(),
  999. [ DisplayP3ColorSpace ]: DisplayP3ToLinearSRGB,
  1000. };
  1001. // Conversions to <target> from Linear-sRGB reference space.
  1002. const FROM_LINEAR = {
  1003. [ LinearSRGBColorSpace ]: ( color ) => color,
  1004. [ SRGBColorSpace ]: ( color ) => color.convertLinearToSRGB(),
  1005. [ DisplayP3ColorSpace ]: LinearSRGBToDisplayP3,
  1006. };
  1007. const ColorManagement = {
  1008. enabled: true,
  1009. get legacyMode() {
  1010. console.warn( 'THREE.ColorManagement: .legacyMode=false renamed to .enabled=true in r150.' );
  1011. return ! this.enabled;
  1012. },
  1013. set legacyMode( legacyMode ) {
  1014. console.warn( 'THREE.ColorManagement: .legacyMode=false renamed to .enabled=true in r150.' );
  1015. this.enabled = ! legacyMode;
  1016. },
  1017. get workingColorSpace() {
  1018. return LinearSRGBColorSpace;
  1019. },
  1020. set workingColorSpace( colorSpace ) {
  1021. console.warn( 'THREE.ColorManagement: .workingColorSpace is readonly.' );
  1022. },
  1023. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  1024. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  1025. return color;
  1026. }
  1027. const sourceToLinear = TO_LINEAR[ sourceColorSpace ];
  1028. const targetFromLinear = FROM_LINEAR[ targetColorSpace ];
  1029. if ( sourceToLinear === undefined || targetFromLinear === undefined ) {
  1030. throw new Error( `Unsupported color space conversion, "${ sourceColorSpace }" to "${ targetColorSpace }".` );
  1031. }
  1032. return targetFromLinear( sourceToLinear( color ) );
  1033. },
  1034. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1035. return this.convert( color, this.workingColorSpace, targetColorSpace );
  1036. },
  1037. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1038. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  1039. },
  1040. };
  1041. let _canvas;
  1042. class ImageUtils {
  1043. static getDataURL( image ) {
  1044. if ( /^data:/i.test( image.src ) ) {
  1045. return image.src;
  1046. }
  1047. if ( typeof HTMLCanvasElement === 'undefined' ) {
  1048. return image.src;
  1049. }
  1050. let canvas;
  1051. if ( image instanceof HTMLCanvasElement ) {
  1052. canvas = image;
  1053. } else {
  1054. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1055. _canvas.width = image.width;
  1056. _canvas.height = image.height;
  1057. const context = _canvas.getContext( '2d' );
  1058. if ( image instanceof ImageData ) {
  1059. context.putImageData( image, 0, 0 );
  1060. } else {
  1061. context.drawImage( image, 0, 0, image.width, image.height );
  1062. }
  1063. canvas = _canvas;
  1064. }
  1065. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1066. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1067. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1068. } else {
  1069. return canvas.toDataURL( 'image/png' );
  1070. }
  1071. }
  1072. static sRGBToLinear( image ) {
  1073. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1074. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1075. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1076. const canvas = createElementNS( 'canvas' );
  1077. canvas.width = image.width;
  1078. canvas.height = image.height;
  1079. const context = canvas.getContext( '2d' );
  1080. context.drawImage( image, 0, 0, image.width, image.height );
  1081. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1082. const data = imageData.data;
  1083. for ( let i = 0; i < data.length; i ++ ) {
  1084. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1085. }
  1086. context.putImageData( imageData, 0, 0 );
  1087. return canvas;
  1088. } else if ( image.data ) {
  1089. const data = image.data.slice( 0 );
  1090. for ( let i = 0; i < data.length; i ++ ) {
  1091. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1092. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1093. } else {
  1094. // assuming float
  1095. data[ i ] = SRGBToLinear( data[ i ] );
  1096. }
  1097. }
  1098. return {
  1099. data: data,
  1100. width: image.width,
  1101. height: image.height
  1102. };
  1103. } else {
  1104. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1105. return image;
  1106. }
  1107. }
  1108. }
  1109. let sourceId = 0;
  1110. class Source {
  1111. constructor( data = null ) {
  1112. this.isSource = true;
  1113. Object.defineProperty( this, 'id', { value: sourceId ++ } );
  1114. this.uuid = generateUUID();
  1115. this.data = data;
  1116. this.version = 0;
  1117. }
  1118. set needsUpdate( value ) {
  1119. if ( value === true ) this.version ++;
  1120. }
  1121. toJSON( meta ) {
  1122. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1123. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1124. return meta.images[ this.uuid ];
  1125. }
  1126. const output = {
  1127. uuid: this.uuid,
  1128. url: ''
  1129. };
  1130. const data = this.data;
  1131. if ( data !== null ) {
  1132. let url;
  1133. if ( Array.isArray( data ) ) {
  1134. // cube texture
  1135. url = [];
  1136. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1137. if ( data[ i ].isDataTexture ) {
  1138. url.push( serializeImage( data[ i ].image ) );
  1139. } else {
  1140. url.push( serializeImage( data[ i ] ) );
  1141. }
  1142. }
  1143. } else {
  1144. // texture
  1145. url = serializeImage( data );
  1146. }
  1147. output.url = url;
  1148. }
  1149. if ( ! isRootObject ) {
  1150. meta.images[ this.uuid ] = output;
  1151. }
  1152. return output;
  1153. }
  1154. }
  1155. function serializeImage( image ) {
  1156. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1157. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1158. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1159. // default images
  1160. return ImageUtils.getDataURL( image );
  1161. } else {
  1162. if ( image.data ) {
  1163. // images of DataTexture
  1164. return {
  1165. data: Array.from( image.data ),
  1166. width: image.width,
  1167. height: image.height,
  1168. type: image.data.constructor.name
  1169. };
  1170. } else {
  1171. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1172. return {};
  1173. }
  1174. }
  1175. }
  1176. let textureId = 0;
  1177. class Texture extends EventDispatcher {
  1178. constructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = Texture.DEFAULT_ANISOTROPY, colorSpace = NoColorSpace ) {
  1179. super();
  1180. this.isTexture = true;
  1181. Object.defineProperty( this, 'id', { value: textureId ++ } );
  1182. this.uuid = generateUUID();
  1183. this.name = '';
  1184. this.source = new Source( image );
  1185. this.mipmaps = [];
  1186. this.mapping = mapping;
  1187. this.channel = 0;
  1188. this.wrapS = wrapS;
  1189. this.wrapT = wrapT;
  1190. this.magFilter = magFilter;
  1191. this.minFilter = minFilter;
  1192. this.anisotropy = anisotropy;
  1193. this.format = format;
  1194. this.internalFormat = null;
  1195. this.type = type;
  1196. this.offset = new Vector2( 0, 0 );
  1197. this.repeat = new Vector2( 1, 1 );
  1198. this.center = new Vector2( 0, 0 );
  1199. this.rotation = 0;
  1200. this.matrixAutoUpdate = true;
  1201. this.matrix = new Matrix3();
  1202. this.generateMipmaps = true;
  1203. this.premultiplyAlpha = false;
  1204. this.flipY = true;
  1205. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1206. if ( typeof colorSpace === 'string' ) {
  1207. this.colorSpace = colorSpace;
  1208. } else { // @deprecated, r152
  1209. warnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' );
  1210. this.colorSpace = colorSpace === sRGBEncoding ? SRGBColorSpace : NoColorSpace;
  1211. }
  1212. this.userData = {};
  1213. this.version = 0;
  1214. this.onUpdate = null;
  1215. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1216. this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1217. }
  1218. get image() {
  1219. return this.source.data;
  1220. }
  1221. set image( value = null ) {
  1222. this.source.data = value;
  1223. }
  1224. updateMatrix() {
  1225. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1226. }
  1227. clone() {
  1228. return new this.constructor().copy( this );
  1229. }
  1230. copy( source ) {
  1231. this.name = source.name;
  1232. this.source = source.source;
  1233. this.mipmaps = source.mipmaps.slice( 0 );
  1234. this.mapping = source.mapping;
  1235. this.channel = source.channel;
  1236. this.wrapS = source.wrapS;
  1237. this.wrapT = source.wrapT;
  1238. this.magFilter = source.magFilter;
  1239. this.minFilter = source.minFilter;
  1240. this.anisotropy = source.anisotropy;
  1241. this.format = source.format;
  1242. this.internalFormat = source.internalFormat;
  1243. this.type = source.type;
  1244. this.offset.copy( source.offset );
  1245. this.repeat.copy( source.repeat );
  1246. this.center.copy( source.center );
  1247. this.rotation = source.rotation;
  1248. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1249. this.matrix.copy( source.matrix );
  1250. this.generateMipmaps = source.generateMipmaps;
  1251. this.premultiplyAlpha = source.premultiplyAlpha;
  1252. this.flipY = source.flipY;
  1253. this.unpackAlignment = source.unpackAlignment;
  1254. this.colorSpace = source.colorSpace;
  1255. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1256. this.needsUpdate = true;
  1257. return this;
  1258. }
  1259. toJSON( meta ) {
  1260. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1261. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1262. return meta.textures[ this.uuid ];
  1263. }
  1264. const output = {
  1265. metadata: {
  1266. version: 4.6,
  1267. type: 'Texture',
  1268. generator: 'Texture.toJSON'
  1269. },
  1270. uuid: this.uuid,
  1271. name: this.name,
  1272. image: this.source.toJSON( meta ).uuid,
  1273. mapping: this.mapping,
  1274. channel: this.channel,
  1275. repeat: [ this.repeat.x, this.repeat.y ],
  1276. offset: [ this.offset.x, this.offset.y ],
  1277. center: [ this.center.x, this.center.y ],
  1278. rotation: this.rotation,
  1279. wrap: [ this.wrapS, this.wrapT ],
  1280. format: this.format,
  1281. internalFormat: this.internalFormat,
  1282. type: this.type,
  1283. colorSpace: this.colorSpace,
  1284. minFilter: this.minFilter,
  1285. magFilter: this.magFilter,
  1286. anisotropy: this.anisotropy,
  1287. flipY: this.flipY,
  1288. generateMipmaps: this.generateMipmaps,
  1289. premultiplyAlpha: this.premultiplyAlpha,
  1290. unpackAlignment: this.unpackAlignment
  1291. };
  1292. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  1293. if ( ! isRootObject ) {
  1294. meta.textures[ this.uuid ] = output;
  1295. }
  1296. return output;
  1297. }
  1298. dispose() {
  1299. this.dispatchEvent( { type: 'dispose' } );
  1300. }
  1301. transformUv( uv ) {
  1302. if ( this.mapping !== UVMapping ) return uv;
  1303. uv.applyMatrix3( this.matrix );
  1304. if ( uv.x < 0 || uv.x > 1 ) {
  1305. switch ( this.wrapS ) {
  1306. case RepeatWrapping:
  1307. uv.x = uv.x - Math.floor( uv.x );
  1308. break;
  1309. case ClampToEdgeWrapping:
  1310. uv.x = uv.x < 0 ? 0 : 1;
  1311. break;
  1312. case MirroredRepeatWrapping:
  1313. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1314. uv.x = Math.ceil( uv.x ) - uv.x;
  1315. } else {
  1316. uv.x = uv.x - Math.floor( uv.x );
  1317. }
  1318. break;
  1319. }
  1320. }
  1321. if ( uv.y < 0 || uv.y > 1 ) {
  1322. switch ( this.wrapT ) {
  1323. case RepeatWrapping:
  1324. uv.y = uv.y - Math.floor( uv.y );
  1325. break;
  1326. case ClampToEdgeWrapping:
  1327. uv.y = uv.y < 0 ? 0 : 1;
  1328. break;
  1329. case MirroredRepeatWrapping:
  1330. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1331. uv.y = Math.ceil( uv.y ) - uv.y;
  1332. } else {
  1333. uv.y = uv.y - Math.floor( uv.y );
  1334. }
  1335. break;
  1336. }
  1337. }
  1338. if ( this.flipY ) {
  1339. uv.y = 1 - uv.y;
  1340. }
  1341. return uv;
  1342. }
  1343. set needsUpdate( value ) {
  1344. if ( value === true ) {
  1345. this.version ++;
  1346. this.source.needsUpdate = true;
  1347. }
  1348. }
  1349. get encoding() { // @deprecated, r152
  1350. warnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' );
  1351. return this.colorSpace === SRGBColorSpace ? sRGBEncoding : LinearEncoding;
  1352. }
  1353. set encoding( encoding ) { // @deprecated, r152
  1354. warnOnce( 'THREE.Texture: Property .encoding has been replaced by .colorSpace.' );
  1355. this.colorSpace = encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace;
  1356. }
  1357. }
  1358. Texture.DEFAULT_IMAGE = null;
  1359. Texture.DEFAULT_MAPPING = UVMapping;
  1360. Texture.DEFAULT_ANISOTROPY = 1;
  1361. class Vector4 {
  1362. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1363. Vector4.prototype.isVector4 = true;
  1364. this.x = x;
  1365. this.y = y;
  1366. this.z = z;
  1367. this.w = w;
  1368. }
  1369. get width() {
  1370. return this.z;
  1371. }
  1372. set width( value ) {
  1373. this.z = value;
  1374. }
  1375. get height() {
  1376. return this.w;
  1377. }
  1378. set height( value ) {
  1379. this.w = value;
  1380. }
  1381. set( x, y, z, w ) {
  1382. this.x = x;
  1383. this.y = y;
  1384. this.z = z;
  1385. this.w = w;
  1386. return this;
  1387. }
  1388. setScalar( scalar ) {
  1389. this.x = scalar;
  1390. this.y = scalar;
  1391. this.z = scalar;
  1392. this.w = scalar;
  1393. return this;
  1394. }
  1395. setX( x ) {
  1396. this.x = x;
  1397. return this;
  1398. }
  1399. setY( y ) {
  1400. this.y = y;
  1401. return this;
  1402. }
  1403. setZ( z ) {
  1404. this.z = z;
  1405. return this;
  1406. }
  1407. setW( w ) {
  1408. this.w = w;
  1409. return this;
  1410. }
  1411. setComponent( index, value ) {
  1412. switch ( index ) {
  1413. case 0: this.x = value; break;
  1414. case 1: this.y = value; break;
  1415. case 2: this.z = value; break;
  1416. case 3: this.w = value; break;
  1417. default: throw new Error( 'index is out of range: ' + index );
  1418. }
  1419. return this;
  1420. }
  1421. getComponent( index ) {
  1422. switch ( index ) {
  1423. case 0: return this.x;
  1424. case 1: return this.y;
  1425. case 2: return this.z;
  1426. case 3: return this.w;
  1427. default: throw new Error( 'index is out of range: ' + index );
  1428. }
  1429. }
  1430. clone() {
  1431. return new this.constructor( this.x, this.y, this.z, this.w );
  1432. }
  1433. copy( v ) {
  1434. this.x = v.x;
  1435. this.y = v.y;
  1436. this.z = v.z;
  1437. this.w = ( v.w !== undefined ) ? v.w : 1;
  1438. return this;
  1439. }
  1440. add( v ) {
  1441. this.x += v.x;
  1442. this.y += v.y;
  1443. this.z += v.z;
  1444. this.w += v.w;
  1445. return this;
  1446. }
  1447. addScalar( s ) {
  1448. this.x += s;
  1449. this.y += s;
  1450. this.z += s;
  1451. this.w += s;
  1452. return this;
  1453. }
  1454. addVectors( a, b ) {
  1455. this.x = a.x + b.x;
  1456. this.y = a.y + b.y;
  1457. this.z = a.z + b.z;
  1458. this.w = a.w + b.w;
  1459. return this;
  1460. }
  1461. addScaledVector( v, s ) {
  1462. this.x += v.x * s;
  1463. this.y += v.y * s;
  1464. this.z += v.z * s;
  1465. this.w += v.w * s;
  1466. return this;
  1467. }
  1468. sub( v ) {
  1469. this.x -= v.x;
  1470. this.y -= v.y;
  1471. this.z -= v.z;
  1472. this.w -= v.w;
  1473. return this;
  1474. }
  1475. subScalar( s ) {
  1476. this.x -= s;
  1477. this.y -= s;
  1478. this.z -= s;
  1479. this.w -= s;
  1480. return this;
  1481. }
  1482. subVectors( a, b ) {
  1483. this.x = a.x - b.x;
  1484. this.y = a.y - b.y;
  1485. this.z = a.z - b.z;
  1486. this.w = a.w - b.w;
  1487. return this;
  1488. }
  1489. multiply( v ) {
  1490. this.x *= v.x;
  1491. this.y *= v.y;
  1492. this.z *= v.z;
  1493. this.w *= v.w;
  1494. return this;
  1495. }
  1496. multiplyScalar( scalar ) {
  1497. this.x *= scalar;
  1498. this.y *= scalar;
  1499. this.z *= scalar;
  1500. this.w *= scalar;
  1501. return this;
  1502. }
  1503. applyMatrix4( m ) {
  1504. const x = this.x, y = this.y, z = this.z, w = this.w;
  1505. const e = m.elements;
  1506. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1507. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1508. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1509. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1510. return this;
  1511. }
  1512. divideScalar( scalar ) {
  1513. return this.multiplyScalar( 1 / scalar );
  1514. }
  1515. setAxisAngleFromQuaternion( q ) {
  1516. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1517. // q is assumed to be normalized
  1518. this.w = 2 * Math.acos( q.w );
  1519. const s = Math.sqrt( 1 - q.w * q.w );
  1520. if ( s < 0.0001 ) {
  1521. this.x = 1;
  1522. this.y = 0;
  1523. this.z = 0;
  1524. } else {
  1525. this.x = q.x / s;
  1526. this.y = q.y / s;
  1527. this.z = q.z / s;
  1528. }
  1529. return this;
  1530. }
  1531. setAxisAngleFromRotationMatrix( m ) {
  1532. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1533. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1534. let angle, x, y, z; // variables for result
  1535. const epsilon = 0.01, // margin to allow for rounding errors
  1536. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1537. te = m.elements,
  1538. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1539. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1540. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1541. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1542. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1543. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1544. // singularity found
  1545. // first check for identity matrix which must have +1 for all terms
  1546. // in leading diagonal and zero in other terms
  1547. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1548. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1549. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1550. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1551. // this singularity is identity matrix so angle = 0
  1552. this.set( 1, 0, 0, 0 );
  1553. return this; // zero angle, arbitrary axis
  1554. }
  1555. // otherwise this singularity is angle = 180
  1556. angle = Math.PI;
  1557. const xx = ( m11 + 1 ) / 2;
  1558. const yy = ( m22 + 1 ) / 2;
  1559. const zz = ( m33 + 1 ) / 2;
  1560. const xy = ( m12 + m21 ) / 4;
  1561. const xz = ( m13 + m31 ) / 4;
  1562. const yz = ( m23 + m32 ) / 4;
  1563. if ( ( xx > yy ) && ( xx > zz ) ) {
  1564. // m11 is the largest diagonal term
  1565. if ( xx < epsilon ) {
  1566. x = 0;
  1567. y = 0.707106781;
  1568. z = 0.707106781;
  1569. } else {
  1570. x = Math.sqrt( xx );
  1571. y = xy / x;
  1572. z = xz / x;
  1573. }
  1574. } else if ( yy > zz ) {
  1575. // m22 is the largest diagonal term
  1576. if ( yy < epsilon ) {
  1577. x = 0.707106781;
  1578. y = 0;
  1579. z = 0.707106781;
  1580. } else {
  1581. y = Math.sqrt( yy );
  1582. x = xy / y;
  1583. z = yz / y;
  1584. }
  1585. } else {
  1586. // m33 is the largest diagonal term so base result on this
  1587. if ( zz < epsilon ) {
  1588. x = 0.707106781;
  1589. y = 0.707106781;
  1590. z = 0;
  1591. } else {
  1592. z = Math.sqrt( zz );
  1593. x = xz / z;
  1594. y = yz / z;
  1595. }
  1596. }
  1597. this.set( x, y, z, angle );
  1598. return this; // return 180 deg rotation
  1599. }
  1600. // as we have reached here there are no singularities so we can handle normally
  1601. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1602. ( m13 - m31 ) * ( m13 - m31 ) +
  1603. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1604. if ( Math.abs( s ) < 0.001 ) s = 1;
  1605. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1606. // caught by singularity test above, but I've left it in just in case
  1607. this.x = ( m32 - m23 ) / s;
  1608. this.y = ( m13 - m31 ) / s;
  1609. this.z = ( m21 - m12 ) / s;
  1610. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1611. return this;
  1612. }
  1613. min( v ) {
  1614. this.x = Math.min( this.x, v.x );
  1615. this.y = Math.min( this.y, v.y );
  1616. this.z = Math.min( this.z, v.z );
  1617. this.w = Math.min( this.w, v.w );
  1618. return this;
  1619. }
  1620. max( v ) {
  1621. this.x = Math.max( this.x, v.x );
  1622. this.y = Math.max( this.y, v.y );
  1623. this.z = Math.max( this.z, v.z );
  1624. this.w = Math.max( this.w, v.w );
  1625. return this;
  1626. }
  1627. clamp( min, max ) {
  1628. // assumes min < max, componentwise
  1629. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1630. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1631. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1632. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1633. return this;
  1634. }
  1635. clampScalar( minVal, maxVal ) {
  1636. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1637. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1638. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1639. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1640. return this;
  1641. }
  1642. clampLength( min, max ) {
  1643. const length = this.length();
  1644. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1645. }
  1646. floor() {
  1647. this.x = Math.floor( this.x );
  1648. this.y = Math.floor( this.y );
  1649. this.z = Math.floor( this.z );
  1650. this.w = Math.floor( this.w );
  1651. return this;
  1652. }
  1653. ceil() {
  1654. this.x = Math.ceil( this.x );
  1655. this.y = Math.ceil( this.y );
  1656. this.z = Math.ceil( this.z );
  1657. this.w = Math.ceil( this.w );
  1658. return this;
  1659. }
  1660. round() {
  1661. this.x = Math.round( this.x );
  1662. this.y = Math.round( this.y );
  1663. this.z = Math.round( this.z );
  1664. this.w = Math.round( this.w );
  1665. return this;
  1666. }
  1667. roundToZero() {
  1668. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1669. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1670. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1671. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1672. return this;
  1673. }
  1674. negate() {
  1675. this.x = - this.x;
  1676. this.y = - this.y;
  1677. this.z = - this.z;
  1678. this.w = - this.w;
  1679. return this;
  1680. }
  1681. dot( v ) {
  1682. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1683. }
  1684. lengthSq() {
  1685. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1686. }
  1687. length() {
  1688. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1689. }
  1690. manhattanLength() {
  1691. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1692. }
  1693. normalize() {
  1694. return this.divideScalar( this.length() || 1 );
  1695. }
  1696. setLength( length ) {
  1697. return this.normalize().multiplyScalar( length );
  1698. }
  1699. lerp( v, alpha ) {
  1700. this.x += ( v.x - this.x ) * alpha;
  1701. this.y += ( v.y - this.y ) * alpha;
  1702. this.z += ( v.z - this.z ) * alpha;
  1703. this.w += ( v.w - this.w ) * alpha;
  1704. return this;
  1705. }
  1706. lerpVectors( v1, v2, alpha ) {
  1707. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1708. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1709. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1710. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1711. return this;
  1712. }
  1713. equals( v ) {
  1714. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1715. }
  1716. fromArray( array, offset = 0 ) {
  1717. this.x = array[ offset ];
  1718. this.y = array[ offset + 1 ];
  1719. this.z = array[ offset + 2 ];
  1720. this.w = array[ offset + 3 ];
  1721. return this;
  1722. }
  1723. toArray( array = [], offset = 0 ) {
  1724. array[ offset ] = this.x;
  1725. array[ offset + 1 ] = this.y;
  1726. array[ offset + 2 ] = this.z;
  1727. array[ offset + 3 ] = this.w;
  1728. return array;
  1729. }
  1730. fromBufferAttribute( attribute, index ) {
  1731. this.x = attribute.getX( index );
  1732. this.y = attribute.getY( index );
  1733. this.z = attribute.getZ( index );
  1734. this.w = attribute.getW( index );
  1735. return this;
  1736. }
  1737. random() {
  1738. this.x = Math.random();
  1739. this.y = Math.random();
  1740. this.z = Math.random();
  1741. this.w = Math.random();
  1742. return this;
  1743. }
  1744. *[ Symbol.iterator ]() {
  1745. yield this.x;
  1746. yield this.y;
  1747. yield this.z;
  1748. yield this.w;
  1749. }
  1750. }
  1751. /*
  1752. In options, we can specify:
  1753. * Texture parameters for an auto-generated target texture
  1754. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1755. */
  1756. class WebGLRenderTarget extends EventDispatcher {
  1757. constructor( width = 1, height = 1, options = {} ) {
  1758. super();
  1759. this.isWebGLRenderTarget = true;
  1760. this.width = width;
  1761. this.height = height;
  1762. this.depth = 1;
  1763. this.scissor = new Vector4( 0, 0, width, height );
  1764. this.scissorTest = false;
  1765. this.viewport = new Vector4( 0, 0, width, height );
  1766. const image = { width: width, height: height, depth: 1 };
  1767. if ( options.encoding !== undefined ) {
  1768. // @deprecated, r152
  1769. warnOnce( 'THREE.WebGLRenderTarget: option.encoding has been replaced by option.colorSpace.' );
  1770. options.colorSpace = options.encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace;
  1771. }
  1772. this.texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  1773. this.texture.isRenderTargetTexture = true;
  1774. this.texture.flipY = false;
  1775. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  1776. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  1777. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  1778. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  1779. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  1780. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  1781. this.samples = options.samples !== undefined ? options.samples : 0;
  1782. }
  1783. setSize( width, height, depth = 1 ) {
  1784. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1785. this.width = width;
  1786. this.height = height;
  1787. this.depth = depth;
  1788. this.texture.image.width = width;
  1789. this.texture.image.height = height;
  1790. this.texture.image.depth = depth;
  1791. this.dispose();
  1792. }
  1793. this.viewport.set( 0, 0, width, height );
  1794. this.scissor.set( 0, 0, width, height );
  1795. }
  1796. clone() {
  1797. return new this.constructor().copy( this );
  1798. }
  1799. copy( source ) {
  1800. this.width = source.width;
  1801. this.height = source.height;
  1802. this.depth = source.depth;
  1803. this.scissor.copy( source.scissor );
  1804. this.scissorTest = source.scissorTest;
  1805. this.viewport.copy( source.viewport );
  1806. this.texture = source.texture.clone();
  1807. this.texture.isRenderTargetTexture = true;
  1808. // ensure image object is not shared, see #20328
  1809. const image = Object.assign( {}, source.texture.image );
  1810. this.texture.source = new Source( image );
  1811. this.depthBuffer = source.depthBuffer;
  1812. this.stencilBuffer = source.stencilBuffer;
  1813. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1814. this.samples = source.samples;
  1815. return this;
  1816. }
  1817. dispose() {
  1818. this.dispatchEvent( { type: 'dispose' } );
  1819. }
  1820. }
  1821. class DataArrayTexture extends Texture {
  1822. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1823. super( null );
  1824. this.isDataArrayTexture = true;
  1825. this.image = { data, width, height, depth };
  1826. this.magFilter = NearestFilter;
  1827. this.minFilter = NearestFilter;
  1828. this.wrapR = ClampToEdgeWrapping;
  1829. this.generateMipmaps = false;
  1830. this.flipY = false;
  1831. this.unpackAlignment = 1;
  1832. }
  1833. }
  1834. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  1835. constructor( width = 1, height = 1, depth = 1 ) {
  1836. super( width, height );
  1837. this.isWebGLArrayRenderTarget = true;
  1838. this.depth = depth;
  1839. this.texture = new DataArrayTexture( null, width, height, depth );
  1840. this.texture.isRenderTargetTexture = true;
  1841. }
  1842. }
  1843. class Data3DTexture extends Texture {
  1844. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  1845. // We're going to add .setXXX() methods for setting properties later.
  1846. // Users can still set in DataTexture3D directly.
  1847. //
  1848. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  1849. // texture.anisotropy = 16;
  1850. //
  1851. // See #14839
  1852. super( null );
  1853. this.isData3DTexture = true;
  1854. this.image = { data, width, height, depth };
  1855. this.magFilter = NearestFilter;
  1856. this.minFilter = NearestFilter;
  1857. this.wrapR = ClampToEdgeWrapping;
  1858. this.generateMipmaps = false;
  1859. this.flipY = false;
  1860. this.unpackAlignment = 1;
  1861. }
  1862. }
  1863. class WebGL3DRenderTarget extends WebGLRenderTarget {
  1864. constructor( width = 1, height = 1, depth = 1 ) {
  1865. super( width, height );
  1866. this.isWebGL3DRenderTarget = true;
  1867. this.depth = depth;
  1868. this.texture = new Data3DTexture( null, width, height, depth );
  1869. this.texture.isRenderTargetTexture = true;
  1870. }
  1871. }
  1872. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  1873. constructor( width = 1, height = 1, count = 1, options = {} ) {
  1874. super( width, height, options );
  1875. this.isWebGLMultipleRenderTargets = true;
  1876. const texture = this.texture;
  1877. this.texture = [];
  1878. for ( let i = 0; i < count; i ++ ) {
  1879. this.texture[ i ] = texture.clone();
  1880. this.texture[ i ].isRenderTargetTexture = true;
  1881. }
  1882. }
  1883. setSize( width, height, depth = 1 ) {
  1884. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  1885. this.width = width;
  1886. this.height = height;
  1887. this.depth = depth;
  1888. for ( let i = 0, il = this.texture.length; i < il; i ++ ) {
  1889. this.texture[ i ].image.width = width;
  1890. this.texture[ i ].image.height = height;
  1891. this.texture[ i ].image.depth = depth;
  1892. }
  1893. this.dispose();
  1894. }
  1895. this.viewport.set( 0, 0, width, height );
  1896. this.scissor.set( 0, 0, width, height );
  1897. return this;
  1898. }
  1899. copy( source ) {
  1900. this.dispose();
  1901. this.width = source.width;
  1902. this.height = source.height;
  1903. this.depth = source.depth;
  1904. this.scissor.copy( source.scissor );
  1905. this.scissorTest = source.scissorTest;
  1906. this.viewport.copy( source.viewport );
  1907. this.depthBuffer = source.depthBuffer;
  1908. this.stencilBuffer = source.stencilBuffer;
  1909. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  1910. this.texture.length = 0;
  1911. for ( let i = 0, il = source.texture.length; i < il; i ++ ) {
  1912. this.texture[ i ] = source.texture[ i ].clone();
  1913. this.texture[ i ].isRenderTargetTexture = true;
  1914. }
  1915. return this;
  1916. }
  1917. }
  1918. class Quaternion {
  1919. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1920. this.isQuaternion = true;
  1921. this._x = x;
  1922. this._y = y;
  1923. this._z = z;
  1924. this._w = w;
  1925. }
  1926. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  1927. // fuzz-free, array-based Quaternion SLERP operation
  1928. let x0 = src0[ srcOffset0 + 0 ],
  1929. y0 = src0[ srcOffset0 + 1 ],
  1930. z0 = src0[ srcOffset0 + 2 ],
  1931. w0 = src0[ srcOffset0 + 3 ];
  1932. const x1 = src1[ srcOffset1 + 0 ],
  1933. y1 = src1[ srcOffset1 + 1 ],
  1934. z1 = src1[ srcOffset1 + 2 ],
  1935. w1 = src1[ srcOffset1 + 3 ];
  1936. if ( t === 0 ) {
  1937. dst[ dstOffset + 0 ] = x0;
  1938. dst[ dstOffset + 1 ] = y0;
  1939. dst[ dstOffset + 2 ] = z0;
  1940. dst[ dstOffset + 3 ] = w0;
  1941. return;
  1942. }
  1943. if ( t === 1 ) {
  1944. dst[ dstOffset + 0 ] = x1;
  1945. dst[ dstOffset + 1 ] = y1;
  1946. dst[ dstOffset + 2 ] = z1;
  1947. dst[ dstOffset + 3 ] = w1;
  1948. return;
  1949. }
  1950. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  1951. let s = 1 - t;
  1952. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  1953. dir = ( cos >= 0 ? 1 : - 1 ),
  1954. sqrSin = 1 - cos * cos;
  1955. // Skip the Slerp for tiny steps to avoid numeric problems:
  1956. if ( sqrSin > Number.EPSILON ) {
  1957. const sin = Math.sqrt( sqrSin ),
  1958. len = Math.atan2( sin, cos * dir );
  1959. s = Math.sin( s * len ) / sin;
  1960. t = Math.sin( t * len ) / sin;
  1961. }
  1962. const tDir = t * dir;
  1963. x0 = x0 * s + x1 * tDir;
  1964. y0 = y0 * s + y1 * tDir;
  1965. z0 = z0 * s + z1 * tDir;
  1966. w0 = w0 * s + w1 * tDir;
  1967. // Normalize in case we just did a lerp:
  1968. if ( s === 1 - t ) {
  1969. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  1970. x0 *= f;
  1971. y0 *= f;
  1972. z0 *= f;
  1973. w0 *= f;
  1974. }
  1975. }
  1976. dst[ dstOffset ] = x0;
  1977. dst[ dstOffset + 1 ] = y0;
  1978. dst[ dstOffset + 2 ] = z0;
  1979. dst[ dstOffset + 3 ] = w0;
  1980. }
  1981. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  1982. const x0 = src0[ srcOffset0 ];
  1983. const y0 = src0[ srcOffset0 + 1 ];
  1984. const z0 = src0[ srcOffset0 + 2 ];
  1985. const w0 = src0[ srcOffset0 + 3 ];
  1986. const x1 = src1[ srcOffset1 ];
  1987. const y1 = src1[ srcOffset1 + 1 ];
  1988. const z1 = src1[ srcOffset1 + 2 ];
  1989. const w1 = src1[ srcOffset1 + 3 ];
  1990. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  1991. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  1992. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  1993. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  1994. return dst;
  1995. }
  1996. get x() {
  1997. return this._x;
  1998. }
  1999. set x( value ) {
  2000. this._x = value;
  2001. this._onChangeCallback();
  2002. }
  2003. get y() {
  2004. return this._y;
  2005. }
  2006. set y( value ) {
  2007. this._y = value;
  2008. this._onChangeCallback();
  2009. }
  2010. get z() {
  2011. return this._z;
  2012. }
  2013. set z( value ) {
  2014. this._z = value;
  2015. this._onChangeCallback();
  2016. }
  2017. get w() {
  2018. return this._w;
  2019. }
  2020. set w( value ) {
  2021. this._w = value;
  2022. this._onChangeCallback();
  2023. }
  2024. set( x, y, z, w ) {
  2025. this._x = x;
  2026. this._y = y;
  2027. this._z = z;
  2028. this._w = w;
  2029. this._onChangeCallback();
  2030. return this;
  2031. }
  2032. clone() {
  2033. return new this.constructor( this._x, this._y, this._z, this._w );
  2034. }
  2035. copy( quaternion ) {
  2036. this._x = quaternion.x;
  2037. this._y = quaternion.y;
  2038. this._z = quaternion.z;
  2039. this._w = quaternion.w;
  2040. this._onChangeCallback();
  2041. return this;
  2042. }
  2043. setFromEuler( euler, update ) {
  2044. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2045. // http://www.mathworks.com/matlabcentral/fileexchange/
  2046. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2047. // content/SpinCalc.m
  2048. const cos = Math.cos;
  2049. const sin = Math.sin;
  2050. const c1 = cos( x / 2 );
  2051. const c2 = cos( y / 2 );
  2052. const c3 = cos( z / 2 );
  2053. const s1 = sin( x / 2 );
  2054. const s2 = sin( y / 2 );
  2055. const s3 = sin( z / 2 );
  2056. switch ( order ) {
  2057. case 'XYZ':
  2058. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2059. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2060. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2061. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2062. break;
  2063. case 'YXZ':
  2064. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2065. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2066. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2067. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2068. break;
  2069. case 'ZXY':
  2070. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2071. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2072. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2073. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2074. break;
  2075. case 'ZYX':
  2076. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2077. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2078. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2079. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2080. break;
  2081. case 'YZX':
  2082. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2083. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2084. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2085. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2086. break;
  2087. case 'XZY':
  2088. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2089. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2090. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2091. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2092. break;
  2093. default:
  2094. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2095. }
  2096. if ( update !== false ) this._onChangeCallback();
  2097. return this;
  2098. }
  2099. setFromAxisAngle( axis, angle ) {
  2100. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2101. // assumes axis is normalized
  2102. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2103. this._x = axis.x * s;
  2104. this._y = axis.y * s;
  2105. this._z = axis.z * s;
  2106. this._w = Math.cos( halfAngle );
  2107. this._onChangeCallback();
  2108. return this;
  2109. }
  2110. setFromRotationMatrix( m ) {
  2111. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2112. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2113. const te = m.elements,
  2114. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2115. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2116. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2117. trace = m11 + m22 + m33;
  2118. if ( trace > 0 ) {
  2119. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2120. this._w = 0.25 / s;
  2121. this._x = ( m32 - m23 ) * s;
  2122. this._y = ( m13 - m31 ) * s;
  2123. this._z = ( m21 - m12 ) * s;
  2124. } else if ( m11 > m22 && m11 > m33 ) {
  2125. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2126. this._w = ( m32 - m23 ) / s;
  2127. this._x = 0.25 * s;
  2128. this._y = ( m12 + m21 ) / s;
  2129. this._z = ( m13 + m31 ) / s;
  2130. } else if ( m22 > m33 ) {
  2131. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2132. this._w = ( m13 - m31 ) / s;
  2133. this._x = ( m12 + m21 ) / s;
  2134. this._y = 0.25 * s;
  2135. this._z = ( m23 + m32 ) / s;
  2136. } else {
  2137. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2138. this._w = ( m21 - m12 ) / s;
  2139. this._x = ( m13 + m31 ) / s;
  2140. this._y = ( m23 + m32 ) / s;
  2141. this._z = 0.25 * s;
  2142. }
  2143. this._onChangeCallback();
  2144. return this;
  2145. }
  2146. setFromUnitVectors( vFrom, vTo ) {
  2147. // assumes direction vectors vFrom and vTo are normalized
  2148. let r = vFrom.dot( vTo ) + 1;
  2149. if ( r < Number.EPSILON ) {
  2150. // vFrom and vTo point in opposite directions
  2151. r = 0;
  2152. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2153. this._x = - vFrom.y;
  2154. this._y = vFrom.x;
  2155. this._z = 0;
  2156. this._w = r;
  2157. } else {
  2158. this._x = 0;
  2159. this._y = - vFrom.z;
  2160. this._z = vFrom.y;
  2161. this._w = r;
  2162. }
  2163. } else {
  2164. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2165. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2166. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2167. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2168. this._w = r;
  2169. }
  2170. return this.normalize();
  2171. }
  2172. angleTo( q ) {
  2173. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  2174. }
  2175. rotateTowards( q, step ) {
  2176. const angle = this.angleTo( q );
  2177. if ( angle === 0 ) return this;
  2178. const t = Math.min( 1, step / angle );
  2179. this.slerp( q, t );
  2180. return this;
  2181. }
  2182. identity() {
  2183. return this.set( 0, 0, 0, 1 );
  2184. }
  2185. invert() {
  2186. // quaternion is assumed to have unit length
  2187. return this.conjugate();
  2188. }
  2189. conjugate() {
  2190. this._x *= - 1;
  2191. this._y *= - 1;
  2192. this._z *= - 1;
  2193. this._onChangeCallback();
  2194. return this;
  2195. }
  2196. dot( v ) {
  2197. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2198. }
  2199. lengthSq() {
  2200. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2201. }
  2202. length() {
  2203. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2204. }
  2205. normalize() {
  2206. let l = this.length();
  2207. if ( l === 0 ) {
  2208. this._x = 0;
  2209. this._y = 0;
  2210. this._z = 0;
  2211. this._w = 1;
  2212. } else {
  2213. l = 1 / l;
  2214. this._x = this._x * l;
  2215. this._y = this._y * l;
  2216. this._z = this._z * l;
  2217. this._w = this._w * l;
  2218. }
  2219. this._onChangeCallback();
  2220. return this;
  2221. }
  2222. multiply( q ) {
  2223. return this.multiplyQuaternions( this, q );
  2224. }
  2225. premultiply( q ) {
  2226. return this.multiplyQuaternions( q, this );
  2227. }
  2228. multiplyQuaternions( a, b ) {
  2229. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2230. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2231. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2232. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2233. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2234. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2235. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2236. this._onChangeCallback();
  2237. return this;
  2238. }
  2239. slerp( qb, t ) {
  2240. if ( t === 0 ) return this;
  2241. if ( t === 1 ) return this.copy( qb );
  2242. const x = this._x, y = this._y, z = this._z, w = this._w;
  2243. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2244. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2245. if ( cosHalfTheta < 0 ) {
  2246. this._w = - qb._w;
  2247. this._x = - qb._x;
  2248. this._y = - qb._y;
  2249. this._z = - qb._z;
  2250. cosHalfTheta = - cosHalfTheta;
  2251. } else {
  2252. this.copy( qb );
  2253. }
  2254. if ( cosHalfTheta >= 1.0 ) {
  2255. this._w = w;
  2256. this._x = x;
  2257. this._y = y;
  2258. this._z = z;
  2259. return this;
  2260. }
  2261. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2262. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2263. const s = 1 - t;
  2264. this._w = s * w + t * this._w;
  2265. this._x = s * x + t * this._x;
  2266. this._y = s * y + t * this._y;
  2267. this._z = s * z + t * this._z;
  2268. this.normalize();
  2269. this._onChangeCallback();
  2270. return this;
  2271. }
  2272. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2273. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2274. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2275. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2276. this._w = ( w * ratioA + this._w * ratioB );
  2277. this._x = ( x * ratioA + this._x * ratioB );
  2278. this._y = ( y * ratioA + this._y * ratioB );
  2279. this._z = ( z * ratioA + this._z * ratioB );
  2280. this._onChangeCallback();
  2281. return this;
  2282. }
  2283. slerpQuaternions( qa, qb, t ) {
  2284. return this.copy( qa ).slerp( qb, t );
  2285. }
  2286. random() {
  2287. // Derived from http://planning.cs.uiuc.edu/node198.html
  2288. // Note, this source uses w, x, y, z ordering,
  2289. // so we swap the order below.
  2290. const u1 = Math.random();
  2291. const sqrt1u1 = Math.sqrt( 1 - u1 );
  2292. const sqrtu1 = Math.sqrt( u1 );
  2293. const u2 = 2 * Math.PI * Math.random();
  2294. const u3 = 2 * Math.PI * Math.random();
  2295. return this.set(
  2296. sqrt1u1 * Math.cos( u2 ),
  2297. sqrtu1 * Math.sin( u3 ),
  2298. sqrtu1 * Math.cos( u3 ),
  2299. sqrt1u1 * Math.sin( u2 ),
  2300. );
  2301. }
  2302. equals( quaternion ) {
  2303. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2304. }
  2305. fromArray( array, offset = 0 ) {
  2306. this._x = array[ offset ];
  2307. this._y = array[ offset + 1 ];
  2308. this._z = array[ offset + 2 ];
  2309. this._w = array[ offset + 3 ];
  2310. this._onChangeCallback();
  2311. return this;
  2312. }
  2313. toArray( array = [], offset = 0 ) {
  2314. array[ offset ] = this._x;
  2315. array[ offset + 1 ] = this._y;
  2316. array[ offset + 2 ] = this._z;
  2317. array[ offset + 3 ] = this._w;
  2318. return array;
  2319. }
  2320. fromBufferAttribute( attribute, index ) {
  2321. this._x = attribute.getX( index );
  2322. this._y = attribute.getY( index );
  2323. this._z = attribute.getZ( index );
  2324. this._w = attribute.getW( index );
  2325. return this;
  2326. }
  2327. toJSON() {
  2328. return this.toArray();
  2329. }
  2330. _onChange( callback ) {
  2331. this._onChangeCallback = callback;
  2332. return this;
  2333. }
  2334. _onChangeCallback() {}
  2335. *[ Symbol.iterator ]() {
  2336. yield this._x;
  2337. yield this._y;
  2338. yield this._z;
  2339. yield this._w;
  2340. }
  2341. }
  2342. class Vector3 {
  2343. constructor( x = 0, y = 0, z = 0 ) {
  2344. Vector3.prototype.isVector3 = true;
  2345. this.x = x;
  2346. this.y = y;
  2347. this.z = z;
  2348. }
  2349. set( x, y, z ) {
  2350. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2351. this.x = x;
  2352. this.y = y;
  2353. this.z = z;
  2354. return this;
  2355. }
  2356. setScalar( scalar ) {
  2357. this.x = scalar;
  2358. this.y = scalar;
  2359. this.z = scalar;
  2360. return this;
  2361. }
  2362. setX( x ) {
  2363. this.x = x;
  2364. return this;
  2365. }
  2366. setY( y ) {
  2367. this.y = y;
  2368. return this;
  2369. }
  2370. setZ( z ) {
  2371. this.z = z;
  2372. return this;
  2373. }
  2374. setComponent( index, value ) {
  2375. switch ( index ) {
  2376. case 0: this.x = value; break;
  2377. case 1: this.y = value; break;
  2378. case 2: this.z = value; break;
  2379. default: throw new Error( 'index is out of range: ' + index );
  2380. }
  2381. return this;
  2382. }
  2383. getComponent( index ) {
  2384. switch ( index ) {
  2385. case 0: return this.x;
  2386. case 1: return this.y;
  2387. case 2: return this.z;
  2388. default: throw new Error( 'index is out of range: ' + index );
  2389. }
  2390. }
  2391. clone() {
  2392. return new this.constructor( this.x, this.y, this.z );
  2393. }
  2394. copy( v ) {
  2395. this.x = v.x;
  2396. this.y = v.y;
  2397. this.z = v.z;
  2398. return this;
  2399. }
  2400. add( v ) {
  2401. this.x += v.x;
  2402. this.y += v.y;
  2403. this.z += v.z;
  2404. return this;
  2405. }
  2406. addScalar( s ) {
  2407. this.x += s;
  2408. this.y += s;
  2409. this.z += s;
  2410. return this;
  2411. }
  2412. addVectors( a, b ) {
  2413. this.x = a.x + b.x;
  2414. this.y = a.y + b.y;
  2415. this.z = a.z + b.z;
  2416. return this;
  2417. }
  2418. addScaledVector( v, s ) {
  2419. this.x += v.x * s;
  2420. this.y += v.y * s;
  2421. this.z += v.z * s;
  2422. return this;
  2423. }
  2424. sub( v ) {
  2425. this.x -= v.x;
  2426. this.y -= v.y;
  2427. this.z -= v.z;
  2428. return this;
  2429. }
  2430. subScalar( s ) {
  2431. this.x -= s;
  2432. this.y -= s;
  2433. this.z -= s;
  2434. return this;
  2435. }
  2436. subVectors( a, b ) {
  2437. this.x = a.x - b.x;
  2438. this.y = a.y - b.y;
  2439. this.z = a.z - b.z;
  2440. return this;
  2441. }
  2442. multiply( v ) {
  2443. this.x *= v.x;
  2444. this.y *= v.y;
  2445. this.z *= v.z;
  2446. return this;
  2447. }
  2448. multiplyScalar( scalar ) {
  2449. this.x *= scalar;
  2450. this.y *= scalar;
  2451. this.z *= scalar;
  2452. return this;
  2453. }
  2454. multiplyVectors( a, b ) {
  2455. this.x = a.x * b.x;
  2456. this.y = a.y * b.y;
  2457. this.z = a.z * b.z;
  2458. return this;
  2459. }
  2460. applyEuler( euler ) {
  2461. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2462. }
  2463. applyAxisAngle( axis, angle ) {
  2464. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2465. }
  2466. applyMatrix3( m ) {
  2467. const x = this.x, y = this.y, z = this.z;
  2468. const e = m.elements;
  2469. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2470. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2471. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2472. return this;
  2473. }
  2474. applyNormalMatrix( m ) {
  2475. return this.applyMatrix3( m ).normalize();
  2476. }
  2477. applyMatrix4( m ) {
  2478. const x = this.x, y = this.y, z = this.z;
  2479. const e = m.elements;
  2480. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2481. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2482. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2483. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2484. return this;
  2485. }
  2486. applyQuaternion( q ) {
  2487. const x = this.x, y = this.y, z = this.z;
  2488. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2489. // calculate quat * vector
  2490. const ix = qw * x + qy * z - qz * y;
  2491. const iy = qw * y + qz * x - qx * z;
  2492. const iz = qw * z + qx * y - qy * x;
  2493. const iw = - qx * x - qy * y - qz * z;
  2494. // calculate result * inverse quat
  2495. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  2496. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  2497. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  2498. return this;
  2499. }
  2500. project( camera ) {
  2501. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2502. }
  2503. unproject( camera ) {
  2504. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2505. }
  2506. transformDirection( m ) {
  2507. // input: THREE.Matrix4 affine matrix
  2508. // vector interpreted as a direction
  2509. const x = this.x, y = this.y, z = this.z;
  2510. const e = m.elements;
  2511. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2512. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2513. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2514. return this.normalize();
  2515. }
  2516. divide( v ) {
  2517. this.x /= v.x;
  2518. this.y /= v.y;
  2519. this.z /= v.z;
  2520. return this;
  2521. }
  2522. divideScalar( scalar ) {
  2523. return this.multiplyScalar( 1 / scalar );
  2524. }
  2525. min( v ) {
  2526. this.x = Math.min( this.x, v.x );
  2527. this.y = Math.min( this.y, v.y );
  2528. this.z = Math.min( this.z, v.z );
  2529. return this;
  2530. }
  2531. max( v ) {
  2532. this.x = Math.max( this.x, v.x );
  2533. this.y = Math.max( this.y, v.y );
  2534. this.z = Math.max( this.z, v.z );
  2535. return this;
  2536. }
  2537. clamp( min, max ) {
  2538. // assumes min < max, componentwise
  2539. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2540. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2541. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2542. return this;
  2543. }
  2544. clampScalar( minVal, maxVal ) {
  2545. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2546. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2547. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2548. return this;
  2549. }
  2550. clampLength( min, max ) {
  2551. const length = this.length();
  2552. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2553. }
  2554. floor() {
  2555. this.x = Math.floor( this.x );
  2556. this.y = Math.floor( this.y );
  2557. this.z = Math.floor( this.z );
  2558. return this;
  2559. }
  2560. ceil() {
  2561. this.x = Math.ceil( this.x );
  2562. this.y = Math.ceil( this.y );
  2563. this.z = Math.ceil( this.z );
  2564. return this;
  2565. }
  2566. round() {
  2567. this.x = Math.round( this.x );
  2568. this.y = Math.round( this.y );
  2569. this.z = Math.round( this.z );
  2570. return this;
  2571. }
  2572. roundToZero() {
  2573. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2574. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2575. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2576. return this;
  2577. }
  2578. negate() {
  2579. this.x = - this.x;
  2580. this.y = - this.y;
  2581. this.z = - this.z;
  2582. return this;
  2583. }
  2584. dot( v ) {
  2585. return this.x * v.x + this.y * v.y + this.z * v.z;
  2586. }
  2587. // TODO lengthSquared?
  2588. lengthSq() {
  2589. return this.x * this.x + this.y * this.y + this.z * this.z;
  2590. }
  2591. length() {
  2592. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2593. }
  2594. manhattanLength() {
  2595. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2596. }
  2597. normalize() {
  2598. return this.divideScalar( this.length() || 1 );
  2599. }
  2600. setLength( length ) {
  2601. return this.normalize().multiplyScalar( length );
  2602. }
  2603. lerp( v, alpha ) {
  2604. this.x += ( v.x - this.x ) * alpha;
  2605. this.y += ( v.y - this.y ) * alpha;
  2606. this.z += ( v.z - this.z ) * alpha;
  2607. return this;
  2608. }
  2609. lerpVectors( v1, v2, alpha ) {
  2610. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2611. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2612. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2613. return this;
  2614. }
  2615. cross( v ) {
  2616. return this.crossVectors( this, v );
  2617. }
  2618. crossVectors( a, b ) {
  2619. const ax = a.x, ay = a.y, az = a.z;
  2620. const bx = b.x, by = b.y, bz = b.z;
  2621. this.x = ay * bz - az * by;
  2622. this.y = az * bx - ax * bz;
  2623. this.z = ax * by - ay * bx;
  2624. return this;
  2625. }
  2626. projectOnVector( v ) {
  2627. const denominator = v.lengthSq();
  2628. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2629. const scalar = v.dot( this ) / denominator;
  2630. return this.copy( v ).multiplyScalar( scalar );
  2631. }
  2632. projectOnPlane( planeNormal ) {
  2633. _vector$b.copy( this ).projectOnVector( planeNormal );
  2634. return this.sub( _vector$b );
  2635. }
  2636. reflect( normal ) {
  2637. // reflect incident vector off plane orthogonal to normal
  2638. // normal is assumed to have unit length
  2639. return this.sub( _vector$b.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2640. }
  2641. angleTo( v ) {
  2642. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2643. if ( denominator === 0 ) return Math.PI / 2;
  2644. const theta = this.dot( v ) / denominator;
  2645. // clamp, to handle numerical problems
  2646. return Math.acos( clamp( theta, - 1, 1 ) );
  2647. }
  2648. distanceTo( v ) {
  2649. return Math.sqrt( this.distanceToSquared( v ) );
  2650. }
  2651. distanceToSquared( v ) {
  2652. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2653. return dx * dx + dy * dy + dz * dz;
  2654. }
  2655. manhattanDistanceTo( v ) {
  2656. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2657. }
  2658. setFromSpherical( s ) {
  2659. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2660. }
  2661. setFromSphericalCoords( radius, phi, theta ) {
  2662. const sinPhiRadius = Math.sin( phi ) * radius;
  2663. this.x = sinPhiRadius * Math.sin( theta );
  2664. this.y = Math.cos( phi ) * radius;
  2665. this.z = sinPhiRadius * Math.cos( theta );
  2666. return this;
  2667. }
  2668. setFromCylindrical( c ) {
  2669. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2670. }
  2671. setFromCylindricalCoords( radius, theta, y ) {
  2672. this.x = radius * Math.sin( theta );
  2673. this.y = y;
  2674. this.z = radius * Math.cos( theta );
  2675. return this;
  2676. }
  2677. setFromMatrixPosition( m ) {
  2678. const e = m.elements;
  2679. this.x = e[ 12 ];
  2680. this.y = e[ 13 ];
  2681. this.z = e[ 14 ];
  2682. return this;
  2683. }
  2684. setFromMatrixScale( m ) {
  2685. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2686. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2687. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2688. this.x = sx;
  2689. this.y = sy;
  2690. this.z = sz;
  2691. return this;
  2692. }
  2693. setFromMatrixColumn( m, index ) {
  2694. return this.fromArray( m.elements, index * 4 );
  2695. }
  2696. setFromMatrix3Column( m, index ) {
  2697. return this.fromArray( m.elements, index * 3 );
  2698. }
  2699. setFromEuler( e ) {
  2700. this.x = e._x;
  2701. this.y = e._y;
  2702. this.z = e._z;
  2703. return this;
  2704. }
  2705. setFromColor( c ) {
  2706. this.x = c.r;
  2707. this.y = c.g;
  2708. this.z = c.b;
  2709. return this;
  2710. }
  2711. equals( v ) {
  2712. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2713. }
  2714. fromArray( array, offset = 0 ) {
  2715. this.x = array[ offset ];
  2716. this.y = array[ offset + 1 ];
  2717. this.z = array[ offset + 2 ];
  2718. return this;
  2719. }
  2720. toArray( array = [], offset = 0 ) {
  2721. array[ offset ] = this.x;
  2722. array[ offset + 1 ] = this.y;
  2723. array[ offset + 2 ] = this.z;
  2724. return array;
  2725. }
  2726. fromBufferAttribute( attribute, index ) {
  2727. this.x = attribute.getX( index );
  2728. this.y = attribute.getY( index );
  2729. this.z = attribute.getZ( index );
  2730. return this;
  2731. }
  2732. random() {
  2733. this.x = Math.random();
  2734. this.y = Math.random();
  2735. this.z = Math.random();
  2736. return this;
  2737. }
  2738. randomDirection() {
  2739. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  2740. const u = ( Math.random() - 0.5 ) * 2;
  2741. const t = Math.random() * Math.PI * 2;
  2742. const f = Math.sqrt( 1 - u ** 2 );
  2743. this.x = f * Math.cos( t );
  2744. this.y = f * Math.sin( t );
  2745. this.z = u;
  2746. return this;
  2747. }
  2748. *[ Symbol.iterator ]() {
  2749. yield this.x;
  2750. yield this.y;
  2751. yield this.z;
  2752. }
  2753. }
  2754. const _vector$b = /*@__PURE__*/ new Vector3();
  2755. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2756. class Box3 {
  2757. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2758. this.isBox3 = true;
  2759. this.min = min;
  2760. this.max = max;
  2761. }
  2762. set( min, max ) {
  2763. this.min.copy( min );
  2764. this.max.copy( max );
  2765. return this;
  2766. }
  2767. setFromArray( array ) {
  2768. this.makeEmpty();
  2769. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  2770. this.expandByPoint( _vector$a.fromArray( array, i ) );
  2771. }
  2772. return this;
  2773. }
  2774. setFromBufferAttribute( attribute ) {
  2775. this.makeEmpty();
  2776. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  2777. this.expandByPoint( _vector$a.fromBufferAttribute( attribute, i ) );
  2778. }
  2779. return this;
  2780. }
  2781. setFromPoints( points ) {
  2782. this.makeEmpty();
  2783. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2784. this.expandByPoint( points[ i ] );
  2785. }
  2786. return this;
  2787. }
  2788. setFromCenterAndSize( center, size ) {
  2789. const halfSize = _vector$a.copy( size ).multiplyScalar( 0.5 );
  2790. this.min.copy( center ).sub( halfSize );
  2791. this.max.copy( center ).add( halfSize );
  2792. return this;
  2793. }
  2794. setFromObject( object, precise = false ) {
  2795. this.makeEmpty();
  2796. return this.expandByObject( object, precise );
  2797. }
  2798. clone() {
  2799. return new this.constructor().copy( this );
  2800. }
  2801. copy( box ) {
  2802. this.min.copy( box.min );
  2803. this.max.copy( box.max );
  2804. return this;
  2805. }
  2806. makeEmpty() {
  2807. this.min.x = this.min.y = this.min.z = + Infinity;
  2808. this.max.x = this.max.y = this.max.z = - Infinity;
  2809. return this;
  2810. }
  2811. isEmpty() {
  2812. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2813. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2814. }
  2815. getCenter( target ) {
  2816. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2817. }
  2818. getSize( target ) {
  2819. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2820. }
  2821. expandByPoint( point ) {
  2822. this.min.min( point );
  2823. this.max.max( point );
  2824. return this;
  2825. }
  2826. expandByVector( vector ) {
  2827. this.min.sub( vector );
  2828. this.max.add( vector );
  2829. return this;
  2830. }
  2831. expandByScalar( scalar ) {
  2832. this.min.addScalar( - scalar );
  2833. this.max.addScalar( scalar );
  2834. return this;
  2835. }
  2836. expandByObject( object, precise = false ) {
  2837. // Computes the world-axis-aligned bounding box of an object (including its children),
  2838. // accounting for both the object's, and children's, world transforms
  2839. object.updateWorldMatrix( false, false );
  2840. if ( object.boundingBox !== undefined ) {
  2841. if ( object.boundingBox === null ) {
  2842. object.computeBoundingBox();
  2843. }
  2844. _box$3.copy( object.boundingBox );
  2845. _box$3.applyMatrix4( object.matrixWorld );
  2846. this.union( _box$3 );
  2847. } else {
  2848. const geometry = object.geometry;
  2849. if ( geometry !== undefined ) {
  2850. if ( precise && geometry.attributes !== undefined && geometry.attributes.position !== undefined ) {
  2851. const position = geometry.attributes.position;
  2852. for ( let i = 0, l = position.count; i < l; i ++ ) {
  2853. _vector$a.fromBufferAttribute( position, i ).applyMatrix4( object.matrixWorld );
  2854. this.expandByPoint( _vector$a );
  2855. }
  2856. } else {
  2857. if ( geometry.boundingBox === null ) {
  2858. geometry.computeBoundingBox();
  2859. }
  2860. _box$3.copy( geometry.boundingBox );
  2861. _box$3.applyMatrix4( object.matrixWorld );
  2862. this.union( _box$3 );
  2863. }
  2864. }
  2865. }
  2866. const children = object.children;
  2867. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2868. this.expandByObject( children[ i ], precise );
  2869. }
  2870. return this;
  2871. }
  2872. containsPoint( point ) {
  2873. return point.x < this.min.x || point.x > this.max.x ||
  2874. point.y < this.min.y || point.y > this.max.y ||
  2875. point.z < this.min.z || point.z > this.max.z ? false : true;
  2876. }
  2877. containsBox( box ) {
  2878. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2879. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2880. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2881. }
  2882. getParameter( point, target ) {
  2883. // This can potentially have a divide by zero if the box
  2884. // has a size dimension of 0.
  2885. return target.set(
  2886. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2887. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2888. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2889. );
  2890. }
  2891. intersectsBox( box ) {
  2892. // using 6 splitting planes to rule out intersections.
  2893. return box.max.x < this.min.x || box.min.x > this.max.x ||
  2894. box.max.y < this.min.y || box.min.y > this.max.y ||
  2895. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  2896. }
  2897. intersectsSphere( sphere ) {
  2898. // Find the point on the AABB closest to the sphere center.
  2899. this.clampPoint( sphere.center, _vector$a );
  2900. // If that point is inside the sphere, the AABB and sphere intersect.
  2901. return _vector$a.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2902. }
  2903. intersectsPlane( plane ) {
  2904. // We compute the minimum and maximum dot product values. If those values
  2905. // are on the same side (back or front) of the plane, then there is no intersection.
  2906. let min, max;
  2907. if ( plane.normal.x > 0 ) {
  2908. min = plane.normal.x * this.min.x;
  2909. max = plane.normal.x * this.max.x;
  2910. } else {
  2911. min = plane.normal.x * this.max.x;
  2912. max = plane.normal.x * this.min.x;
  2913. }
  2914. if ( plane.normal.y > 0 ) {
  2915. min += plane.normal.y * this.min.y;
  2916. max += plane.normal.y * this.max.y;
  2917. } else {
  2918. min += plane.normal.y * this.max.y;
  2919. max += plane.normal.y * this.min.y;
  2920. }
  2921. if ( plane.normal.z > 0 ) {
  2922. min += plane.normal.z * this.min.z;
  2923. max += plane.normal.z * this.max.z;
  2924. } else {
  2925. min += plane.normal.z * this.max.z;
  2926. max += plane.normal.z * this.min.z;
  2927. }
  2928. return ( min <= - plane.constant && max >= - plane.constant );
  2929. }
  2930. intersectsTriangle( triangle ) {
  2931. if ( this.isEmpty() ) {
  2932. return false;
  2933. }
  2934. // compute box center and extents
  2935. this.getCenter( _center );
  2936. _extents.subVectors( this.max, _center );
  2937. // translate triangle to aabb origin
  2938. _v0$2.subVectors( triangle.a, _center );
  2939. _v1$7.subVectors( triangle.b, _center );
  2940. _v2$4.subVectors( triangle.c, _center );
  2941. // compute edge vectors for triangle
  2942. _f0.subVectors( _v1$7, _v0$2 );
  2943. _f1.subVectors( _v2$4, _v1$7 );
  2944. _f2.subVectors( _v0$2, _v2$4 );
  2945. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2946. // 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
  2947. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2948. let axes = [
  2949. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  2950. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  2951. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  2952. ];
  2953. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2954. return false;
  2955. }
  2956. // test 3 face normals from the aabb
  2957. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  2958. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2959. return false;
  2960. }
  2961. // finally testing the face normal of the triangle
  2962. // use already existing triangle edge vectors here
  2963. _triangleNormal.crossVectors( _f0, _f1 );
  2964. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  2965. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  2966. }
  2967. clampPoint( point, target ) {
  2968. return target.copy( point ).clamp( this.min, this.max );
  2969. }
  2970. distanceToPoint( point ) {
  2971. return this.clampPoint( point, _vector$a ).distanceTo( point );
  2972. }
  2973. getBoundingSphere( target ) {
  2974. if ( this.isEmpty() ) {
  2975. target.makeEmpty();
  2976. } else {
  2977. this.getCenter( target.center );
  2978. target.radius = this.getSize( _vector$a ).length() * 0.5;
  2979. }
  2980. return target;
  2981. }
  2982. intersect( box ) {
  2983. this.min.max( box.min );
  2984. this.max.min( box.max );
  2985. // 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.
  2986. if ( this.isEmpty() ) this.makeEmpty();
  2987. return this;
  2988. }
  2989. union( box ) {
  2990. this.min.min( box.min );
  2991. this.max.max( box.max );
  2992. return this;
  2993. }
  2994. applyMatrix4( matrix ) {
  2995. // transform of empty box is an empty box.
  2996. if ( this.isEmpty() ) return this;
  2997. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2998. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2999. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3000. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3001. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3002. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3003. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3004. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3005. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3006. this.setFromPoints( _points );
  3007. return this;
  3008. }
  3009. translate( offset ) {
  3010. this.min.add( offset );
  3011. this.max.add( offset );
  3012. return this;
  3013. }
  3014. equals( box ) {
  3015. return box.min.equals( this.min ) && box.max.equals( this.max );
  3016. }
  3017. }
  3018. const _points = [
  3019. /*@__PURE__*/ new Vector3(),
  3020. /*@__PURE__*/ new Vector3(),
  3021. /*@__PURE__*/ new Vector3(),
  3022. /*@__PURE__*/ new Vector3(),
  3023. /*@__PURE__*/ new Vector3(),
  3024. /*@__PURE__*/ new Vector3(),
  3025. /*@__PURE__*/ new Vector3(),
  3026. /*@__PURE__*/ new Vector3()
  3027. ];
  3028. const _vector$a = /*@__PURE__*/ new Vector3();
  3029. const _box$3 = /*@__PURE__*/ new Box3();
  3030. // triangle centered vertices
  3031. const _v0$2 = /*@__PURE__*/ new Vector3();
  3032. const _v1$7 = /*@__PURE__*/ new Vector3();
  3033. const _v2$4 = /*@__PURE__*/ new Vector3();
  3034. // triangle edge vectors
  3035. const _f0 = /*@__PURE__*/ new Vector3();
  3036. const _f1 = /*@__PURE__*/ new Vector3();
  3037. const _f2 = /*@__PURE__*/ new Vector3();
  3038. const _center = /*@__PURE__*/ new Vector3();
  3039. const _extents = /*@__PURE__*/ new Vector3();
  3040. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3041. const _testAxis = /*@__PURE__*/ new Vector3();
  3042. function satForAxes( axes, v0, v1, v2, extents ) {
  3043. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3044. _testAxis.fromArray( axes, i );
  3045. // project the aabb onto the separating axis
  3046. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3047. // project all 3 vertices of the triangle onto the separating axis
  3048. const p0 = v0.dot( _testAxis );
  3049. const p1 = v1.dot( _testAxis );
  3050. const p2 = v2.dot( _testAxis );
  3051. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3052. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3053. // points of the projected triangle are outside the projected half-length of the aabb
  3054. // the axis is separating and we can exit
  3055. return false;
  3056. }
  3057. }
  3058. return true;
  3059. }
  3060. const _box$2 = /*@__PURE__*/ new Box3();
  3061. const _v1$6 = /*@__PURE__*/ new Vector3();
  3062. const _v2$3 = /*@__PURE__*/ new Vector3();
  3063. class Sphere {
  3064. constructor( center = new Vector3(), radius = - 1 ) {
  3065. this.center = center;
  3066. this.radius = radius;
  3067. }
  3068. set( center, radius ) {
  3069. this.center.copy( center );
  3070. this.radius = radius;
  3071. return this;
  3072. }
  3073. setFromPoints( points, optionalCenter ) {
  3074. const center = this.center;
  3075. if ( optionalCenter !== undefined ) {
  3076. center.copy( optionalCenter );
  3077. } else {
  3078. _box$2.setFromPoints( points ).getCenter( center );
  3079. }
  3080. let maxRadiusSq = 0;
  3081. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3082. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3083. }
  3084. this.radius = Math.sqrt( maxRadiusSq );
  3085. return this;
  3086. }
  3087. copy( sphere ) {
  3088. this.center.copy( sphere.center );
  3089. this.radius = sphere.radius;
  3090. return this;
  3091. }
  3092. isEmpty() {
  3093. return ( this.radius < 0 );
  3094. }
  3095. makeEmpty() {
  3096. this.center.set( 0, 0, 0 );
  3097. this.radius = - 1;
  3098. return this;
  3099. }
  3100. containsPoint( point ) {
  3101. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3102. }
  3103. distanceToPoint( point ) {
  3104. return ( point.distanceTo( this.center ) - this.radius );
  3105. }
  3106. intersectsSphere( sphere ) {
  3107. const radiusSum = this.radius + sphere.radius;
  3108. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3109. }
  3110. intersectsBox( box ) {
  3111. return box.intersectsSphere( this );
  3112. }
  3113. intersectsPlane( plane ) {
  3114. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3115. }
  3116. clampPoint( point, target ) {
  3117. const deltaLengthSq = this.center.distanceToSquared( point );
  3118. target.copy( point );
  3119. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3120. target.sub( this.center ).normalize();
  3121. target.multiplyScalar( this.radius ).add( this.center );
  3122. }
  3123. return target;
  3124. }
  3125. getBoundingBox( target ) {
  3126. if ( this.isEmpty() ) {
  3127. // Empty sphere produces empty bounding box
  3128. target.makeEmpty();
  3129. return target;
  3130. }
  3131. target.set( this.center, this.center );
  3132. target.expandByScalar( this.radius );
  3133. return target;
  3134. }
  3135. applyMatrix4( matrix ) {
  3136. this.center.applyMatrix4( matrix );
  3137. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3138. return this;
  3139. }
  3140. translate( offset ) {
  3141. this.center.add( offset );
  3142. return this;
  3143. }
  3144. expandByPoint( point ) {
  3145. if ( this.isEmpty() ) {
  3146. this.center.copy( point );
  3147. this.radius = 0;
  3148. return this;
  3149. }
  3150. _v1$6.subVectors( point, this.center );
  3151. const lengthSq = _v1$6.lengthSq();
  3152. if ( lengthSq > ( this.radius * this.radius ) ) {
  3153. // calculate the minimal sphere
  3154. const length = Math.sqrt( lengthSq );
  3155. const delta = ( length - this.radius ) * 0.5;
  3156. this.center.addScaledVector( _v1$6, delta / length );
  3157. this.radius += delta;
  3158. }
  3159. return this;
  3160. }
  3161. union( sphere ) {
  3162. if ( sphere.isEmpty() ) {
  3163. return this;
  3164. }
  3165. if ( this.isEmpty() ) {
  3166. this.copy( sphere );
  3167. return this;
  3168. }
  3169. if ( this.center.equals( sphere.center ) === true ) {
  3170. this.radius = Math.max( this.radius, sphere.radius );
  3171. } else {
  3172. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3173. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3174. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3175. }
  3176. return this;
  3177. }
  3178. equals( sphere ) {
  3179. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3180. }
  3181. clone() {
  3182. return new this.constructor().copy( this );
  3183. }
  3184. }
  3185. const _vector$9 = /*@__PURE__*/ new Vector3();
  3186. const _segCenter = /*@__PURE__*/ new Vector3();
  3187. const _segDir = /*@__PURE__*/ new Vector3();
  3188. const _diff = /*@__PURE__*/ new Vector3();
  3189. const _edge1 = /*@__PURE__*/ new Vector3();
  3190. const _edge2 = /*@__PURE__*/ new Vector3();
  3191. const _normal$1 = /*@__PURE__*/ new Vector3();
  3192. class Ray {
  3193. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3194. this.origin = origin;
  3195. this.direction = direction;
  3196. }
  3197. set( origin, direction ) {
  3198. this.origin.copy( origin );
  3199. this.direction.copy( direction );
  3200. return this;
  3201. }
  3202. copy( ray ) {
  3203. this.origin.copy( ray.origin );
  3204. this.direction.copy( ray.direction );
  3205. return this;
  3206. }
  3207. at( t, target ) {
  3208. return target.copy( this.origin ).addScaledVector( this.direction, t );
  3209. }
  3210. lookAt( v ) {
  3211. this.direction.copy( v ).sub( this.origin ).normalize();
  3212. return this;
  3213. }
  3214. recast( t ) {
  3215. this.origin.copy( this.at( t, _vector$9 ) );
  3216. return this;
  3217. }
  3218. closestPointToPoint( point, target ) {
  3219. target.subVectors( point, this.origin );
  3220. const directionDistance = target.dot( this.direction );
  3221. if ( directionDistance < 0 ) {
  3222. return target.copy( this.origin );
  3223. }
  3224. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3225. }
  3226. distanceToPoint( point ) {
  3227. return Math.sqrt( this.distanceSqToPoint( point ) );
  3228. }
  3229. distanceSqToPoint( point ) {
  3230. const directionDistance = _vector$9.subVectors( point, this.origin ).dot( this.direction );
  3231. // point behind the ray
  3232. if ( directionDistance < 0 ) {
  3233. return this.origin.distanceToSquared( point );
  3234. }
  3235. _vector$9.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3236. return _vector$9.distanceToSquared( point );
  3237. }
  3238. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3239. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3240. // It returns the min distance between the ray and the segment
  3241. // defined by v0 and v1
  3242. // It can also set two optional targets :
  3243. // - The closest point on the ray
  3244. // - The closest point on the segment
  3245. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3246. _segDir.copy( v1 ).sub( v0 ).normalize();
  3247. _diff.copy( this.origin ).sub( _segCenter );
  3248. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3249. const a01 = - this.direction.dot( _segDir );
  3250. const b0 = _diff.dot( this.direction );
  3251. const b1 = - _diff.dot( _segDir );
  3252. const c = _diff.lengthSq();
  3253. const det = Math.abs( 1 - a01 * a01 );
  3254. let s0, s1, sqrDist, extDet;
  3255. if ( det > 0 ) {
  3256. // The ray and segment are not parallel.
  3257. s0 = a01 * b1 - b0;
  3258. s1 = a01 * b0 - b1;
  3259. extDet = segExtent * det;
  3260. if ( s0 >= 0 ) {
  3261. if ( s1 >= - extDet ) {
  3262. if ( s1 <= extDet ) {
  3263. // region 0
  3264. // Minimum at interior points of ray and segment.
  3265. const invDet = 1 / det;
  3266. s0 *= invDet;
  3267. s1 *= invDet;
  3268. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3269. } else {
  3270. // region 1
  3271. s1 = segExtent;
  3272. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3273. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3274. }
  3275. } else {
  3276. // region 5
  3277. s1 = - segExtent;
  3278. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3279. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3280. }
  3281. } else {
  3282. if ( s1 <= - extDet ) {
  3283. // region 4
  3284. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3285. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3286. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3287. } else if ( s1 <= extDet ) {
  3288. // region 3
  3289. s0 = 0;
  3290. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3291. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3292. } else {
  3293. // region 2
  3294. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3295. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3296. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3297. }
  3298. }
  3299. } else {
  3300. // Ray and segment are parallel.
  3301. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3302. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3303. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3304. }
  3305. if ( optionalPointOnRay ) {
  3306. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  3307. }
  3308. if ( optionalPointOnSegment ) {
  3309. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  3310. }
  3311. return sqrDist;
  3312. }
  3313. intersectSphere( sphere, target ) {
  3314. _vector$9.subVectors( sphere.center, this.origin );
  3315. const tca = _vector$9.dot( this.direction );
  3316. const d2 = _vector$9.dot( _vector$9 ) - tca * tca;
  3317. const radius2 = sphere.radius * sphere.radius;
  3318. if ( d2 > radius2 ) return null;
  3319. const thc = Math.sqrt( radius2 - d2 );
  3320. // t0 = first intersect point - entrance on front of sphere
  3321. const t0 = tca - thc;
  3322. // t1 = second intersect point - exit point on back of sphere
  3323. const t1 = tca + thc;
  3324. // test to see if t1 is behind the ray - if so, return null
  3325. if ( t1 < 0 ) return null;
  3326. // test to see if t0 is behind the ray:
  3327. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3328. // in order to always return an intersect point that is in front of the ray.
  3329. if ( t0 < 0 ) return this.at( t1, target );
  3330. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3331. return this.at( t0, target );
  3332. }
  3333. intersectsSphere( sphere ) {
  3334. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3335. }
  3336. distanceToPlane( plane ) {
  3337. const denominator = plane.normal.dot( this.direction );
  3338. if ( denominator === 0 ) {
  3339. // line is coplanar, return origin
  3340. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3341. return 0;
  3342. }
  3343. // Null is preferable to undefined since undefined means.... it is undefined
  3344. return null;
  3345. }
  3346. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3347. // Return if the ray never intersects the plane
  3348. return t >= 0 ? t : null;
  3349. }
  3350. intersectPlane( plane, target ) {
  3351. const t = this.distanceToPlane( plane );
  3352. if ( t === null ) {
  3353. return null;
  3354. }
  3355. return this.at( t, target );
  3356. }
  3357. intersectsPlane( plane ) {
  3358. // check if the ray lies on the plane first
  3359. const distToPoint = plane.distanceToPoint( this.origin );
  3360. if ( distToPoint === 0 ) {
  3361. return true;
  3362. }
  3363. const denominator = plane.normal.dot( this.direction );
  3364. if ( denominator * distToPoint < 0 ) {
  3365. return true;
  3366. }
  3367. // ray origin is behind the plane (and is pointing behind it)
  3368. return false;
  3369. }
  3370. intersectBox( box, target ) {
  3371. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3372. const invdirx = 1 / this.direction.x,
  3373. invdiry = 1 / this.direction.y,
  3374. invdirz = 1 / this.direction.z;
  3375. const origin = this.origin;
  3376. if ( invdirx >= 0 ) {
  3377. tmin = ( box.min.x - origin.x ) * invdirx;
  3378. tmax = ( box.max.x - origin.x ) * invdirx;
  3379. } else {
  3380. tmin = ( box.max.x - origin.x ) * invdirx;
  3381. tmax = ( box.min.x - origin.x ) * invdirx;
  3382. }
  3383. if ( invdiry >= 0 ) {
  3384. tymin = ( box.min.y - origin.y ) * invdiry;
  3385. tymax = ( box.max.y - origin.y ) * invdiry;
  3386. } else {
  3387. tymin = ( box.max.y - origin.y ) * invdiry;
  3388. tymax = ( box.min.y - origin.y ) * invdiry;
  3389. }
  3390. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3391. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3392. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3393. if ( invdirz >= 0 ) {
  3394. tzmin = ( box.min.z - origin.z ) * invdirz;
  3395. tzmax = ( box.max.z - origin.z ) * invdirz;
  3396. } else {
  3397. tzmin = ( box.max.z - origin.z ) * invdirz;
  3398. tzmax = ( box.min.z - origin.z ) * invdirz;
  3399. }
  3400. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3401. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3402. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3403. //return point closest to the ray (positive side)
  3404. if ( tmax < 0 ) return null;
  3405. return this.at( tmin >= 0 ? tmin : tmax, target );
  3406. }
  3407. intersectsBox( box ) {
  3408. return this.intersectBox( box, _vector$9 ) !== null;
  3409. }
  3410. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3411. // Compute the offset origin, edges, and normal.
  3412. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3413. _edge1.subVectors( b, a );
  3414. _edge2.subVectors( c, a );
  3415. _normal$1.crossVectors( _edge1, _edge2 );
  3416. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3417. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3418. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3419. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3420. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3421. let DdN = this.direction.dot( _normal$1 );
  3422. let sign;
  3423. if ( DdN > 0 ) {
  3424. if ( backfaceCulling ) return null;
  3425. sign = 1;
  3426. } else if ( DdN < 0 ) {
  3427. sign = - 1;
  3428. DdN = - DdN;
  3429. } else {
  3430. return null;
  3431. }
  3432. _diff.subVectors( this.origin, a );
  3433. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3434. // b1 < 0, no intersection
  3435. if ( DdQxE2 < 0 ) {
  3436. return null;
  3437. }
  3438. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3439. // b2 < 0, no intersection
  3440. if ( DdE1xQ < 0 ) {
  3441. return null;
  3442. }
  3443. // b1+b2 > 1, no intersection
  3444. if ( DdQxE2 + DdE1xQ > DdN ) {
  3445. return null;
  3446. }
  3447. // Line intersects triangle, check if ray does.
  3448. const QdN = - sign * _diff.dot( _normal$1 );
  3449. // t < 0, no intersection
  3450. if ( QdN < 0 ) {
  3451. return null;
  3452. }
  3453. // Ray intersects triangle.
  3454. return this.at( QdN / DdN, target );
  3455. }
  3456. applyMatrix4( matrix4 ) {
  3457. this.origin.applyMatrix4( matrix4 );
  3458. this.direction.transformDirection( matrix4 );
  3459. return this;
  3460. }
  3461. equals( ray ) {
  3462. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3463. }
  3464. clone() {
  3465. return new this.constructor().copy( this );
  3466. }
  3467. }
  3468. class Matrix4 {
  3469. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3470. Matrix4.prototype.isMatrix4 = true;
  3471. this.elements = [
  3472. 1, 0, 0, 0,
  3473. 0, 1, 0, 0,
  3474. 0, 0, 1, 0,
  3475. 0, 0, 0, 1
  3476. ];
  3477. if ( n11 !== undefined ) {
  3478. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  3479. }
  3480. }
  3481. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3482. const te = this.elements;
  3483. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3484. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3485. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3486. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3487. return this;
  3488. }
  3489. identity() {
  3490. this.set(
  3491. 1, 0, 0, 0,
  3492. 0, 1, 0, 0,
  3493. 0, 0, 1, 0,
  3494. 0, 0, 0, 1
  3495. );
  3496. return this;
  3497. }
  3498. clone() {
  3499. return new Matrix4().fromArray( this.elements );
  3500. }
  3501. copy( m ) {
  3502. const te = this.elements;
  3503. const me = m.elements;
  3504. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3505. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3506. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3507. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3508. return this;
  3509. }
  3510. copyPosition( m ) {
  3511. const te = this.elements, me = m.elements;
  3512. te[ 12 ] = me[ 12 ];
  3513. te[ 13 ] = me[ 13 ];
  3514. te[ 14 ] = me[ 14 ];
  3515. return this;
  3516. }
  3517. setFromMatrix3( m ) {
  3518. const me = m.elements;
  3519. this.set(
  3520. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3521. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3522. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3523. 0, 0, 0, 1
  3524. );
  3525. return this;
  3526. }
  3527. extractBasis( xAxis, yAxis, zAxis ) {
  3528. xAxis.setFromMatrixColumn( this, 0 );
  3529. yAxis.setFromMatrixColumn( this, 1 );
  3530. zAxis.setFromMatrixColumn( this, 2 );
  3531. return this;
  3532. }
  3533. makeBasis( xAxis, yAxis, zAxis ) {
  3534. this.set(
  3535. xAxis.x, yAxis.x, zAxis.x, 0,
  3536. xAxis.y, yAxis.y, zAxis.y, 0,
  3537. xAxis.z, yAxis.z, zAxis.z, 0,
  3538. 0, 0, 0, 1
  3539. );
  3540. return this;
  3541. }
  3542. extractRotation( m ) {
  3543. // this method does not support reflection matrices
  3544. const te = this.elements;
  3545. const me = m.elements;
  3546. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3547. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3548. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3549. te[ 0 ] = me[ 0 ] * scaleX;
  3550. te[ 1 ] = me[ 1 ] * scaleX;
  3551. te[ 2 ] = me[ 2 ] * scaleX;
  3552. te[ 3 ] = 0;
  3553. te[ 4 ] = me[ 4 ] * scaleY;
  3554. te[ 5 ] = me[ 5 ] * scaleY;
  3555. te[ 6 ] = me[ 6 ] * scaleY;
  3556. te[ 7 ] = 0;
  3557. te[ 8 ] = me[ 8 ] * scaleZ;
  3558. te[ 9 ] = me[ 9 ] * scaleZ;
  3559. te[ 10 ] = me[ 10 ] * scaleZ;
  3560. te[ 11 ] = 0;
  3561. te[ 12 ] = 0;
  3562. te[ 13 ] = 0;
  3563. te[ 14 ] = 0;
  3564. te[ 15 ] = 1;
  3565. return this;
  3566. }
  3567. makeRotationFromEuler( euler ) {
  3568. const te = this.elements;
  3569. const x = euler.x, y = euler.y, z = euler.z;
  3570. const a = Math.cos( x ), b = Math.sin( x );
  3571. const c = Math.cos( y ), d = Math.sin( y );
  3572. const e = Math.cos( z ), f = Math.sin( z );
  3573. if ( euler.order === 'XYZ' ) {
  3574. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3575. te[ 0 ] = c * e;
  3576. te[ 4 ] = - c * f;
  3577. te[ 8 ] = d;
  3578. te[ 1 ] = af + be * d;
  3579. te[ 5 ] = ae - bf * d;
  3580. te[ 9 ] = - b * c;
  3581. te[ 2 ] = bf - ae * d;
  3582. te[ 6 ] = be + af * d;
  3583. te[ 10 ] = a * c;
  3584. } else if ( euler.order === 'YXZ' ) {
  3585. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3586. te[ 0 ] = ce + df * b;
  3587. te[ 4 ] = de * b - cf;
  3588. te[ 8 ] = a * d;
  3589. te[ 1 ] = a * f;
  3590. te[ 5 ] = a * e;
  3591. te[ 9 ] = - b;
  3592. te[ 2 ] = cf * b - de;
  3593. te[ 6 ] = df + ce * b;
  3594. te[ 10 ] = a * c;
  3595. } else if ( euler.order === 'ZXY' ) {
  3596. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3597. te[ 0 ] = ce - df * b;
  3598. te[ 4 ] = - a * f;
  3599. te[ 8 ] = de + cf * b;
  3600. te[ 1 ] = cf + de * b;
  3601. te[ 5 ] = a * e;
  3602. te[ 9 ] = df - ce * b;
  3603. te[ 2 ] = - a * d;
  3604. te[ 6 ] = b;
  3605. te[ 10 ] = a * c;
  3606. } else if ( euler.order === 'ZYX' ) {
  3607. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3608. te[ 0 ] = c * e;
  3609. te[ 4 ] = be * d - af;
  3610. te[ 8 ] = ae * d + bf;
  3611. te[ 1 ] = c * f;
  3612. te[ 5 ] = bf * d + ae;
  3613. te[ 9 ] = af * d - be;
  3614. te[ 2 ] = - d;
  3615. te[ 6 ] = b * c;
  3616. te[ 10 ] = a * c;
  3617. } else if ( euler.order === 'YZX' ) {
  3618. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3619. te[ 0 ] = c * e;
  3620. te[ 4 ] = bd - ac * f;
  3621. te[ 8 ] = bc * f + ad;
  3622. te[ 1 ] = f;
  3623. te[ 5 ] = a * e;
  3624. te[ 9 ] = - b * e;
  3625. te[ 2 ] = - d * e;
  3626. te[ 6 ] = ad * f + bc;
  3627. te[ 10 ] = ac - bd * f;
  3628. } else if ( euler.order === 'XZY' ) {
  3629. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3630. te[ 0 ] = c * e;
  3631. te[ 4 ] = - f;
  3632. te[ 8 ] = d * e;
  3633. te[ 1 ] = ac * f + bd;
  3634. te[ 5 ] = a * e;
  3635. te[ 9 ] = ad * f - bc;
  3636. te[ 2 ] = bc * f - ad;
  3637. te[ 6 ] = b * e;
  3638. te[ 10 ] = bd * f + ac;
  3639. }
  3640. // bottom row
  3641. te[ 3 ] = 0;
  3642. te[ 7 ] = 0;
  3643. te[ 11 ] = 0;
  3644. // last column
  3645. te[ 12 ] = 0;
  3646. te[ 13 ] = 0;
  3647. te[ 14 ] = 0;
  3648. te[ 15 ] = 1;
  3649. return this;
  3650. }
  3651. makeRotationFromQuaternion( q ) {
  3652. return this.compose( _zero, q, _one );
  3653. }
  3654. lookAt( eye, target, up ) {
  3655. const te = this.elements;
  3656. _z.subVectors( eye, target );
  3657. if ( _z.lengthSq() === 0 ) {
  3658. // eye and target are in the same position
  3659. _z.z = 1;
  3660. }
  3661. _z.normalize();
  3662. _x.crossVectors( up, _z );
  3663. if ( _x.lengthSq() === 0 ) {
  3664. // up and z are parallel
  3665. if ( Math.abs( up.z ) === 1 ) {
  3666. _z.x += 0.0001;
  3667. } else {
  3668. _z.z += 0.0001;
  3669. }
  3670. _z.normalize();
  3671. _x.crossVectors( up, _z );
  3672. }
  3673. _x.normalize();
  3674. _y.crossVectors( _z, _x );
  3675. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3676. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3677. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3678. return this;
  3679. }
  3680. multiply( m ) {
  3681. return this.multiplyMatrices( this, m );
  3682. }
  3683. premultiply( m ) {
  3684. return this.multiplyMatrices( m, this );
  3685. }
  3686. multiplyMatrices( a, b ) {
  3687. const ae = a.elements;
  3688. const be = b.elements;
  3689. const te = this.elements;
  3690. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3691. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3692. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3693. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3694. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3695. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3696. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3697. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3698. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3699. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3700. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3701. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3702. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3703. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3704. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3705. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3706. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3707. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3708. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3709. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3710. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3711. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3712. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3713. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3714. return this;
  3715. }
  3716. multiplyScalar( s ) {
  3717. const te = this.elements;
  3718. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3719. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3720. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3721. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3722. return this;
  3723. }
  3724. determinant() {
  3725. const te = this.elements;
  3726. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3727. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3728. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3729. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3730. //TODO: make this more efficient
  3731. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3732. return (
  3733. n41 * (
  3734. + n14 * n23 * n32
  3735. - n13 * n24 * n32
  3736. - n14 * n22 * n33
  3737. + n12 * n24 * n33
  3738. + n13 * n22 * n34
  3739. - n12 * n23 * n34
  3740. ) +
  3741. n42 * (
  3742. + n11 * n23 * n34
  3743. - n11 * n24 * n33
  3744. + n14 * n21 * n33
  3745. - n13 * n21 * n34
  3746. + n13 * n24 * n31
  3747. - n14 * n23 * n31
  3748. ) +
  3749. n43 * (
  3750. + n11 * n24 * n32
  3751. - n11 * n22 * n34
  3752. - n14 * n21 * n32
  3753. + n12 * n21 * n34
  3754. + n14 * n22 * n31
  3755. - n12 * n24 * n31
  3756. ) +
  3757. n44 * (
  3758. - n13 * n22 * n31
  3759. - n11 * n23 * n32
  3760. + n11 * n22 * n33
  3761. + n13 * n21 * n32
  3762. - n12 * n21 * n33
  3763. + n12 * n23 * n31
  3764. )
  3765. );
  3766. }
  3767. transpose() {
  3768. const te = this.elements;
  3769. let tmp;
  3770. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3771. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3772. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3773. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3774. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3775. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3776. return this;
  3777. }
  3778. setPosition( x, y, z ) {
  3779. const te = this.elements;
  3780. if ( x.isVector3 ) {
  3781. te[ 12 ] = x.x;
  3782. te[ 13 ] = x.y;
  3783. te[ 14 ] = x.z;
  3784. } else {
  3785. te[ 12 ] = x;
  3786. te[ 13 ] = y;
  3787. te[ 14 ] = z;
  3788. }
  3789. return this;
  3790. }
  3791. invert() {
  3792. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3793. const te = this.elements,
  3794. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3795. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3796. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3797. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3798. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3799. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3800. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3801. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3802. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3803. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3804. const detInv = 1 / det;
  3805. te[ 0 ] = t11 * detInv;
  3806. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3807. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3808. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3809. te[ 4 ] = t12 * detInv;
  3810. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3811. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3812. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3813. te[ 8 ] = t13 * detInv;
  3814. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3815. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3816. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3817. te[ 12 ] = t14 * detInv;
  3818. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3819. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3820. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3821. return this;
  3822. }
  3823. scale( v ) {
  3824. const te = this.elements;
  3825. const x = v.x, y = v.y, z = v.z;
  3826. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3827. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3828. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3829. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3830. return this;
  3831. }
  3832. getMaxScaleOnAxis() {
  3833. const te = this.elements;
  3834. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3835. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3836. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3837. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3838. }
  3839. makeTranslation( x, y, z ) {
  3840. if ( x.isVector3 ) {
  3841. this.set(
  3842. 1, 0, 0, x.x,
  3843. 0, 1, 0, x.y,
  3844. 0, 0, 1, x.z,
  3845. 0, 0, 0, 1
  3846. );
  3847. } else {
  3848. this.set(
  3849. 1, 0, 0, x,
  3850. 0, 1, 0, y,
  3851. 0, 0, 1, z,
  3852. 0, 0, 0, 1
  3853. );
  3854. }
  3855. return this;
  3856. }
  3857. makeRotationX( theta ) {
  3858. const c = Math.cos( theta ), s = Math.sin( theta );
  3859. this.set(
  3860. 1, 0, 0, 0,
  3861. 0, c, - s, 0,
  3862. 0, s, c, 0,
  3863. 0, 0, 0, 1
  3864. );
  3865. return this;
  3866. }
  3867. makeRotationY( theta ) {
  3868. const c = Math.cos( theta ), s = Math.sin( theta );
  3869. this.set(
  3870. c, 0, s, 0,
  3871. 0, 1, 0, 0,
  3872. - s, 0, c, 0,
  3873. 0, 0, 0, 1
  3874. );
  3875. return this;
  3876. }
  3877. makeRotationZ( theta ) {
  3878. const c = Math.cos( theta ), s = Math.sin( theta );
  3879. this.set(
  3880. c, - s, 0, 0,
  3881. s, c, 0, 0,
  3882. 0, 0, 1, 0,
  3883. 0, 0, 0, 1
  3884. );
  3885. return this;
  3886. }
  3887. makeRotationAxis( axis, angle ) {
  3888. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3889. const c = Math.cos( angle );
  3890. const s = Math.sin( angle );
  3891. const t = 1 - c;
  3892. const x = axis.x, y = axis.y, z = axis.z;
  3893. const tx = t * x, ty = t * y;
  3894. this.set(
  3895. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3896. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3897. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3898. 0, 0, 0, 1
  3899. );
  3900. return this;
  3901. }
  3902. makeScale( x, y, z ) {
  3903. this.set(
  3904. x, 0, 0, 0,
  3905. 0, y, 0, 0,
  3906. 0, 0, z, 0,
  3907. 0, 0, 0, 1
  3908. );
  3909. return this;
  3910. }
  3911. makeShear( xy, xz, yx, yz, zx, zy ) {
  3912. this.set(
  3913. 1, yx, zx, 0,
  3914. xy, 1, zy, 0,
  3915. xz, yz, 1, 0,
  3916. 0, 0, 0, 1
  3917. );
  3918. return this;
  3919. }
  3920. compose( position, quaternion, scale ) {
  3921. const te = this.elements;
  3922. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3923. const x2 = x + x, y2 = y + y, z2 = z + z;
  3924. const xx = x * x2, xy = x * y2, xz = x * z2;
  3925. const yy = y * y2, yz = y * z2, zz = z * z2;
  3926. const wx = w * x2, wy = w * y2, wz = w * z2;
  3927. const sx = scale.x, sy = scale.y, sz = scale.z;
  3928. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3929. te[ 1 ] = ( xy + wz ) * sx;
  3930. te[ 2 ] = ( xz - wy ) * sx;
  3931. te[ 3 ] = 0;
  3932. te[ 4 ] = ( xy - wz ) * sy;
  3933. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3934. te[ 6 ] = ( yz + wx ) * sy;
  3935. te[ 7 ] = 0;
  3936. te[ 8 ] = ( xz + wy ) * sz;
  3937. te[ 9 ] = ( yz - wx ) * sz;
  3938. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3939. te[ 11 ] = 0;
  3940. te[ 12 ] = position.x;
  3941. te[ 13 ] = position.y;
  3942. te[ 14 ] = position.z;
  3943. te[ 15 ] = 1;
  3944. return this;
  3945. }
  3946. decompose( position, quaternion, scale ) {
  3947. const te = this.elements;
  3948. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3949. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3950. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3951. // if determine is negative, we need to invert one scale
  3952. const det = this.determinant();
  3953. if ( det < 0 ) sx = - sx;
  3954. position.x = te[ 12 ];
  3955. position.y = te[ 13 ];
  3956. position.z = te[ 14 ];
  3957. // scale the rotation part
  3958. _m1$2.copy( this );
  3959. const invSX = 1 / sx;
  3960. const invSY = 1 / sy;
  3961. const invSZ = 1 / sz;
  3962. _m1$2.elements[ 0 ] *= invSX;
  3963. _m1$2.elements[ 1 ] *= invSX;
  3964. _m1$2.elements[ 2 ] *= invSX;
  3965. _m1$2.elements[ 4 ] *= invSY;
  3966. _m1$2.elements[ 5 ] *= invSY;
  3967. _m1$2.elements[ 6 ] *= invSY;
  3968. _m1$2.elements[ 8 ] *= invSZ;
  3969. _m1$2.elements[ 9 ] *= invSZ;
  3970. _m1$2.elements[ 10 ] *= invSZ;
  3971. quaternion.setFromRotationMatrix( _m1$2 );
  3972. scale.x = sx;
  3973. scale.y = sy;
  3974. scale.z = sz;
  3975. return this;
  3976. }
  3977. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  3978. const te = this.elements;
  3979. const x = 2 * near / ( right - left );
  3980. const y = 2 * near / ( top - bottom );
  3981. const a = ( right + left ) / ( right - left );
  3982. const b = ( top + bottom ) / ( top - bottom );
  3983. let c, d;
  3984. if ( coordinateSystem === WebGLCoordinateSystem ) {
  3985. c = - ( far + near ) / ( far - near );
  3986. d = ( - 2 * far * near ) / ( far - near );
  3987. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  3988. c = - far / ( far - near );
  3989. d = ( - far * near ) / ( far - near );
  3990. } else {
  3991. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  3992. }
  3993. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3994. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3995. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3996. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3997. return this;
  3998. }
  3999. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem ) {
  4000. const te = this.elements;
  4001. const w = 1.0 / ( right - left );
  4002. const h = 1.0 / ( top - bottom );
  4003. const p = 1.0 / ( far - near );
  4004. const x = ( right + left ) * w;
  4005. const y = ( top + bottom ) * h;
  4006. let z, zInv;
  4007. if ( coordinateSystem === WebGLCoordinateSystem ) {
  4008. z = ( far + near ) * p;
  4009. zInv = - 2 * p;
  4010. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  4011. z = near * p;
  4012. zInv = - 1 * p;
  4013. } else {
  4014. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  4015. }
  4016. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4017. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4018. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = zInv; te[ 14 ] = - z;
  4019. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4020. return this;
  4021. }
  4022. equals( matrix ) {
  4023. const te = this.elements;
  4024. const me = matrix.elements;
  4025. for ( let i = 0; i < 16; i ++ ) {
  4026. if ( te[ i ] !== me[ i ] ) return false;
  4027. }
  4028. return true;
  4029. }
  4030. fromArray( array, offset = 0 ) {
  4031. for ( let i = 0; i < 16; i ++ ) {
  4032. this.elements[ i ] = array[ i + offset ];
  4033. }
  4034. return this;
  4035. }
  4036. toArray( array = [], offset = 0 ) {
  4037. const te = this.elements;
  4038. array[ offset ] = te[ 0 ];
  4039. array[ offset + 1 ] = te[ 1 ];
  4040. array[ offset + 2 ] = te[ 2 ];
  4041. array[ offset + 3 ] = te[ 3 ];
  4042. array[ offset + 4 ] = te[ 4 ];
  4043. array[ offset + 5 ] = te[ 5 ];
  4044. array[ offset + 6 ] = te[ 6 ];
  4045. array[ offset + 7 ] = te[ 7 ];
  4046. array[ offset + 8 ] = te[ 8 ];
  4047. array[ offset + 9 ] = te[ 9 ];
  4048. array[ offset + 10 ] = te[ 10 ];
  4049. array[ offset + 11 ] = te[ 11 ];
  4050. array[ offset + 12 ] = te[ 12 ];
  4051. array[ offset + 13 ] = te[ 13 ];
  4052. array[ offset + 14 ] = te[ 14 ];
  4053. array[ offset + 15 ] = te[ 15 ];
  4054. return array;
  4055. }
  4056. }
  4057. const _v1$5 = /*@__PURE__*/ new Vector3();
  4058. const _m1$2 = /*@__PURE__*/ new Matrix4();
  4059. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4060. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4061. const _x = /*@__PURE__*/ new Vector3();
  4062. const _y = /*@__PURE__*/ new Vector3();
  4063. const _z = /*@__PURE__*/ new Vector3();
  4064. const _matrix = /*@__PURE__*/ new Matrix4();
  4065. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4066. class Euler {
  4067. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  4068. this.isEuler = true;
  4069. this._x = x;
  4070. this._y = y;
  4071. this._z = z;
  4072. this._order = order;
  4073. }
  4074. get x() {
  4075. return this._x;
  4076. }
  4077. set x( value ) {
  4078. this._x = value;
  4079. this._onChangeCallback();
  4080. }
  4081. get y() {
  4082. return this._y;
  4083. }
  4084. set y( value ) {
  4085. this._y = value;
  4086. this._onChangeCallback();
  4087. }
  4088. get z() {
  4089. return this._z;
  4090. }
  4091. set z( value ) {
  4092. this._z = value;
  4093. this._onChangeCallback();
  4094. }
  4095. get order() {
  4096. return this._order;
  4097. }
  4098. set order( value ) {
  4099. this._order = value;
  4100. this._onChangeCallback();
  4101. }
  4102. set( x, y, z, order = this._order ) {
  4103. this._x = x;
  4104. this._y = y;
  4105. this._z = z;
  4106. this._order = order;
  4107. this._onChangeCallback();
  4108. return this;
  4109. }
  4110. clone() {
  4111. return new this.constructor( this._x, this._y, this._z, this._order );
  4112. }
  4113. copy( euler ) {
  4114. this._x = euler._x;
  4115. this._y = euler._y;
  4116. this._z = euler._z;
  4117. this._order = euler._order;
  4118. this._onChangeCallback();
  4119. return this;
  4120. }
  4121. setFromRotationMatrix( m, order = this._order, update = true ) {
  4122. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4123. const te = m.elements;
  4124. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4125. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4126. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4127. switch ( order ) {
  4128. case 'XYZ':
  4129. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4130. if ( Math.abs( m13 ) < 0.9999999 ) {
  4131. this._x = Math.atan2( - m23, m33 );
  4132. this._z = Math.atan2( - m12, m11 );
  4133. } else {
  4134. this._x = Math.atan2( m32, m22 );
  4135. this._z = 0;
  4136. }
  4137. break;
  4138. case 'YXZ':
  4139. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4140. if ( Math.abs( m23 ) < 0.9999999 ) {
  4141. this._y = Math.atan2( m13, m33 );
  4142. this._z = Math.atan2( m21, m22 );
  4143. } else {
  4144. this._y = Math.atan2( - m31, m11 );
  4145. this._z = 0;
  4146. }
  4147. break;
  4148. case 'ZXY':
  4149. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4150. if ( Math.abs( m32 ) < 0.9999999 ) {
  4151. this._y = Math.atan2( - m31, m33 );
  4152. this._z = Math.atan2( - m12, m22 );
  4153. } else {
  4154. this._y = 0;
  4155. this._z = Math.atan2( m21, m11 );
  4156. }
  4157. break;
  4158. case 'ZYX':
  4159. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4160. if ( Math.abs( m31 ) < 0.9999999 ) {
  4161. this._x = Math.atan2( m32, m33 );
  4162. this._z = Math.atan2( m21, m11 );
  4163. } else {
  4164. this._x = 0;
  4165. this._z = Math.atan2( - m12, m22 );
  4166. }
  4167. break;
  4168. case 'YZX':
  4169. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4170. if ( Math.abs( m21 ) < 0.9999999 ) {
  4171. this._x = Math.atan2( - m23, m22 );
  4172. this._y = Math.atan2( - m31, m11 );
  4173. } else {
  4174. this._x = 0;
  4175. this._y = Math.atan2( m13, m33 );
  4176. }
  4177. break;
  4178. case 'XZY':
  4179. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  4180. if ( Math.abs( m12 ) < 0.9999999 ) {
  4181. this._x = Math.atan2( m32, m22 );
  4182. this._y = Math.atan2( m13, m11 );
  4183. } else {
  4184. this._x = Math.atan2( - m23, m33 );
  4185. this._y = 0;
  4186. }
  4187. break;
  4188. default:
  4189. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4190. }
  4191. this._order = order;
  4192. if ( update === true ) this._onChangeCallback();
  4193. return this;
  4194. }
  4195. setFromQuaternion( q, order, update ) {
  4196. _matrix.makeRotationFromQuaternion( q );
  4197. return this.setFromRotationMatrix( _matrix, order, update );
  4198. }
  4199. setFromVector3( v, order = this._order ) {
  4200. return this.set( v.x, v.y, v.z, order );
  4201. }
  4202. reorder( newOrder ) {
  4203. // WARNING: this discards revolution information -bhouston
  4204. _quaternion$3.setFromEuler( this );
  4205. return this.setFromQuaternion( _quaternion$3, newOrder );
  4206. }
  4207. equals( euler ) {
  4208. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4209. }
  4210. fromArray( array ) {
  4211. this._x = array[ 0 ];
  4212. this._y = array[ 1 ];
  4213. this._z = array[ 2 ];
  4214. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4215. this._onChangeCallback();
  4216. return this;
  4217. }
  4218. toArray( array = [], offset = 0 ) {
  4219. array[ offset ] = this._x;
  4220. array[ offset + 1 ] = this._y;
  4221. array[ offset + 2 ] = this._z;
  4222. array[ offset + 3 ] = this._order;
  4223. return array;
  4224. }
  4225. _onChange( callback ) {
  4226. this._onChangeCallback = callback;
  4227. return this;
  4228. }
  4229. _onChangeCallback() {}
  4230. *[ Symbol.iterator ]() {
  4231. yield this._x;
  4232. yield this._y;
  4233. yield this._z;
  4234. yield this._order;
  4235. }
  4236. }
  4237. Euler.DEFAULT_ORDER = 'XYZ';
  4238. class Layers {
  4239. constructor() {
  4240. this.mask = 1 | 0;
  4241. }
  4242. set( channel ) {
  4243. this.mask = ( 1 << channel | 0 ) >>> 0;
  4244. }
  4245. enable( channel ) {
  4246. this.mask |= 1 << channel | 0;
  4247. }
  4248. enableAll() {
  4249. this.mask = 0xffffffff | 0;
  4250. }
  4251. toggle( channel ) {
  4252. this.mask ^= 1 << channel | 0;
  4253. }
  4254. disable( channel ) {
  4255. this.mask &= ~ ( 1 << channel | 0 );
  4256. }
  4257. disableAll() {
  4258. this.mask = 0;
  4259. }
  4260. test( layers ) {
  4261. return ( this.mask & layers.mask ) !== 0;
  4262. }
  4263. isEnabled( channel ) {
  4264. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4265. }
  4266. }
  4267. let _object3DId = 0;
  4268. const _v1$4 = /*@__PURE__*/ new Vector3();
  4269. const _q1 = /*@__PURE__*/ new Quaternion();
  4270. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4271. const _target = /*@__PURE__*/ new Vector3();
  4272. const _position$3 = /*@__PURE__*/ new Vector3();
  4273. const _scale$2 = /*@__PURE__*/ new Vector3();
  4274. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4275. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4276. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4277. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4278. const _addedEvent = { type: 'added' };
  4279. const _removedEvent = { type: 'removed' };
  4280. class Object3D extends EventDispatcher {
  4281. constructor() {
  4282. super();
  4283. this.isObject3D = true;
  4284. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4285. this.uuid = generateUUID();
  4286. this.name = '';
  4287. this.type = 'Object3D';
  4288. this.parent = null;
  4289. this.children = [];
  4290. this.up = Object3D.DEFAULT_UP.clone();
  4291. const position = new Vector3();
  4292. const rotation = new Euler();
  4293. const quaternion = new Quaternion();
  4294. const scale = new Vector3( 1, 1, 1 );
  4295. function onRotationChange() {
  4296. quaternion.setFromEuler( rotation, false );
  4297. }
  4298. function onQuaternionChange() {
  4299. rotation.setFromQuaternion( quaternion, undefined, false );
  4300. }
  4301. rotation._onChange( onRotationChange );
  4302. quaternion._onChange( onQuaternionChange );
  4303. Object.defineProperties( this, {
  4304. position: {
  4305. configurable: true,
  4306. enumerable: true,
  4307. value: position
  4308. },
  4309. rotation: {
  4310. configurable: true,
  4311. enumerable: true,
  4312. value: rotation
  4313. },
  4314. quaternion: {
  4315. configurable: true,
  4316. enumerable: true,
  4317. value: quaternion
  4318. },
  4319. scale: {
  4320. configurable: true,
  4321. enumerable: true,
  4322. value: scale
  4323. },
  4324. modelViewMatrix: {
  4325. value: new Matrix4()
  4326. },
  4327. normalMatrix: {
  4328. value: new Matrix3()
  4329. }
  4330. } );
  4331. this.matrix = new Matrix4();
  4332. this.matrixWorld = new Matrix4();
  4333. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4334. this.matrixWorldNeedsUpdate = false;
  4335. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4336. this.layers = new Layers();
  4337. this.visible = true;
  4338. this.castShadow = false;
  4339. this.receiveShadow = false;
  4340. this.frustumCulled = true;
  4341. this.renderOrder = 0;
  4342. this.animations = [];
  4343. this.userData = {};
  4344. }
  4345. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4346. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4347. applyMatrix4( matrix ) {
  4348. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4349. this.matrix.premultiply( matrix );
  4350. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4351. }
  4352. applyQuaternion( q ) {
  4353. this.quaternion.premultiply( q );
  4354. return this;
  4355. }
  4356. setRotationFromAxisAngle( axis, angle ) {
  4357. // assumes axis is normalized
  4358. this.quaternion.setFromAxisAngle( axis, angle );
  4359. }
  4360. setRotationFromEuler( euler ) {
  4361. this.quaternion.setFromEuler( euler, true );
  4362. }
  4363. setRotationFromMatrix( m ) {
  4364. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4365. this.quaternion.setFromRotationMatrix( m );
  4366. }
  4367. setRotationFromQuaternion( q ) {
  4368. // assumes q is normalized
  4369. this.quaternion.copy( q );
  4370. }
  4371. rotateOnAxis( axis, angle ) {
  4372. // rotate object on axis in object space
  4373. // axis is assumed to be normalized
  4374. _q1.setFromAxisAngle( axis, angle );
  4375. this.quaternion.multiply( _q1 );
  4376. return this;
  4377. }
  4378. rotateOnWorldAxis( axis, angle ) {
  4379. // rotate object on axis in world space
  4380. // axis is assumed to be normalized
  4381. // method assumes no rotated parent
  4382. _q1.setFromAxisAngle( axis, angle );
  4383. this.quaternion.premultiply( _q1 );
  4384. return this;
  4385. }
  4386. rotateX( angle ) {
  4387. return this.rotateOnAxis( _xAxis, angle );
  4388. }
  4389. rotateY( angle ) {
  4390. return this.rotateOnAxis( _yAxis, angle );
  4391. }
  4392. rotateZ( angle ) {
  4393. return this.rotateOnAxis( _zAxis, angle );
  4394. }
  4395. translateOnAxis( axis, distance ) {
  4396. // translate object by distance along axis in object space
  4397. // axis is assumed to be normalized
  4398. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4399. this.position.add( _v1$4.multiplyScalar( distance ) );
  4400. return this;
  4401. }
  4402. translateX( distance ) {
  4403. return this.translateOnAxis( _xAxis, distance );
  4404. }
  4405. translateY( distance ) {
  4406. return this.translateOnAxis( _yAxis, distance );
  4407. }
  4408. translateZ( distance ) {
  4409. return this.translateOnAxis( _zAxis, distance );
  4410. }
  4411. localToWorld( vector ) {
  4412. this.updateWorldMatrix( true, false );
  4413. return vector.applyMatrix4( this.matrixWorld );
  4414. }
  4415. worldToLocal( vector ) {
  4416. this.updateWorldMatrix( true, false );
  4417. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4418. }
  4419. lookAt( x, y, z ) {
  4420. // This method does not support objects having non-uniformly-scaled parent(s)
  4421. if ( x.isVector3 ) {
  4422. _target.copy( x );
  4423. } else {
  4424. _target.set( x, y, z );
  4425. }
  4426. const parent = this.parent;
  4427. this.updateWorldMatrix( true, false );
  4428. _position$3.setFromMatrixPosition( this.matrixWorld );
  4429. if ( this.isCamera || this.isLight ) {
  4430. _m1$1.lookAt( _position$3, _target, this.up );
  4431. } else {
  4432. _m1$1.lookAt( _target, _position$3, this.up );
  4433. }
  4434. this.quaternion.setFromRotationMatrix( _m1$1 );
  4435. if ( parent ) {
  4436. _m1$1.extractRotation( parent.matrixWorld );
  4437. _q1.setFromRotationMatrix( _m1$1 );
  4438. this.quaternion.premultiply( _q1.invert() );
  4439. }
  4440. }
  4441. add( object ) {
  4442. if ( arguments.length > 1 ) {
  4443. for ( let i = 0; i < arguments.length; i ++ ) {
  4444. this.add( arguments[ i ] );
  4445. }
  4446. return this;
  4447. }
  4448. if ( object === this ) {
  4449. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4450. return this;
  4451. }
  4452. if ( object && object.isObject3D ) {
  4453. if ( object.parent !== null ) {
  4454. object.parent.remove( object );
  4455. }
  4456. object.parent = this;
  4457. this.children.push( object );
  4458. object.dispatchEvent( _addedEvent );
  4459. } else {
  4460. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4461. }
  4462. return this;
  4463. }
  4464. remove( object ) {
  4465. if ( arguments.length > 1 ) {
  4466. for ( let i = 0; i < arguments.length; i ++ ) {
  4467. this.remove( arguments[ i ] );
  4468. }
  4469. return this;
  4470. }
  4471. const index = this.children.indexOf( object );
  4472. if ( index !== - 1 ) {
  4473. object.parent = null;
  4474. this.children.splice( index, 1 );
  4475. object.dispatchEvent( _removedEvent );
  4476. }
  4477. return this;
  4478. }
  4479. removeFromParent() {
  4480. const parent = this.parent;
  4481. if ( parent !== null ) {
  4482. parent.remove( this );
  4483. }
  4484. return this;
  4485. }
  4486. clear() {
  4487. for ( let i = 0; i < this.children.length; i ++ ) {
  4488. const object = this.children[ i ];
  4489. object.parent = null;
  4490. object.dispatchEvent( _removedEvent );
  4491. }
  4492. this.children.length = 0;
  4493. return this;
  4494. }
  4495. attach( object ) {
  4496. // adds object as a child of this, while maintaining the object's world transform
  4497. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4498. this.updateWorldMatrix( true, false );
  4499. _m1$1.copy( this.matrixWorld ).invert();
  4500. if ( object.parent !== null ) {
  4501. object.parent.updateWorldMatrix( true, false );
  4502. _m1$1.multiply( object.parent.matrixWorld );
  4503. }
  4504. object.applyMatrix4( _m1$1 );
  4505. this.add( object );
  4506. object.updateWorldMatrix( false, true );
  4507. return this;
  4508. }
  4509. getObjectById( id ) {
  4510. return this.getObjectByProperty( 'id', id );
  4511. }
  4512. getObjectByName( name ) {
  4513. return this.getObjectByProperty( 'name', name );
  4514. }
  4515. getObjectByProperty( name, value ) {
  4516. if ( this[ name ] === value ) return this;
  4517. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4518. const child = this.children[ i ];
  4519. const object = child.getObjectByProperty( name, value );
  4520. if ( object !== undefined ) {
  4521. return object;
  4522. }
  4523. }
  4524. return undefined;
  4525. }
  4526. getObjectsByProperty( name, value ) {
  4527. let result = [];
  4528. if ( this[ name ] === value ) result.push( this );
  4529. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4530. const childResult = this.children[ i ].getObjectsByProperty( name, value );
  4531. if ( childResult.length > 0 ) {
  4532. result = result.concat( childResult );
  4533. }
  4534. }
  4535. return result;
  4536. }
  4537. getWorldPosition( target ) {
  4538. this.updateWorldMatrix( true, false );
  4539. return target.setFromMatrixPosition( this.matrixWorld );
  4540. }
  4541. getWorldQuaternion( target ) {
  4542. this.updateWorldMatrix( true, false );
  4543. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4544. return target;
  4545. }
  4546. getWorldScale( target ) {
  4547. this.updateWorldMatrix( true, false );
  4548. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4549. return target;
  4550. }
  4551. getWorldDirection( target ) {
  4552. this.updateWorldMatrix( true, false );
  4553. const e = this.matrixWorld.elements;
  4554. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4555. }
  4556. raycast( /* raycaster, intersects */ ) {}
  4557. traverse( callback ) {
  4558. callback( this );
  4559. const children = this.children;
  4560. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4561. children[ i ].traverse( callback );
  4562. }
  4563. }
  4564. traverseVisible( callback ) {
  4565. if ( this.visible === false ) return;
  4566. callback( this );
  4567. const children = this.children;
  4568. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4569. children[ i ].traverseVisible( callback );
  4570. }
  4571. }
  4572. traverseAncestors( callback ) {
  4573. const parent = this.parent;
  4574. if ( parent !== null ) {
  4575. callback( parent );
  4576. parent.traverseAncestors( callback );
  4577. }
  4578. }
  4579. updateMatrix() {
  4580. this.matrix.compose( this.position, this.quaternion, this.scale );
  4581. this.matrixWorldNeedsUpdate = true;
  4582. }
  4583. updateMatrixWorld( force ) {
  4584. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4585. if ( this.matrixWorldNeedsUpdate || force ) {
  4586. if ( this.parent === null ) {
  4587. this.matrixWorld.copy( this.matrix );
  4588. } else {
  4589. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4590. }
  4591. this.matrixWorldNeedsUpdate = false;
  4592. force = true;
  4593. }
  4594. // update children
  4595. const children = this.children;
  4596. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4597. const child = children[ i ];
  4598. if ( child.matrixWorldAutoUpdate === true || force === true ) {
  4599. child.updateMatrixWorld( force );
  4600. }
  4601. }
  4602. }
  4603. updateWorldMatrix( updateParents, updateChildren ) {
  4604. const parent = this.parent;
  4605. if ( updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true ) {
  4606. parent.updateWorldMatrix( true, false );
  4607. }
  4608. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4609. if ( this.parent === null ) {
  4610. this.matrixWorld.copy( this.matrix );
  4611. } else {
  4612. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4613. }
  4614. // update children
  4615. if ( updateChildren === true ) {
  4616. const children = this.children;
  4617. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4618. const child = children[ i ];
  4619. if ( child.matrixWorldAutoUpdate === true ) {
  4620. child.updateWorldMatrix( false, true );
  4621. }
  4622. }
  4623. }
  4624. }
  4625. toJSON( meta ) {
  4626. // meta is a string when called from JSON.stringify
  4627. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4628. const output = {};
  4629. // meta is a hash used to collect geometries, materials.
  4630. // not providing it implies that this is the root object
  4631. // being serialized.
  4632. if ( isRootObject ) {
  4633. // initialize meta obj
  4634. meta = {
  4635. geometries: {},
  4636. materials: {},
  4637. textures: {},
  4638. images: {},
  4639. shapes: {},
  4640. skeletons: {},
  4641. animations: {},
  4642. nodes: {}
  4643. };
  4644. output.metadata = {
  4645. version: 4.6,
  4646. type: 'Object',
  4647. generator: 'Object3D.toJSON'
  4648. };
  4649. }
  4650. // standard Object3D serialization
  4651. const object = {};
  4652. object.uuid = this.uuid;
  4653. object.type = this.type;
  4654. if ( this.name !== '' ) object.name = this.name;
  4655. if ( this.castShadow === true ) object.castShadow = true;
  4656. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4657. if ( this.visible === false ) object.visible = false;
  4658. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4659. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4660. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4661. object.layers = this.layers.mask;
  4662. object.matrix = this.matrix.toArray();
  4663. object.up = this.up.toArray();
  4664. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4665. // object specific properties
  4666. if ( this.isInstancedMesh ) {
  4667. object.type = 'InstancedMesh';
  4668. object.count = this.count;
  4669. object.instanceMatrix = this.instanceMatrix.toJSON();
  4670. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4671. }
  4672. //
  4673. function serialize( library, element ) {
  4674. if ( library[ element.uuid ] === undefined ) {
  4675. library[ element.uuid ] = element.toJSON( meta );
  4676. }
  4677. return element.uuid;
  4678. }
  4679. if ( this.isScene ) {
  4680. if ( this.background ) {
  4681. if ( this.background.isColor ) {
  4682. object.background = this.background.toJSON();
  4683. } else if ( this.background.isTexture ) {
  4684. object.background = this.background.toJSON( meta ).uuid;
  4685. }
  4686. }
  4687. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4688. object.environment = this.environment.toJSON( meta ).uuid;
  4689. }
  4690. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4691. object.geometry = serialize( meta.geometries, this.geometry );
  4692. const parameters = this.geometry.parameters;
  4693. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4694. const shapes = parameters.shapes;
  4695. if ( Array.isArray( shapes ) ) {
  4696. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4697. const shape = shapes[ i ];
  4698. serialize( meta.shapes, shape );
  4699. }
  4700. } else {
  4701. serialize( meta.shapes, shapes );
  4702. }
  4703. }
  4704. }
  4705. if ( this.isSkinnedMesh ) {
  4706. object.bindMode = this.bindMode;
  4707. object.bindMatrix = this.bindMatrix.toArray();
  4708. if ( this.skeleton !== undefined ) {
  4709. serialize( meta.skeletons, this.skeleton );
  4710. object.skeleton = this.skeleton.uuid;
  4711. }
  4712. }
  4713. if ( this.material !== undefined ) {
  4714. if ( Array.isArray( this.material ) ) {
  4715. const uuids = [];
  4716. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4717. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4718. }
  4719. object.material = uuids;
  4720. } else {
  4721. object.material = serialize( meta.materials, this.material );
  4722. }
  4723. }
  4724. //
  4725. if ( this.children.length > 0 ) {
  4726. object.children = [];
  4727. for ( let i = 0; i < this.children.length; i ++ ) {
  4728. object.children.push( this.children[ i ].toJSON( meta ).object );
  4729. }
  4730. }
  4731. //
  4732. if ( this.animations.length > 0 ) {
  4733. object.animations = [];
  4734. for ( let i = 0; i < this.animations.length; i ++ ) {
  4735. const animation = this.animations[ i ];
  4736. object.animations.push( serialize( meta.animations, animation ) );
  4737. }
  4738. }
  4739. if ( isRootObject ) {
  4740. const geometries = extractFromCache( meta.geometries );
  4741. const materials = extractFromCache( meta.materials );
  4742. const textures = extractFromCache( meta.textures );
  4743. const images = extractFromCache( meta.images );
  4744. const shapes = extractFromCache( meta.shapes );
  4745. const skeletons = extractFromCache( meta.skeletons );
  4746. const animations = extractFromCache( meta.animations );
  4747. const nodes = extractFromCache( meta.nodes );
  4748. if ( geometries.length > 0 ) output.geometries = geometries;
  4749. if ( materials.length > 0 ) output.materials = materials;
  4750. if ( textures.length > 0 ) output.textures = textures;
  4751. if ( images.length > 0 ) output.images = images;
  4752. if ( shapes.length > 0 ) output.shapes = shapes;
  4753. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4754. if ( animations.length > 0 ) output.animations = animations;
  4755. if ( nodes.length > 0 ) output.nodes = nodes;
  4756. }
  4757. output.object = object;
  4758. return output;
  4759. // extract data from the cache hash
  4760. // remove metadata on each item
  4761. // and return as array
  4762. function extractFromCache( cache ) {
  4763. const values = [];
  4764. for ( const key in cache ) {
  4765. const data = cache[ key ];
  4766. delete data.metadata;
  4767. values.push( data );
  4768. }
  4769. return values;
  4770. }
  4771. }
  4772. clone( recursive ) {
  4773. return new this.constructor().copy( this, recursive );
  4774. }
  4775. copy( source, recursive = true ) {
  4776. this.name = source.name;
  4777. this.up.copy( source.up );
  4778. this.position.copy( source.position );
  4779. this.rotation.order = source.rotation.order;
  4780. this.quaternion.copy( source.quaternion );
  4781. this.scale.copy( source.scale );
  4782. this.matrix.copy( source.matrix );
  4783. this.matrixWorld.copy( source.matrixWorld );
  4784. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4785. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4786. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  4787. this.layers.mask = source.layers.mask;
  4788. this.visible = source.visible;
  4789. this.castShadow = source.castShadow;
  4790. this.receiveShadow = source.receiveShadow;
  4791. this.frustumCulled = source.frustumCulled;
  4792. this.renderOrder = source.renderOrder;
  4793. this.animations = source.animations;
  4794. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4795. if ( recursive === true ) {
  4796. for ( let i = 0; i < source.children.length; i ++ ) {
  4797. const child = source.children[ i ];
  4798. this.add( child.clone() );
  4799. }
  4800. }
  4801. return this;
  4802. }
  4803. }
  4804. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4805. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  4806. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  4807. const _v0$1 = /*@__PURE__*/ new Vector3();
  4808. const _v1$3 = /*@__PURE__*/ new Vector3();
  4809. const _v2$2 = /*@__PURE__*/ new Vector3();
  4810. const _v3$1 = /*@__PURE__*/ new Vector3();
  4811. const _vab = /*@__PURE__*/ new Vector3();
  4812. const _vac = /*@__PURE__*/ new Vector3();
  4813. const _vbc = /*@__PURE__*/ new Vector3();
  4814. const _vap = /*@__PURE__*/ new Vector3();
  4815. const _vbp = /*@__PURE__*/ new Vector3();
  4816. const _vcp = /*@__PURE__*/ new Vector3();
  4817. let warnedGetUV = false;
  4818. class Triangle {
  4819. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4820. this.a = a;
  4821. this.b = b;
  4822. this.c = c;
  4823. }
  4824. static getNormal( a, b, c, target ) {
  4825. target.subVectors( c, b );
  4826. _v0$1.subVectors( a, b );
  4827. target.cross( _v0$1 );
  4828. const targetLengthSq = target.lengthSq();
  4829. if ( targetLengthSq > 0 ) {
  4830. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4831. }
  4832. return target.set( 0, 0, 0 );
  4833. }
  4834. // static/instance method to calculate barycentric coordinates
  4835. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4836. static getBarycoord( point, a, b, c, target ) {
  4837. _v0$1.subVectors( c, a );
  4838. _v1$3.subVectors( b, a );
  4839. _v2$2.subVectors( point, a );
  4840. const dot00 = _v0$1.dot( _v0$1 );
  4841. const dot01 = _v0$1.dot( _v1$3 );
  4842. const dot02 = _v0$1.dot( _v2$2 );
  4843. const dot11 = _v1$3.dot( _v1$3 );
  4844. const dot12 = _v1$3.dot( _v2$2 );
  4845. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4846. // collinear or singular triangle
  4847. if ( denom === 0 ) {
  4848. // arbitrary location outside of triangle?
  4849. // not sure if this is the best idea, maybe should be returning undefined
  4850. return target.set( - 2, - 1, - 1 );
  4851. }
  4852. const invDenom = 1 / denom;
  4853. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4854. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4855. // barycentric coordinates must always sum to 1
  4856. return target.set( 1 - u - v, v, u );
  4857. }
  4858. static containsPoint( point, a, b, c ) {
  4859. this.getBarycoord( point, a, b, c, _v3$1 );
  4860. return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 );
  4861. }
  4862. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) { // @deprecated, r151
  4863. if ( warnedGetUV === false ) {
  4864. console.warn( 'THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation().' );
  4865. warnedGetUV = true;
  4866. }
  4867. return this.getInterpolation( point, p1, p2, p3, uv1, uv2, uv3, target );
  4868. }
  4869. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  4870. this.getBarycoord( point, p1, p2, p3, _v3$1 );
  4871. target.setScalar( 0 );
  4872. target.addScaledVector( v1, _v3$1.x );
  4873. target.addScaledVector( v2, _v3$1.y );
  4874. target.addScaledVector( v3, _v3$1.z );
  4875. return target;
  4876. }
  4877. static isFrontFacing( a, b, c, direction ) {
  4878. _v0$1.subVectors( c, b );
  4879. _v1$3.subVectors( a, b );
  4880. // strictly front facing
  4881. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4882. }
  4883. set( a, b, c ) {
  4884. this.a.copy( a );
  4885. this.b.copy( b );
  4886. this.c.copy( c );
  4887. return this;
  4888. }
  4889. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4890. this.a.copy( points[ i0 ] );
  4891. this.b.copy( points[ i1 ] );
  4892. this.c.copy( points[ i2 ] );
  4893. return this;
  4894. }
  4895. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  4896. this.a.fromBufferAttribute( attribute, i0 );
  4897. this.b.fromBufferAttribute( attribute, i1 );
  4898. this.c.fromBufferAttribute( attribute, i2 );
  4899. return this;
  4900. }
  4901. clone() {
  4902. return new this.constructor().copy( this );
  4903. }
  4904. copy( triangle ) {
  4905. this.a.copy( triangle.a );
  4906. this.b.copy( triangle.b );
  4907. this.c.copy( triangle.c );
  4908. return this;
  4909. }
  4910. getArea() {
  4911. _v0$1.subVectors( this.c, this.b );
  4912. _v1$3.subVectors( this.a, this.b );
  4913. return _v0$1.cross( _v1$3 ).length() * 0.5;
  4914. }
  4915. getMidpoint( target ) {
  4916. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4917. }
  4918. getNormal( target ) {
  4919. return Triangle.getNormal( this.a, this.b, this.c, target );
  4920. }
  4921. getPlane( target ) {
  4922. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  4923. }
  4924. getBarycoord( point, target ) {
  4925. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  4926. }
  4927. getUV( point, uv1, uv2, uv3, target ) { // @deprecated, r151
  4928. if ( warnedGetUV === false ) {
  4929. console.warn( 'THREE.Triangle.getUV() has been renamed to THREE.Triangle.getInterpolation().' );
  4930. warnedGetUV = true;
  4931. }
  4932. return Triangle.getInterpolation( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  4933. }
  4934. getInterpolation( point, v1, v2, v3, target ) {
  4935. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  4936. }
  4937. containsPoint( point ) {
  4938. return Triangle.containsPoint( point, this.a, this.b, this.c );
  4939. }
  4940. isFrontFacing( direction ) {
  4941. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  4942. }
  4943. intersectsBox( box ) {
  4944. return box.intersectsTriangle( this );
  4945. }
  4946. closestPointToPoint( p, target ) {
  4947. const a = this.a, b = this.b, c = this.c;
  4948. let v, w;
  4949. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4950. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4951. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4952. // basically, we're distinguishing which of the voronoi regions of the triangle
  4953. // the point lies in with the minimum amount of redundant computation.
  4954. _vab.subVectors( b, a );
  4955. _vac.subVectors( c, a );
  4956. _vap.subVectors( p, a );
  4957. const d1 = _vab.dot( _vap );
  4958. const d2 = _vac.dot( _vap );
  4959. if ( d1 <= 0 && d2 <= 0 ) {
  4960. // vertex region of A; barycentric coords (1, 0, 0)
  4961. return target.copy( a );
  4962. }
  4963. _vbp.subVectors( p, b );
  4964. const d3 = _vab.dot( _vbp );
  4965. const d4 = _vac.dot( _vbp );
  4966. if ( d3 >= 0 && d4 <= d3 ) {
  4967. // vertex region of B; barycentric coords (0, 1, 0)
  4968. return target.copy( b );
  4969. }
  4970. const vc = d1 * d4 - d3 * d2;
  4971. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  4972. v = d1 / ( d1 - d3 );
  4973. // edge region of AB; barycentric coords (1-v, v, 0)
  4974. return target.copy( a ).addScaledVector( _vab, v );
  4975. }
  4976. _vcp.subVectors( p, c );
  4977. const d5 = _vab.dot( _vcp );
  4978. const d6 = _vac.dot( _vcp );
  4979. if ( d6 >= 0 && d5 <= d6 ) {
  4980. // vertex region of C; barycentric coords (0, 0, 1)
  4981. return target.copy( c );
  4982. }
  4983. const vb = d5 * d2 - d1 * d6;
  4984. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  4985. w = d2 / ( d2 - d6 );
  4986. // edge region of AC; barycentric coords (1-w, 0, w)
  4987. return target.copy( a ).addScaledVector( _vac, w );
  4988. }
  4989. const va = d3 * d6 - d5 * d4;
  4990. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  4991. _vbc.subVectors( c, b );
  4992. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  4993. // edge region of BC; barycentric coords (0, 1-w, w)
  4994. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  4995. }
  4996. // face region
  4997. const denom = 1 / ( va + vb + vc );
  4998. // u = va * denom
  4999. v = vb * denom;
  5000. w = vc * denom;
  5001. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5002. }
  5003. equals( triangle ) {
  5004. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5005. }
  5006. }
  5007. let materialId = 0;
  5008. class Material extends EventDispatcher {
  5009. constructor() {
  5010. super();
  5011. this.isMaterial = true;
  5012. Object.defineProperty( this, 'id', { value: materialId ++ } );
  5013. this.uuid = generateUUID();
  5014. this.name = '';
  5015. this.type = 'Material';
  5016. this.blending = NormalBlending;
  5017. this.side = FrontSide;
  5018. this.vertexColors = false;
  5019. this.opacity = 1;
  5020. this.transparent = false;
  5021. this.alphaHash = false;
  5022. this.blendSrc = SrcAlphaFactor;
  5023. this.blendDst = OneMinusSrcAlphaFactor;
  5024. this.blendEquation = AddEquation;
  5025. this.blendSrcAlpha = null;
  5026. this.blendDstAlpha = null;
  5027. this.blendEquationAlpha = null;
  5028. this.depthFunc = LessEqualDepth;
  5029. this.depthTest = true;
  5030. this.depthWrite = true;
  5031. this.stencilWriteMask = 0xff;
  5032. this.stencilFunc = AlwaysStencilFunc;
  5033. this.stencilRef = 0;
  5034. this.stencilFuncMask = 0xff;
  5035. this.stencilFail = KeepStencilOp;
  5036. this.stencilZFail = KeepStencilOp;
  5037. this.stencilZPass = KeepStencilOp;
  5038. this.stencilWrite = false;
  5039. this.clippingPlanes = null;
  5040. this.clipIntersection = false;
  5041. this.clipShadows = false;
  5042. this.shadowSide = null;
  5043. this.colorWrite = true;
  5044. this.precision = null; // override the renderer's default precision for this material
  5045. this.polygonOffset = false;
  5046. this.polygonOffsetFactor = 0;
  5047. this.polygonOffsetUnits = 0;
  5048. this.dithering = false;
  5049. this.alphaToCoverage = false;
  5050. this.premultipliedAlpha = false;
  5051. this.forceSinglePass = false;
  5052. this.visible = true;
  5053. this.toneMapped = true;
  5054. this.userData = {};
  5055. this.version = 0;
  5056. this._alphaTest = 0;
  5057. }
  5058. get alphaTest() {
  5059. return this._alphaTest;
  5060. }
  5061. set alphaTest( value ) {
  5062. if ( this._alphaTest > 0 !== value > 0 ) {
  5063. this.version ++;
  5064. }
  5065. this._alphaTest = value;
  5066. }
  5067. onBuild( /* shaderobject, renderer */ ) {}
  5068. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  5069. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5070. customProgramCacheKey() {
  5071. return this.onBeforeCompile.toString();
  5072. }
  5073. setValues( values ) {
  5074. if ( values === undefined ) return;
  5075. for ( const key in values ) {
  5076. const newValue = values[ key ];
  5077. if ( newValue === undefined ) {
  5078. console.warn( `THREE.Material: parameter '${ key }' has value of undefined.` );
  5079. continue;
  5080. }
  5081. const currentValue = this[ key ];
  5082. if ( currentValue === undefined ) {
  5083. console.warn( `THREE.Material: '${ key }' is not a property of THREE.${ this.type }.` );
  5084. continue;
  5085. }
  5086. if ( currentValue && currentValue.isColor ) {
  5087. currentValue.set( newValue );
  5088. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5089. currentValue.copy( newValue );
  5090. } else {
  5091. this[ key ] = newValue;
  5092. }
  5093. }
  5094. }
  5095. toJSON( meta ) {
  5096. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5097. if ( isRootObject ) {
  5098. meta = {
  5099. textures: {},
  5100. images: {}
  5101. };
  5102. }
  5103. const data = {
  5104. metadata: {
  5105. version: 4.6,
  5106. type: 'Material',
  5107. generator: 'Material.toJSON'
  5108. }
  5109. };
  5110. // standard Material serialization
  5111. data.uuid = this.uuid;
  5112. data.type = this.type;
  5113. if ( this.name !== '' ) data.name = this.name;
  5114. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5115. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5116. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5117. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5118. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5119. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5120. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5121. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5122. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5123. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5124. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5125. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5126. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5127. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5128. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5129. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5130. }
  5131. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5132. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5133. }
  5134. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5135. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5136. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5137. }
  5138. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5139. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5140. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5141. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5142. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5143. }
  5144. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5145. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5146. }
  5147. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  5148. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  5149. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  5150. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  5151. }
  5152. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5153. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5154. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5155. if ( this.lightMap && this.lightMap.isTexture ) {
  5156. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5157. data.lightMapIntensity = this.lightMapIntensity;
  5158. }
  5159. if ( this.aoMap && this.aoMap.isTexture ) {
  5160. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5161. data.aoMapIntensity = this.aoMapIntensity;
  5162. }
  5163. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5164. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5165. data.bumpScale = this.bumpScale;
  5166. }
  5167. if ( this.normalMap && this.normalMap.isTexture ) {
  5168. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5169. data.normalMapType = this.normalMapType;
  5170. data.normalScale = this.normalScale.toArray();
  5171. }
  5172. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5173. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5174. data.displacementScale = this.displacementScale;
  5175. data.displacementBias = this.displacementBias;
  5176. }
  5177. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5178. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5179. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5180. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5181. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5182. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5183. if ( this.envMap && this.envMap.isTexture ) {
  5184. data.envMap = this.envMap.toJSON( meta ).uuid;
  5185. if ( this.combine !== undefined ) data.combine = this.combine;
  5186. }
  5187. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5188. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5189. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5190. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5191. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5192. }
  5193. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5194. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5195. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5196. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5197. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5198. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5199. if ( this.size !== undefined ) data.size = this.size;
  5200. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5201. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5202. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5203. if ( this.side !== FrontSide ) data.side = this.side;
  5204. if ( this.vertexColors ) data.vertexColors = true;
  5205. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5206. if ( this.transparent === true ) data.transparent = this.transparent;
  5207. data.depthFunc = this.depthFunc;
  5208. data.depthTest = this.depthTest;
  5209. data.depthWrite = this.depthWrite;
  5210. data.colorWrite = this.colorWrite;
  5211. data.stencilWrite = this.stencilWrite;
  5212. data.stencilWriteMask = this.stencilWriteMask;
  5213. data.stencilFunc = this.stencilFunc;
  5214. data.stencilRef = this.stencilRef;
  5215. data.stencilFuncMask = this.stencilFuncMask;
  5216. data.stencilFail = this.stencilFail;
  5217. data.stencilZFail = this.stencilZFail;
  5218. data.stencilZPass = this.stencilZPass;
  5219. // rotation (SpriteMaterial)
  5220. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5221. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5222. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5223. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5224. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5225. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5226. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5227. if ( this.scale !== undefined ) data.scale = this.scale;
  5228. if ( this.dithering === true ) data.dithering = true;
  5229. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5230. if ( this.alphaHash === true ) data.alphaHash = this.alphaHash;
  5231. if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage;
  5232. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  5233. if ( this.forceSinglePass === true ) data.forceSinglePass = this.forceSinglePass;
  5234. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  5235. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5236. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5237. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5238. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  5239. if ( this.visible === false ) data.visible = false;
  5240. if ( this.toneMapped === false ) data.toneMapped = false;
  5241. if ( this.fog === false ) data.fog = false;
  5242. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5243. // TODO: Copied from Object3D.toJSON
  5244. function extractFromCache( cache ) {
  5245. const values = [];
  5246. for ( const key in cache ) {
  5247. const data = cache[ key ];
  5248. delete data.metadata;
  5249. values.push( data );
  5250. }
  5251. return values;
  5252. }
  5253. if ( isRootObject ) {
  5254. const textures = extractFromCache( meta.textures );
  5255. const images = extractFromCache( meta.images );
  5256. if ( textures.length > 0 ) data.textures = textures;
  5257. if ( images.length > 0 ) data.images = images;
  5258. }
  5259. return data;
  5260. }
  5261. clone() {
  5262. return new this.constructor().copy( this );
  5263. }
  5264. copy( source ) {
  5265. this.name = source.name;
  5266. this.blending = source.blending;
  5267. this.side = source.side;
  5268. this.vertexColors = source.vertexColors;
  5269. this.opacity = source.opacity;
  5270. this.transparent = source.transparent;
  5271. this.blendSrc = source.blendSrc;
  5272. this.blendDst = source.blendDst;
  5273. this.blendEquation = source.blendEquation;
  5274. this.blendSrcAlpha = source.blendSrcAlpha;
  5275. this.blendDstAlpha = source.blendDstAlpha;
  5276. this.blendEquationAlpha = source.blendEquationAlpha;
  5277. this.depthFunc = source.depthFunc;
  5278. this.depthTest = source.depthTest;
  5279. this.depthWrite = source.depthWrite;
  5280. this.stencilWriteMask = source.stencilWriteMask;
  5281. this.stencilFunc = source.stencilFunc;
  5282. this.stencilRef = source.stencilRef;
  5283. this.stencilFuncMask = source.stencilFuncMask;
  5284. this.stencilFail = source.stencilFail;
  5285. this.stencilZFail = source.stencilZFail;
  5286. this.stencilZPass = source.stencilZPass;
  5287. this.stencilWrite = source.stencilWrite;
  5288. const srcPlanes = source.clippingPlanes;
  5289. let dstPlanes = null;
  5290. if ( srcPlanes !== null ) {
  5291. const n = srcPlanes.length;
  5292. dstPlanes = new Array( n );
  5293. for ( let i = 0; i !== n; ++ i ) {
  5294. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5295. }
  5296. }
  5297. this.clippingPlanes = dstPlanes;
  5298. this.clipIntersection = source.clipIntersection;
  5299. this.clipShadows = source.clipShadows;
  5300. this.shadowSide = source.shadowSide;
  5301. this.colorWrite = source.colorWrite;
  5302. this.precision = source.precision;
  5303. this.polygonOffset = source.polygonOffset;
  5304. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5305. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5306. this.dithering = source.dithering;
  5307. this.alphaTest = source.alphaTest;
  5308. this.alphaHash = source.alphaHash;
  5309. this.alphaToCoverage = source.alphaToCoverage;
  5310. this.premultipliedAlpha = source.premultipliedAlpha;
  5311. this.forceSinglePass = source.forceSinglePass;
  5312. this.visible = source.visible;
  5313. this.toneMapped = source.toneMapped;
  5314. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5315. return this;
  5316. }
  5317. dispose() {
  5318. this.dispatchEvent( { type: 'dispose' } );
  5319. }
  5320. set needsUpdate( value ) {
  5321. if ( value === true ) this.version ++;
  5322. }
  5323. }
  5324. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5325. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5326. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5327. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5328. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5329. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5330. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5331. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5332. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5333. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5334. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5335. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5336. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5337. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5338. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5339. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5340. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5341. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5342. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5343. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5344. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5345. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5346. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5347. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5348. const _hslA = { h: 0, s: 0, l: 0 };
  5349. const _hslB = { h: 0, s: 0, l: 0 };
  5350. function hue2rgb( p, q, t ) {
  5351. if ( t < 0 ) t += 1;
  5352. if ( t > 1 ) t -= 1;
  5353. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5354. if ( t < 1 / 2 ) return q;
  5355. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5356. return p;
  5357. }
  5358. class Color {
  5359. constructor( r, g, b ) {
  5360. this.isColor = true;
  5361. this.r = 1;
  5362. this.g = 1;
  5363. this.b = 1;
  5364. return this.set( r, g, b );
  5365. }
  5366. set( r, g, b ) {
  5367. if ( g === undefined && b === undefined ) {
  5368. // r is THREE.Color, hex or string
  5369. const value = r;
  5370. if ( value && value.isColor ) {
  5371. this.copy( value );
  5372. } else if ( typeof value === 'number' ) {
  5373. this.setHex( value );
  5374. } else if ( typeof value === 'string' ) {
  5375. this.setStyle( value );
  5376. }
  5377. } else {
  5378. this.setRGB( r, g, b );
  5379. }
  5380. return this;
  5381. }
  5382. setScalar( scalar ) {
  5383. this.r = scalar;
  5384. this.g = scalar;
  5385. this.b = scalar;
  5386. return this;
  5387. }
  5388. setHex( hex, colorSpace = SRGBColorSpace ) {
  5389. hex = Math.floor( hex );
  5390. this.r = ( hex >> 16 & 255 ) / 255;
  5391. this.g = ( hex >> 8 & 255 ) / 255;
  5392. this.b = ( hex & 255 ) / 255;
  5393. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5394. return this;
  5395. }
  5396. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  5397. this.r = r;
  5398. this.g = g;
  5399. this.b = b;
  5400. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5401. return this;
  5402. }
  5403. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  5404. // h,s,l ranges are in 0.0 - 1.0
  5405. h = euclideanModulo( h, 1 );
  5406. s = clamp( s, 0, 1 );
  5407. l = clamp( l, 0, 1 );
  5408. if ( s === 0 ) {
  5409. this.r = this.g = this.b = l;
  5410. } else {
  5411. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5412. const q = ( 2 * l ) - p;
  5413. this.r = hue2rgb( q, p, h + 1 / 3 );
  5414. this.g = hue2rgb( q, p, h );
  5415. this.b = hue2rgb( q, p, h - 1 / 3 );
  5416. }
  5417. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5418. return this;
  5419. }
  5420. setStyle( style, colorSpace = SRGBColorSpace ) {
  5421. function handleAlpha( string ) {
  5422. if ( string === undefined ) return;
  5423. if ( parseFloat( string ) < 1 ) {
  5424. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5425. }
  5426. }
  5427. let m;
  5428. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  5429. // rgb / hsl
  5430. let color;
  5431. const name = m[ 1 ];
  5432. const components = m[ 2 ];
  5433. switch ( name ) {
  5434. case 'rgb':
  5435. case 'rgba':
  5436. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5437. // rgb(255,0,0) rgba(255,0,0,0.5)
  5438. handleAlpha( color[ 4 ] );
  5439. return this.setRGB(
  5440. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  5441. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  5442. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  5443. colorSpace
  5444. );
  5445. }
  5446. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5447. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5448. handleAlpha( color[ 4 ] );
  5449. return this.setRGB(
  5450. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  5451. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  5452. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  5453. colorSpace
  5454. );
  5455. }
  5456. break;
  5457. case 'hsl':
  5458. case 'hsla':
  5459. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5460. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5461. handleAlpha( color[ 4 ] );
  5462. return this.setHSL(
  5463. parseFloat( color[ 1 ] ) / 360,
  5464. parseFloat( color[ 2 ] ) / 100,
  5465. parseFloat( color[ 3 ] ) / 100,
  5466. colorSpace
  5467. );
  5468. }
  5469. break;
  5470. default:
  5471. console.warn( 'THREE.Color: Unknown color model ' + style );
  5472. }
  5473. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5474. // hex color
  5475. const hex = m[ 1 ];
  5476. const size = hex.length;
  5477. if ( size === 3 ) {
  5478. // #ff0
  5479. return this.setRGB(
  5480. parseInt( hex.charAt( 0 ), 16 ) / 15,
  5481. parseInt( hex.charAt( 1 ), 16 ) / 15,
  5482. parseInt( hex.charAt( 2 ), 16 ) / 15,
  5483. colorSpace
  5484. );
  5485. } else if ( size === 6 ) {
  5486. // #ff0000
  5487. return this.setHex( parseInt( hex, 16 ), colorSpace );
  5488. } else {
  5489. console.warn( 'THREE.Color: Invalid hex color ' + style );
  5490. }
  5491. } else if ( style && style.length > 0 ) {
  5492. return this.setColorName( style, colorSpace );
  5493. }
  5494. return this;
  5495. }
  5496. setColorName( style, colorSpace = SRGBColorSpace ) {
  5497. // color keywords
  5498. const hex = _colorKeywords[ style.toLowerCase() ];
  5499. if ( hex !== undefined ) {
  5500. // red
  5501. this.setHex( hex, colorSpace );
  5502. } else {
  5503. // unknown color
  5504. console.warn( 'THREE.Color: Unknown color ' + style );
  5505. }
  5506. return this;
  5507. }
  5508. clone() {
  5509. return new this.constructor( this.r, this.g, this.b );
  5510. }
  5511. copy( color ) {
  5512. this.r = color.r;
  5513. this.g = color.g;
  5514. this.b = color.b;
  5515. return this;
  5516. }
  5517. copySRGBToLinear( color ) {
  5518. this.r = SRGBToLinear( color.r );
  5519. this.g = SRGBToLinear( color.g );
  5520. this.b = SRGBToLinear( color.b );
  5521. return this;
  5522. }
  5523. copyLinearToSRGB( color ) {
  5524. this.r = LinearToSRGB( color.r );
  5525. this.g = LinearToSRGB( color.g );
  5526. this.b = LinearToSRGB( color.b );
  5527. return this;
  5528. }
  5529. convertSRGBToLinear() {
  5530. this.copySRGBToLinear( this );
  5531. return this;
  5532. }
  5533. convertLinearToSRGB() {
  5534. this.copyLinearToSRGB( this );
  5535. return this;
  5536. }
  5537. getHex( colorSpace = SRGBColorSpace ) {
  5538. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5539. return Math.round( clamp( _color.r * 255, 0, 255 ) ) * 65536 + Math.round( clamp( _color.g * 255, 0, 255 ) ) * 256 + Math.round( clamp( _color.b * 255, 0, 255 ) );
  5540. }
  5541. getHexString( colorSpace = SRGBColorSpace ) {
  5542. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  5543. }
  5544. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  5545. // h,s,l ranges are in 0.0 - 1.0
  5546. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5547. const r = _color.r, g = _color.g, b = _color.b;
  5548. const max = Math.max( r, g, b );
  5549. const min = Math.min( r, g, b );
  5550. let hue, saturation;
  5551. const lightness = ( min + max ) / 2.0;
  5552. if ( min === max ) {
  5553. hue = 0;
  5554. saturation = 0;
  5555. } else {
  5556. const delta = max - min;
  5557. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5558. switch ( max ) {
  5559. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5560. case g: hue = ( b - r ) / delta + 2; break;
  5561. case b: hue = ( r - g ) / delta + 4; break;
  5562. }
  5563. hue /= 6;
  5564. }
  5565. target.h = hue;
  5566. target.s = saturation;
  5567. target.l = lightness;
  5568. return target;
  5569. }
  5570. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  5571. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5572. target.r = _color.r;
  5573. target.g = _color.g;
  5574. target.b = _color.b;
  5575. return target;
  5576. }
  5577. getStyle( colorSpace = SRGBColorSpace ) {
  5578. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5579. const r = _color.r, g = _color.g, b = _color.b;
  5580. if ( colorSpace !== SRGBColorSpace ) {
  5581. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  5582. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  5583. }
  5584. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  5585. }
  5586. offsetHSL( h, s, l ) {
  5587. this.getHSL( _hslA );
  5588. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  5589. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  5590. return this;
  5591. }
  5592. add( color ) {
  5593. this.r += color.r;
  5594. this.g += color.g;
  5595. this.b += color.b;
  5596. return this;
  5597. }
  5598. addColors( color1, color2 ) {
  5599. this.r = color1.r + color2.r;
  5600. this.g = color1.g + color2.g;
  5601. this.b = color1.b + color2.b;
  5602. return this;
  5603. }
  5604. addScalar( s ) {
  5605. this.r += s;
  5606. this.g += s;
  5607. this.b += s;
  5608. return this;
  5609. }
  5610. sub( color ) {
  5611. this.r = Math.max( 0, this.r - color.r );
  5612. this.g = Math.max( 0, this.g - color.g );
  5613. this.b = Math.max( 0, this.b - color.b );
  5614. return this;
  5615. }
  5616. multiply( color ) {
  5617. this.r *= color.r;
  5618. this.g *= color.g;
  5619. this.b *= color.b;
  5620. return this;
  5621. }
  5622. multiplyScalar( s ) {
  5623. this.r *= s;
  5624. this.g *= s;
  5625. this.b *= s;
  5626. return this;
  5627. }
  5628. lerp( color, alpha ) {
  5629. this.r += ( color.r - this.r ) * alpha;
  5630. this.g += ( color.g - this.g ) * alpha;
  5631. this.b += ( color.b - this.b ) * alpha;
  5632. return this;
  5633. }
  5634. lerpColors( color1, color2, alpha ) {
  5635. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5636. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5637. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5638. return this;
  5639. }
  5640. lerpHSL( color, alpha ) {
  5641. this.getHSL( _hslA );
  5642. color.getHSL( _hslB );
  5643. const h = lerp( _hslA.h, _hslB.h, alpha );
  5644. const s = lerp( _hslA.s, _hslB.s, alpha );
  5645. const l = lerp( _hslA.l, _hslB.l, alpha );
  5646. this.setHSL( h, s, l );
  5647. return this;
  5648. }
  5649. setFromVector3( v ) {
  5650. this.r = v.x;
  5651. this.g = v.y;
  5652. this.b = v.z;
  5653. return this;
  5654. }
  5655. applyMatrix3( m ) {
  5656. const r = this.r, g = this.g, b = this.b;
  5657. const e = m.elements;
  5658. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  5659. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  5660. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  5661. return this;
  5662. }
  5663. equals( c ) {
  5664. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5665. }
  5666. fromArray( array, offset = 0 ) {
  5667. this.r = array[ offset ];
  5668. this.g = array[ offset + 1 ];
  5669. this.b = array[ offset + 2 ];
  5670. return this;
  5671. }
  5672. toArray( array = [], offset = 0 ) {
  5673. array[ offset ] = this.r;
  5674. array[ offset + 1 ] = this.g;
  5675. array[ offset + 2 ] = this.b;
  5676. return array;
  5677. }
  5678. fromBufferAttribute( attribute, index ) {
  5679. this.r = attribute.getX( index );
  5680. this.g = attribute.getY( index );
  5681. this.b = attribute.getZ( index );
  5682. return this;
  5683. }
  5684. toJSON() {
  5685. return this.getHex();
  5686. }
  5687. *[ Symbol.iterator ]() {
  5688. yield this.r;
  5689. yield this.g;
  5690. yield this.b;
  5691. }
  5692. }
  5693. const _color = /*@__PURE__*/ new Color();
  5694. Color.NAMES = _colorKeywords;
  5695. class MeshBasicMaterial extends Material {
  5696. constructor( parameters ) {
  5697. super();
  5698. this.isMeshBasicMaterial = true;
  5699. this.type = 'MeshBasicMaterial';
  5700. this.color = new Color( 0xffffff ); // emissive
  5701. this.map = null;
  5702. this.lightMap = null;
  5703. this.lightMapIntensity = 1.0;
  5704. this.aoMap = null;
  5705. this.aoMapIntensity = 1.0;
  5706. this.specularMap = null;
  5707. this.alphaMap = null;
  5708. this.envMap = null;
  5709. this.combine = MultiplyOperation;
  5710. this.reflectivity = 1;
  5711. this.refractionRatio = 0.98;
  5712. this.wireframe = false;
  5713. this.wireframeLinewidth = 1;
  5714. this.wireframeLinecap = 'round';
  5715. this.wireframeLinejoin = 'round';
  5716. this.fog = true;
  5717. this.setValues( parameters );
  5718. }
  5719. copy( source ) {
  5720. super.copy( source );
  5721. this.color.copy( source.color );
  5722. this.map = source.map;
  5723. this.lightMap = source.lightMap;
  5724. this.lightMapIntensity = source.lightMapIntensity;
  5725. this.aoMap = source.aoMap;
  5726. this.aoMapIntensity = source.aoMapIntensity;
  5727. this.specularMap = source.specularMap;
  5728. this.alphaMap = source.alphaMap;
  5729. this.envMap = source.envMap;
  5730. this.combine = source.combine;
  5731. this.reflectivity = source.reflectivity;
  5732. this.refractionRatio = source.refractionRatio;
  5733. this.wireframe = source.wireframe;
  5734. this.wireframeLinewidth = source.wireframeLinewidth;
  5735. this.wireframeLinecap = source.wireframeLinecap;
  5736. this.wireframeLinejoin = source.wireframeLinejoin;
  5737. this.fog = source.fog;
  5738. return this;
  5739. }
  5740. }
  5741. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  5742. const _tables = /*@__PURE__*/ _generateTables();
  5743. function _generateTables() {
  5744. // float32 to float16 helpers
  5745. const buffer = new ArrayBuffer( 4 );
  5746. const floatView = new Float32Array( buffer );
  5747. const uint32View = new Uint32Array( buffer );
  5748. const baseTable = new Uint32Array( 512 );
  5749. const shiftTable = new Uint32Array( 512 );
  5750. for ( let i = 0; i < 256; ++ i ) {
  5751. const e = i - 127;
  5752. // very small number (0, -0)
  5753. if ( e < - 27 ) {
  5754. baseTable[ i ] = 0x0000;
  5755. baseTable[ i | 0x100 ] = 0x8000;
  5756. shiftTable[ i ] = 24;
  5757. shiftTable[ i | 0x100 ] = 24;
  5758. // small number (denorm)
  5759. } else if ( e < - 14 ) {
  5760. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  5761. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  5762. shiftTable[ i ] = - e - 1;
  5763. shiftTable[ i | 0x100 ] = - e - 1;
  5764. // normal number
  5765. } else if ( e <= 15 ) {
  5766. baseTable[ i ] = ( e + 15 ) << 10;
  5767. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  5768. shiftTable[ i ] = 13;
  5769. shiftTable[ i | 0x100 ] = 13;
  5770. // large number (Infinity, -Infinity)
  5771. } else if ( e < 128 ) {
  5772. baseTable[ i ] = 0x7c00;
  5773. baseTable[ i | 0x100 ] = 0xfc00;
  5774. shiftTable[ i ] = 24;
  5775. shiftTable[ i | 0x100 ] = 24;
  5776. // stay (NaN, Infinity, -Infinity)
  5777. } else {
  5778. baseTable[ i ] = 0x7c00;
  5779. baseTable[ i | 0x100 ] = 0xfc00;
  5780. shiftTable[ i ] = 13;
  5781. shiftTable[ i | 0x100 ] = 13;
  5782. }
  5783. }
  5784. // float16 to float32 helpers
  5785. const mantissaTable = new Uint32Array( 2048 );
  5786. const exponentTable = new Uint32Array( 64 );
  5787. const offsetTable = new Uint32Array( 64 );
  5788. for ( let i = 1; i < 1024; ++ i ) {
  5789. let m = i << 13; // zero pad mantissa bits
  5790. let e = 0; // zero exponent
  5791. // normalized
  5792. while ( ( m & 0x00800000 ) === 0 ) {
  5793. m <<= 1;
  5794. e -= 0x00800000; // decrement exponent
  5795. }
  5796. m &= ~ 0x00800000; // clear leading 1 bit
  5797. e += 0x38800000; // adjust bias
  5798. mantissaTable[ i ] = m | e;
  5799. }
  5800. for ( let i = 1024; i < 2048; ++ i ) {
  5801. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  5802. }
  5803. for ( let i = 1; i < 31; ++ i ) {
  5804. exponentTable[ i ] = i << 23;
  5805. }
  5806. exponentTable[ 31 ] = 0x47800000;
  5807. exponentTable[ 32 ] = 0x80000000;
  5808. for ( let i = 33; i < 63; ++ i ) {
  5809. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  5810. }
  5811. exponentTable[ 63 ] = 0xc7800000;
  5812. for ( let i = 1; i < 64; ++ i ) {
  5813. if ( i !== 32 ) {
  5814. offsetTable[ i ] = 1024;
  5815. }
  5816. }
  5817. return {
  5818. floatView: floatView,
  5819. uint32View: uint32View,
  5820. baseTable: baseTable,
  5821. shiftTable: shiftTable,
  5822. mantissaTable: mantissaTable,
  5823. exponentTable: exponentTable,
  5824. offsetTable: offsetTable
  5825. };
  5826. }
  5827. // float32 to float16
  5828. function toHalfFloat( val ) {
  5829. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  5830. val = clamp( val, - 65504, 65504 );
  5831. _tables.floatView[ 0 ] = val;
  5832. const f = _tables.uint32View[ 0 ];
  5833. const e = ( f >> 23 ) & 0x1ff;
  5834. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  5835. }
  5836. // float16 to float32
  5837. function fromHalfFloat( val ) {
  5838. const m = val >> 10;
  5839. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  5840. return _tables.floatView[ 0 ];
  5841. }
  5842. const DataUtils = {
  5843. toHalfFloat: toHalfFloat,
  5844. fromHalfFloat: fromHalfFloat,
  5845. };
  5846. const _vector$8 = /*@__PURE__*/ new Vector3();
  5847. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5848. class BufferAttribute {
  5849. constructor( array, itemSize, normalized = false ) {
  5850. if ( Array.isArray( array ) ) {
  5851. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5852. }
  5853. this.isBufferAttribute = true;
  5854. this.name = '';
  5855. this.array = array;
  5856. this.itemSize = itemSize;
  5857. this.count = array !== undefined ? array.length / itemSize : 0;
  5858. this.normalized = normalized;
  5859. this.usage = StaticDrawUsage;
  5860. this.updateRange = { offset: 0, count: - 1 };
  5861. this.gpuType = FloatType;
  5862. this.version = 0;
  5863. }
  5864. onUploadCallback() {}
  5865. set needsUpdate( value ) {
  5866. if ( value === true ) this.version ++;
  5867. }
  5868. setUsage( value ) {
  5869. this.usage = value;
  5870. return this;
  5871. }
  5872. copy( source ) {
  5873. this.name = source.name;
  5874. this.array = new source.array.constructor( source.array );
  5875. this.itemSize = source.itemSize;
  5876. this.count = source.count;
  5877. this.normalized = source.normalized;
  5878. this.usage = source.usage;
  5879. this.gpuType = source.gpuType;
  5880. return this;
  5881. }
  5882. copyAt( index1, attribute, index2 ) {
  5883. index1 *= this.itemSize;
  5884. index2 *= attribute.itemSize;
  5885. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5886. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5887. }
  5888. return this;
  5889. }
  5890. copyArray( array ) {
  5891. this.array.set( array );
  5892. return this;
  5893. }
  5894. applyMatrix3( m ) {
  5895. if ( this.itemSize === 2 ) {
  5896. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5897. _vector2$1.fromBufferAttribute( this, i );
  5898. _vector2$1.applyMatrix3( m );
  5899. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5900. }
  5901. } else if ( this.itemSize === 3 ) {
  5902. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5903. _vector$8.fromBufferAttribute( this, i );
  5904. _vector$8.applyMatrix3( m );
  5905. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  5906. }
  5907. }
  5908. return this;
  5909. }
  5910. applyMatrix4( m ) {
  5911. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5912. _vector$8.fromBufferAttribute( this, i );
  5913. _vector$8.applyMatrix4( m );
  5914. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  5915. }
  5916. return this;
  5917. }
  5918. applyNormalMatrix( m ) {
  5919. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5920. _vector$8.fromBufferAttribute( this, i );
  5921. _vector$8.applyNormalMatrix( m );
  5922. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  5923. }
  5924. return this;
  5925. }
  5926. transformDirection( m ) {
  5927. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5928. _vector$8.fromBufferAttribute( this, i );
  5929. _vector$8.transformDirection( m );
  5930. this.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  5931. }
  5932. return this;
  5933. }
  5934. set( value, offset = 0 ) {
  5935. // Matching BufferAttribute constructor, do not normalize the array.
  5936. this.array.set( value, offset );
  5937. return this;
  5938. }
  5939. getX( index ) {
  5940. let x = this.array[ index * this.itemSize ];
  5941. if ( this.normalized ) x = denormalize( x, this.array );
  5942. return x;
  5943. }
  5944. setX( index, x ) {
  5945. if ( this.normalized ) x = normalize( x, this.array );
  5946. this.array[ index * this.itemSize ] = x;
  5947. return this;
  5948. }
  5949. getY( index ) {
  5950. let y = this.array[ index * this.itemSize + 1 ];
  5951. if ( this.normalized ) y = denormalize( y, this.array );
  5952. return y;
  5953. }
  5954. setY( index, y ) {
  5955. if ( this.normalized ) y = normalize( y, this.array );
  5956. this.array[ index * this.itemSize + 1 ] = y;
  5957. return this;
  5958. }
  5959. getZ( index ) {
  5960. let z = this.array[ index * this.itemSize + 2 ];
  5961. if ( this.normalized ) z = denormalize( z, this.array );
  5962. return z;
  5963. }
  5964. setZ( index, z ) {
  5965. if ( this.normalized ) z = normalize( z, this.array );
  5966. this.array[ index * this.itemSize + 2 ] = z;
  5967. return this;
  5968. }
  5969. getW( index ) {
  5970. let w = this.array[ index * this.itemSize + 3 ];
  5971. if ( this.normalized ) w = denormalize( w, this.array );
  5972. return w;
  5973. }
  5974. setW( index, w ) {
  5975. if ( this.normalized ) w = normalize( w, this.array );
  5976. this.array[ index * this.itemSize + 3 ] = w;
  5977. return this;
  5978. }
  5979. setXY( index, x, y ) {
  5980. index *= this.itemSize;
  5981. if ( this.normalized ) {
  5982. x = normalize( x, this.array );
  5983. y = normalize( y, this.array );
  5984. }
  5985. this.array[ index + 0 ] = x;
  5986. this.array[ index + 1 ] = y;
  5987. return this;
  5988. }
  5989. setXYZ( index, x, y, z ) {
  5990. index *= this.itemSize;
  5991. if ( this.normalized ) {
  5992. x = normalize( x, this.array );
  5993. y = normalize( y, this.array );
  5994. z = normalize( z, this.array );
  5995. }
  5996. this.array[ index + 0 ] = x;
  5997. this.array[ index + 1 ] = y;
  5998. this.array[ index + 2 ] = z;
  5999. return this;
  6000. }
  6001. setXYZW( index, x, y, z, w ) {
  6002. index *= this.itemSize;
  6003. if ( this.normalized ) {
  6004. x = normalize( x, this.array );
  6005. y = normalize( y, this.array );
  6006. z = normalize( z, this.array );
  6007. w = normalize( w, this.array );
  6008. }
  6009. this.array[ index + 0 ] = x;
  6010. this.array[ index + 1 ] = y;
  6011. this.array[ index + 2 ] = z;
  6012. this.array[ index + 3 ] = w;
  6013. return this;
  6014. }
  6015. onUpload( callback ) {
  6016. this.onUploadCallback = callback;
  6017. return this;
  6018. }
  6019. clone() {
  6020. return new this.constructor( this.array, this.itemSize ).copy( this );
  6021. }
  6022. toJSON() {
  6023. const data = {
  6024. itemSize: this.itemSize,
  6025. type: this.array.constructor.name,
  6026. array: Array.from( this.array ),
  6027. normalized: this.normalized
  6028. };
  6029. if ( this.name !== '' ) data.name = this.name;
  6030. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  6031. if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange;
  6032. return data;
  6033. }
  6034. }
  6035. //
  6036. class Int8BufferAttribute extends BufferAttribute {
  6037. constructor( array, itemSize, normalized ) {
  6038. super( new Int8Array( array ), itemSize, normalized );
  6039. }
  6040. }
  6041. class Uint8BufferAttribute extends BufferAttribute {
  6042. constructor( array, itemSize, normalized ) {
  6043. super( new Uint8Array( array ), itemSize, normalized );
  6044. }
  6045. }
  6046. class Uint8ClampedBufferAttribute extends BufferAttribute {
  6047. constructor( array, itemSize, normalized ) {
  6048. super( new Uint8ClampedArray( array ), itemSize, normalized );
  6049. }
  6050. }
  6051. class Int16BufferAttribute extends BufferAttribute {
  6052. constructor( array, itemSize, normalized ) {
  6053. super( new Int16Array( array ), itemSize, normalized );
  6054. }
  6055. }
  6056. class Uint16BufferAttribute extends BufferAttribute {
  6057. constructor( array, itemSize, normalized ) {
  6058. super( new Uint16Array( array ), itemSize, normalized );
  6059. }
  6060. }
  6061. class Int32BufferAttribute extends BufferAttribute {
  6062. constructor( array, itemSize, normalized ) {
  6063. super( new Int32Array( array ), itemSize, normalized );
  6064. }
  6065. }
  6066. class Uint32BufferAttribute extends BufferAttribute {
  6067. constructor( array, itemSize, normalized ) {
  6068. super( new Uint32Array( array ), itemSize, normalized );
  6069. }
  6070. }
  6071. class Float16BufferAttribute extends BufferAttribute {
  6072. constructor( array, itemSize, normalized ) {
  6073. super( new Uint16Array( array ), itemSize, normalized );
  6074. this.isFloat16BufferAttribute = true;
  6075. }
  6076. getX( index ) {
  6077. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  6078. if ( this.normalized ) x = denormalize( x, this.array );
  6079. return x;
  6080. }
  6081. setX( index, x ) {
  6082. if ( this.normalized ) x = normalize( x, this.array );
  6083. this.array[ index * this.itemSize ] = toHalfFloat( x );
  6084. return this;
  6085. }
  6086. getY( index ) {
  6087. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  6088. if ( this.normalized ) y = denormalize( y, this.array );
  6089. return y;
  6090. }
  6091. setY( index, y ) {
  6092. if ( this.normalized ) y = normalize( y, this.array );
  6093. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  6094. return this;
  6095. }
  6096. getZ( index ) {
  6097. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  6098. if ( this.normalized ) z = denormalize( z, this.array );
  6099. return z;
  6100. }
  6101. setZ( index, z ) {
  6102. if ( this.normalized ) z = normalize( z, this.array );
  6103. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  6104. return this;
  6105. }
  6106. getW( index ) {
  6107. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  6108. if ( this.normalized ) w = denormalize( w, this.array );
  6109. return w;
  6110. }
  6111. setW( index, w ) {
  6112. if ( this.normalized ) w = normalize( w, this.array );
  6113. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  6114. return this;
  6115. }
  6116. setXY( index, x, y ) {
  6117. index *= this.itemSize;
  6118. if ( this.normalized ) {
  6119. x = normalize( x, this.array );
  6120. y = normalize( y, this.array );
  6121. }
  6122. this.array[ index + 0 ] = toHalfFloat( x );
  6123. this.array[ index + 1 ] = toHalfFloat( y );
  6124. return this;
  6125. }
  6126. setXYZ( index, x, y, z ) {
  6127. index *= this.itemSize;
  6128. if ( this.normalized ) {
  6129. x = normalize( x, this.array );
  6130. y = normalize( y, this.array );
  6131. z = normalize( z, this.array );
  6132. }
  6133. this.array[ index + 0 ] = toHalfFloat( x );
  6134. this.array[ index + 1 ] = toHalfFloat( y );
  6135. this.array[ index + 2 ] = toHalfFloat( z );
  6136. return this;
  6137. }
  6138. setXYZW( index, x, y, z, w ) {
  6139. index *= this.itemSize;
  6140. if ( this.normalized ) {
  6141. x = normalize( x, this.array );
  6142. y = normalize( y, this.array );
  6143. z = normalize( z, this.array );
  6144. w = normalize( w, this.array );
  6145. }
  6146. this.array[ index + 0 ] = toHalfFloat( x );
  6147. this.array[ index + 1 ] = toHalfFloat( y );
  6148. this.array[ index + 2 ] = toHalfFloat( z );
  6149. this.array[ index + 3 ] = toHalfFloat( w );
  6150. return this;
  6151. }
  6152. }
  6153. class Float32BufferAttribute extends BufferAttribute {
  6154. constructor( array, itemSize, normalized ) {
  6155. super( new Float32Array( array ), itemSize, normalized );
  6156. }
  6157. }
  6158. class Float64BufferAttribute extends BufferAttribute {
  6159. constructor( array, itemSize, normalized ) {
  6160. super( new Float64Array( array ), itemSize, normalized );
  6161. }
  6162. }
  6163. let _id$1 = 0;
  6164. const _m1 = /*@__PURE__*/ new Matrix4();
  6165. const _obj = /*@__PURE__*/ new Object3D();
  6166. const _offset = /*@__PURE__*/ new Vector3();
  6167. const _box$1 = /*@__PURE__*/ new Box3();
  6168. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6169. const _vector$7 = /*@__PURE__*/ new Vector3();
  6170. class BufferGeometry extends EventDispatcher {
  6171. constructor() {
  6172. super();
  6173. this.isBufferGeometry = true;
  6174. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  6175. this.uuid = generateUUID();
  6176. this.name = '';
  6177. this.type = 'BufferGeometry';
  6178. this.index = null;
  6179. this.attributes = {};
  6180. this.morphAttributes = {};
  6181. this.morphTargetsRelative = false;
  6182. this.groups = [];
  6183. this.boundingBox = null;
  6184. this.boundingSphere = null;
  6185. this.drawRange = { start: 0, count: Infinity };
  6186. this.userData = {};
  6187. }
  6188. getIndex() {
  6189. return this.index;
  6190. }
  6191. setIndex( index ) {
  6192. if ( Array.isArray( index ) ) {
  6193. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6194. } else {
  6195. this.index = index;
  6196. }
  6197. return this;
  6198. }
  6199. getAttribute( name ) {
  6200. return this.attributes[ name ];
  6201. }
  6202. setAttribute( name, attribute ) {
  6203. this.attributes[ name ] = attribute;
  6204. return this;
  6205. }
  6206. deleteAttribute( name ) {
  6207. delete this.attributes[ name ];
  6208. return this;
  6209. }
  6210. hasAttribute( name ) {
  6211. return this.attributes[ name ] !== undefined;
  6212. }
  6213. addGroup( start, count, materialIndex = 0 ) {
  6214. this.groups.push( {
  6215. start: start,
  6216. count: count,
  6217. materialIndex: materialIndex
  6218. } );
  6219. }
  6220. clearGroups() {
  6221. this.groups = [];
  6222. }
  6223. setDrawRange( start, count ) {
  6224. this.drawRange.start = start;
  6225. this.drawRange.count = count;
  6226. }
  6227. applyMatrix4( matrix ) {
  6228. const position = this.attributes.position;
  6229. if ( position !== undefined ) {
  6230. position.applyMatrix4( matrix );
  6231. position.needsUpdate = true;
  6232. }
  6233. const normal = this.attributes.normal;
  6234. if ( normal !== undefined ) {
  6235. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6236. normal.applyNormalMatrix( normalMatrix );
  6237. normal.needsUpdate = true;
  6238. }
  6239. const tangent = this.attributes.tangent;
  6240. if ( tangent !== undefined ) {
  6241. tangent.transformDirection( matrix );
  6242. tangent.needsUpdate = true;
  6243. }
  6244. if ( this.boundingBox !== null ) {
  6245. this.computeBoundingBox();
  6246. }
  6247. if ( this.boundingSphere !== null ) {
  6248. this.computeBoundingSphere();
  6249. }
  6250. return this;
  6251. }
  6252. applyQuaternion( q ) {
  6253. _m1.makeRotationFromQuaternion( q );
  6254. this.applyMatrix4( _m1 );
  6255. return this;
  6256. }
  6257. rotateX( angle ) {
  6258. // rotate geometry around world x-axis
  6259. _m1.makeRotationX( angle );
  6260. this.applyMatrix4( _m1 );
  6261. return this;
  6262. }
  6263. rotateY( angle ) {
  6264. // rotate geometry around world y-axis
  6265. _m1.makeRotationY( angle );
  6266. this.applyMatrix4( _m1 );
  6267. return this;
  6268. }
  6269. rotateZ( angle ) {
  6270. // rotate geometry around world z-axis
  6271. _m1.makeRotationZ( angle );
  6272. this.applyMatrix4( _m1 );
  6273. return this;
  6274. }
  6275. translate( x, y, z ) {
  6276. // translate geometry
  6277. _m1.makeTranslation( x, y, z );
  6278. this.applyMatrix4( _m1 );
  6279. return this;
  6280. }
  6281. scale( x, y, z ) {
  6282. // scale geometry
  6283. _m1.makeScale( x, y, z );
  6284. this.applyMatrix4( _m1 );
  6285. return this;
  6286. }
  6287. lookAt( vector ) {
  6288. _obj.lookAt( vector );
  6289. _obj.updateMatrix();
  6290. this.applyMatrix4( _obj.matrix );
  6291. return this;
  6292. }
  6293. center() {
  6294. this.computeBoundingBox();
  6295. this.boundingBox.getCenter( _offset ).negate();
  6296. this.translate( _offset.x, _offset.y, _offset.z );
  6297. return this;
  6298. }
  6299. setFromPoints( points ) {
  6300. const position = [];
  6301. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6302. const point = points[ i ];
  6303. position.push( point.x, point.y, point.z || 0 );
  6304. }
  6305. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6306. return this;
  6307. }
  6308. computeBoundingBox() {
  6309. if ( this.boundingBox === null ) {
  6310. this.boundingBox = new Box3();
  6311. }
  6312. const position = this.attributes.position;
  6313. const morphAttributesPosition = this.morphAttributes.position;
  6314. if ( position && position.isGLBufferAttribute ) {
  6315. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  6316. this.boundingBox.set(
  6317. new Vector3( - Infinity, - Infinity, - Infinity ),
  6318. new Vector3( + Infinity, + Infinity, + Infinity )
  6319. );
  6320. return;
  6321. }
  6322. if ( position !== undefined ) {
  6323. this.boundingBox.setFromBufferAttribute( position );
  6324. // process morph attributes if present
  6325. if ( morphAttributesPosition ) {
  6326. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6327. const morphAttribute = morphAttributesPosition[ i ];
  6328. _box$1.setFromBufferAttribute( morphAttribute );
  6329. if ( this.morphTargetsRelative ) {
  6330. _vector$7.addVectors( this.boundingBox.min, _box$1.min );
  6331. this.boundingBox.expandByPoint( _vector$7 );
  6332. _vector$7.addVectors( this.boundingBox.max, _box$1.max );
  6333. this.boundingBox.expandByPoint( _vector$7 );
  6334. } else {
  6335. this.boundingBox.expandByPoint( _box$1.min );
  6336. this.boundingBox.expandByPoint( _box$1.max );
  6337. }
  6338. }
  6339. }
  6340. } else {
  6341. this.boundingBox.makeEmpty();
  6342. }
  6343. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6344. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6345. }
  6346. }
  6347. computeBoundingSphere() {
  6348. if ( this.boundingSphere === null ) {
  6349. this.boundingSphere = new Sphere();
  6350. }
  6351. const position = this.attributes.position;
  6352. const morphAttributesPosition = this.morphAttributes.position;
  6353. if ( position && position.isGLBufferAttribute ) {
  6354. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  6355. this.boundingSphere.set( new Vector3(), Infinity );
  6356. return;
  6357. }
  6358. if ( position ) {
  6359. // first, find the center of the bounding sphere
  6360. const center = this.boundingSphere.center;
  6361. _box$1.setFromBufferAttribute( position );
  6362. // process morph attributes if present
  6363. if ( morphAttributesPosition ) {
  6364. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6365. const morphAttribute = morphAttributesPosition[ i ];
  6366. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6367. if ( this.morphTargetsRelative ) {
  6368. _vector$7.addVectors( _box$1.min, _boxMorphTargets.min );
  6369. _box$1.expandByPoint( _vector$7 );
  6370. _vector$7.addVectors( _box$1.max, _boxMorphTargets.max );
  6371. _box$1.expandByPoint( _vector$7 );
  6372. } else {
  6373. _box$1.expandByPoint( _boxMorphTargets.min );
  6374. _box$1.expandByPoint( _boxMorphTargets.max );
  6375. }
  6376. }
  6377. }
  6378. _box$1.getCenter( center );
  6379. // second, try to find a boundingSphere with a radius smaller than the
  6380. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6381. let maxRadiusSq = 0;
  6382. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6383. _vector$7.fromBufferAttribute( position, i );
  6384. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$7 ) );
  6385. }
  6386. // process morph attributes if present
  6387. if ( morphAttributesPosition ) {
  6388. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6389. const morphAttribute = morphAttributesPosition[ i ];
  6390. const morphTargetsRelative = this.morphTargetsRelative;
  6391. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6392. _vector$7.fromBufferAttribute( morphAttribute, j );
  6393. if ( morphTargetsRelative ) {
  6394. _offset.fromBufferAttribute( position, j );
  6395. _vector$7.add( _offset );
  6396. }
  6397. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$7 ) );
  6398. }
  6399. }
  6400. }
  6401. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6402. if ( isNaN( this.boundingSphere.radius ) ) {
  6403. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6404. }
  6405. }
  6406. }
  6407. computeTangents() {
  6408. const index = this.index;
  6409. const attributes = this.attributes;
  6410. // based on http://www.terathon.com/code/tangent.html
  6411. // (per vertex tangents)
  6412. if ( index === null ||
  6413. attributes.position === undefined ||
  6414. attributes.normal === undefined ||
  6415. attributes.uv === undefined ) {
  6416. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6417. return;
  6418. }
  6419. const indices = index.array;
  6420. const positions = attributes.position.array;
  6421. const normals = attributes.normal.array;
  6422. const uvs = attributes.uv.array;
  6423. const nVertices = positions.length / 3;
  6424. if ( this.hasAttribute( 'tangent' ) === false ) {
  6425. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  6426. }
  6427. const tangents = this.getAttribute( 'tangent' ).array;
  6428. const tan1 = [], tan2 = [];
  6429. for ( let i = 0; i < nVertices; i ++ ) {
  6430. tan1[ i ] = new Vector3();
  6431. tan2[ i ] = new Vector3();
  6432. }
  6433. const vA = new Vector3(),
  6434. vB = new Vector3(),
  6435. vC = new Vector3(),
  6436. uvA = new Vector2(),
  6437. uvB = new Vector2(),
  6438. uvC = new Vector2(),
  6439. sdir = new Vector3(),
  6440. tdir = new Vector3();
  6441. function handleTriangle( a, b, c ) {
  6442. vA.fromArray( positions, a * 3 );
  6443. vB.fromArray( positions, b * 3 );
  6444. vC.fromArray( positions, c * 3 );
  6445. uvA.fromArray( uvs, a * 2 );
  6446. uvB.fromArray( uvs, b * 2 );
  6447. uvC.fromArray( uvs, c * 2 );
  6448. vB.sub( vA );
  6449. vC.sub( vA );
  6450. uvB.sub( uvA );
  6451. uvC.sub( uvA );
  6452. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6453. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6454. if ( ! isFinite( r ) ) return;
  6455. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6456. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6457. tan1[ a ].add( sdir );
  6458. tan1[ b ].add( sdir );
  6459. tan1[ c ].add( sdir );
  6460. tan2[ a ].add( tdir );
  6461. tan2[ b ].add( tdir );
  6462. tan2[ c ].add( tdir );
  6463. }
  6464. let groups = this.groups;
  6465. if ( groups.length === 0 ) {
  6466. groups = [ {
  6467. start: 0,
  6468. count: indices.length
  6469. } ];
  6470. }
  6471. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6472. const group = groups[ i ];
  6473. const start = group.start;
  6474. const count = group.count;
  6475. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6476. handleTriangle(
  6477. indices[ j + 0 ],
  6478. indices[ j + 1 ],
  6479. indices[ j + 2 ]
  6480. );
  6481. }
  6482. }
  6483. const tmp = new Vector3(), tmp2 = new Vector3();
  6484. const n = new Vector3(), n2 = new Vector3();
  6485. function handleVertex( v ) {
  6486. n.fromArray( normals, v * 3 );
  6487. n2.copy( n );
  6488. const t = tan1[ v ];
  6489. // Gram-Schmidt orthogonalize
  6490. tmp.copy( t );
  6491. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6492. // Calculate handedness
  6493. tmp2.crossVectors( n2, t );
  6494. const test = tmp2.dot( tan2[ v ] );
  6495. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6496. tangents[ v * 4 ] = tmp.x;
  6497. tangents[ v * 4 + 1 ] = tmp.y;
  6498. tangents[ v * 4 + 2 ] = tmp.z;
  6499. tangents[ v * 4 + 3 ] = w;
  6500. }
  6501. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6502. const group = groups[ i ];
  6503. const start = group.start;
  6504. const count = group.count;
  6505. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6506. handleVertex( indices[ j + 0 ] );
  6507. handleVertex( indices[ j + 1 ] );
  6508. handleVertex( indices[ j + 2 ] );
  6509. }
  6510. }
  6511. }
  6512. computeVertexNormals() {
  6513. const index = this.index;
  6514. const positionAttribute = this.getAttribute( 'position' );
  6515. if ( positionAttribute !== undefined ) {
  6516. let normalAttribute = this.getAttribute( 'normal' );
  6517. if ( normalAttribute === undefined ) {
  6518. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6519. this.setAttribute( 'normal', normalAttribute );
  6520. } else {
  6521. // reset existing normals to zero
  6522. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6523. normalAttribute.setXYZ( i, 0, 0, 0 );
  6524. }
  6525. }
  6526. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6527. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6528. const cb = new Vector3(), ab = new Vector3();
  6529. // indexed elements
  6530. if ( index ) {
  6531. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6532. const vA = index.getX( i + 0 );
  6533. const vB = index.getX( i + 1 );
  6534. const vC = index.getX( i + 2 );
  6535. pA.fromBufferAttribute( positionAttribute, vA );
  6536. pB.fromBufferAttribute( positionAttribute, vB );
  6537. pC.fromBufferAttribute( positionAttribute, vC );
  6538. cb.subVectors( pC, pB );
  6539. ab.subVectors( pA, pB );
  6540. cb.cross( ab );
  6541. nA.fromBufferAttribute( normalAttribute, vA );
  6542. nB.fromBufferAttribute( normalAttribute, vB );
  6543. nC.fromBufferAttribute( normalAttribute, vC );
  6544. nA.add( cb );
  6545. nB.add( cb );
  6546. nC.add( cb );
  6547. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6548. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6549. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6550. }
  6551. } else {
  6552. // non-indexed elements (unconnected triangle soup)
  6553. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6554. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6555. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6556. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6557. cb.subVectors( pC, pB );
  6558. ab.subVectors( pA, pB );
  6559. cb.cross( ab );
  6560. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6561. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6562. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6563. }
  6564. }
  6565. this.normalizeNormals();
  6566. normalAttribute.needsUpdate = true;
  6567. }
  6568. }
  6569. normalizeNormals() {
  6570. const normals = this.attributes.normal;
  6571. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6572. _vector$7.fromBufferAttribute( normals, i );
  6573. _vector$7.normalize();
  6574. normals.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  6575. }
  6576. }
  6577. toNonIndexed() {
  6578. function convertBufferAttribute( attribute, indices ) {
  6579. const array = attribute.array;
  6580. const itemSize = attribute.itemSize;
  6581. const normalized = attribute.normalized;
  6582. const array2 = new array.constructor( indices.length * itemSize );
  6583. let index = 0, index2 = 0;
  6584. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6585. if ( attribute.isInterleavedBufferAttribute ) {
  6586. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6587. } else {
  6588. index = indices[ i ] * itemSize;
  6589. }
  6590. for ( let j = 0; j < itemSize; j ++ ) {
  6591. array2[ index2 ++ ] = array[ index ++ ];
  6592. }
  6593. }
  6594. return new BufferAttribute( array2, itemSize, normalized );
  6595. }
  6596. //
  6597. if ( this.index === null ) {
  6598. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6599. return this;
  6600. }
  6601. const geometry2 = new BufferGeometry();
  6602. const indices = this.index.array;
  6603. const attributes = this.attributes;
  6604. // attributes
  6605. for ( const name in attributes ) {
  6606. const attribute = attributes[ name ];
  6607. const newAttribute = convertBufferAttribute( attribute, indices );
  6608. geometry2.setAttribute( name, newAttribute );
  6609. }
  6610. // morph attributes
  6611. const morphAttributes = this.morphAttributes;
  6612. for ( const name in morphAttributes ) {
  6613. const morphArray = [];
  6614. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6615. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6616. const attribute = morphAttribute[ i ];
  6617. const newAttribute = convertBufferAttribute( attribute, indices );
  6618. morphArray.push( newAttribute );
  6619. }
  6620. geometry2.morphAttributes[ name ] = morphArray;
  6621. }
  6622. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6623. // groups
  6624. const groups = this.groups;
  6625. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6626. const group = groups[ i ];
  6627. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6628. }
  6629. return geometry2;
  6630. }
  6631. toJSON() {
  6632. const data = {
  6633. metadata: {
  6634. version: 4.6,
  6635. type: 'BufferGeometry',
  6636. generator: 'BufferGeometry.toJSON'
  6637. }
  6638. };
  6639. // standard BufferGeometry serialization
  6640. data.uuid = this.uuid;
  6641. data.type = this.type;
  6642. if ( this.name !== '' ) data.name = this.name;
  6643. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6644. if ( this.parameters !== undefined ) {
  6645. const parameters = this.parameters;
  6646. for ( const key in parameters ) {
  6647. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6648. }
  6649. return data;
  6650. }
  6651. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6652. data.data = { attributes: {} };
  6653. const index = this.index;
  6654. if ( index !== null ) {
  6655. data.data.index = {
  6656. type: index.array.constructor.name,
  6657. array: Array.prototype.slice.call( index.array )
  6658. };
  6659. }
  6660. const attributes = this.attributes;
  6661. for ( const key in attributes ) {
  6662. const attribute = attributes[ key ];
  6663. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6664. }
  6665. const morphAttributes = {};
  6666. let hasMorphAttributes = false;
  6667. for ( const key in this.morphAttributes ) {
  6668. const attributeArray = this.morphAttributes[ key ];
  6669. const array = [];
  6670. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6671. const attribute = attributeArray[ i ];
  6672. array.push( attribute.toJSON( data.data ) );
  6673. }
  6674. if ( array.length > 0 ) {
  6675. morphAttributes[ key ] = array;
  6676. hasMorphAttributes = true;
  6677. }
  6678. }
  6679. if ( hasMorphAttributes ) {
  6680. data.data.morphAttributes = morphAttributes;
  6681. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6682. }
  6683. const groups = this.groups;
  6684. if ( groups.length > 0 ) {
  6685. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6686. }
  6687. const boundingSphere = this.boundingSphere;
  6688. if ( boundingSphere !== null ) {
  6689. data.data.boundingSphere = {
  6690. center: boundingSphere.center.toArray(),
  6691. radius: boundingSphere.radius
  6692. };
  6693. }
  6694. return data;
  6695. }
  6696. clone() {
  6697. return new this.constructor().copy( this );
  6698. }
  6699. copy( source ) {
  6700. // reset
  6701. this.index = null;
  6702. this.attributes = {};
  6703. this.morphAttributes = {};
  6704. this.groups = [];
  6705. this.boundingBox = null;
  6706. this.boundingSphere = null;
  6707. // used for storing cloned, shared data
  6708. const data = {};
  6709. // name
  6710. this.name = source.name;
  6711. // index
  6712. const index = source.index;
  6713. if ( index !== null ) {
  6714. this.setIndex( index.clone( data ) );
  6715. }
  6716. // attributes
  6717. const attributes = source.attributes;
  6718. for ( const name in attributes ) {
  6719. const attribute = attributes[ name ];
  6720. this.setAttribute( name, attribute.clone( data ) );
  6721. }
  6722. // morph attributes
  6723. const morphAttributes = source.morphAttributes;
  6724. for ( const name in morphAttributes ) {
  6725. const array = [];
  6726. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6727. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6728. array.push( morphAttribute[ i ].clone( data ) );
  6729. }
  6730. this.morphAttributes[ name ] = array;
  6731. }
  6732. this.morphTargetsRelative = source.morphTargetsRelative;
  6733. // groups
  6734. const groups = source.groups;
  6735. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6736. const group = groups[ i ];
  6737. this.addGroup( group.start, group.count, group.materialIndex );
  6738. }
  6739. // bounding box
  6740. const boundingBox = source.boundingBox;
  6741. if ( boundingBox !== null ) {
  6742. this.boundingBox = boundingBox.clone();
  6743. }
  6744. // bounding sphere
  6745. const boundingSphere = source.boundingSphere;
  6746. if ( boundingSphere !== null ) {
  6747. this.boundingSphere = boundingSphere.clone();
  6748. }
  6749. // draw range
  6750. this.drawRange.start = source.drawRange.start;
  6751. this.drawRange.count = source.drawRange.count;
  6752. // user data
  6753. this.userData = source.userData;
  6754. return this;
  6755. }
  6756. dispose() {
  6757. this.dispatchEvent( { type: 'dispose' } );
  6758. }
  6759. }
  6760. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  6761. const _ray$3 = /*@__PURE__*/ new Ray();
  6762. const _sphere$5 = /*@__PURE__*/ new Sphere();
  6763. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6764. const _vA$1 = /*@__PURE__*/ new Vector3();
  6765. const _vB$1 = /*@__PURE__*/ new Vector3();
  6766. const _vC$1 = /*@__PURE__*/ new Vector3();
  6767. const _tempA = /*@__PURE__*/ new Vector3();
  6768. const _morphA = /*@__PURE__*/ new Vector3();
  6769. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6770. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6771. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6772. const _normalA = /*@__PURE__*/ new Vector3();
  6773. const _normalB = /*@__PURE__*/ new Vector3();
  6774. const _normalC = /*@__PURE__*/ new Vector3();
  6775. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6776. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6777. class Mesh extends Object3D {
  6778. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6779. super();
  6780. this.isMesh = true;
  6781. this.type = 'Mesh';
  6782. this.geometry = geometry;
  6783. this.material = material;
  6784. this.updateMorphTargets();
  6785. }
  6786. copy( source, recursive ) {
  6787. super.copy( source, recursive );
  6788. if ( source.morphTargetInfluences !== undefined ) {
  6789. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6790. }
  6791. if ( source.morphTargetDictionary !== undefined ) {
  6792. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6793. }
  6794. this.material = source.material;
  6795. this.geometry = source.geometry;
  6796. return this;
  6797. }
  6798. updateMorphTargets() {
  6799. const geometry = this.geometry;
  6800. const morphAttributes = geometry.morphAttributes;
  6801. const keys = Object.keys( morphAttributes );
  6802. if ( keys.length > 0 ) {
  6803. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6804. if ( morphAttribute !== undefined ) {
  6805. this.morphTargetInfluences = [];
  6806. this.morphTargetDictionary = {};
  6807. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6808. const name = morphAttribute[ m ].name || String( m );
  6809. this.morphTargetInfluences.push( 0 );
  6810. this.morphTargetDictionary[ name ] = m;
  6811. }
  6812. }
  6813. }
  6814. }
  6815. getVertexPosition( index, target ) {
  6816. const geometry = this.geometry;
  6817. const position = geometry.attributes.position;
  6818. const morphPosition = geometry.morphAttributes.position;
  6819. const morphTargetsRelative = geometry.morphTargetsRelative;
  6820. target.fromBufferAttribute( position, index );
  6821. const morphInfluences = this.morphTargetInfluences;
  6822. if ( morphPosition && morphInfluences ) {
  6823. _morphA.set( 0, 0, 0 );
  6824. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6825. const influence = morphInfluences[ i ];
  6826. const morphAttribute = morphPosition[ i ];
  6827. if ( influence === 0 ) continue;
  6828. _tempA.fromBufferAttribute( morphAttribute, index );
  6829. if ( morphTargetsRelative ) {
  6830. _morphA.addScaledVector( _tempA, influence );
  6831. } else {
  6832. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6833. }
  6834. }
  6835. target.add( _morphA );
  6836. }
  6837. return target;
  6838. }
  6839. raycast( raycaster, intersects ) {
  6840. const geometry = this.geometry;
  6841. const material = this.material;
  6842. const matrixWorld = this.matrixWorld;
  6843. if ( material === undefined ) return;
  6844. // test with bounding sphere in world space
  6845. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6846. _sphere$5.copy( geometry.boundingSphere );
  6847. _sphere$5.applyMatrix4( matrixWorld );
  6848. // check distance from ray origin to bounding sphere
  6849. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  6850. if ( _sphere$5.containsPoint( _ray$3.origin ) === false ) {
  6851. if ( _ray$3.intersectSphere( _sphere$5, _sphereHitAt ) === null ) return;
  6852. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  6853. }
  6854. // convert ray to local space of mesh
  6855. _inverseMatrix$3.copy( matrixWorld ).invert();
  6856. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  6857. // test with bounding box in local space
  6858. if ( geometry.boundingBox !== null ) {
  6859. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  6860. }
  6861. // test for intersections with geometry
  6862. this._computeIntersections( raycaster, intersects, _ray$3 );
  6863. }
  6864. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  6865. let intersection;
  6866. const geometry = this.geometry;
  6867. const material = this.material;
  6868. const index = geometry.index;
  6869. const position = geometry.attributes.position;
  6870. const uv = geometry.attributes.uv;
  6871. const uv1 = geometry.attributes.uv1;
  6872. const normal = geometry.attributes.normal;
  6873. const groups = geometry.groups;
  6874. const drawRange = geometry.drawRange;
  6875. if ( index !== null ) {
  6876. // indexed buffer geometry
  6877. if ( Array.isArray( material ) ) {
  6878. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6879. const group = groups[ i ];
  6880. const groupMaterial = material[ group.materialIndex ];
  6881. const start = Math.max( group.start, drawRange.start );
  6882. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6883. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6884. const a = index.getX( j );
  6885. const b = index.getX( j + 1 );
  6886. const c = index.getX( j + 2 );
  6887. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6888. if ( intersection ) {
  6889. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6890. intersection.face.materialIndex = group.materialIndex;
  6891. intersects.push( intersection );
  6892. }
  6893. }
  6894. }
  6895. } else {
  6896. const start = Math.max( 0, drawRange.start );
  6897. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6898. for ( let i = start, il = end; i < il; i += 3 ) {
  6899. const a = index.getX( i );
  6900. const b = index.getX( i + 1 );
  6901. const c = index.getX( i + 2 );
  6902. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6903. if ( intersection ) {
  6904. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6905. intersects.push( intersection );
  6906. }
  6907. }
  6908. }
  6909. } else if ( position !== undefined ) {
  6910. // non-indexed buffer geometry
  6911. if ( Array.isArray( material ) ) {
  6912. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6913. const group = groups[ i ];
  6914. const groupMaterial = material[ group.materialIndex ];
  6915. const start = Math.max( group.start, drawRange.start );
  6916. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6917. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6918. const a = j;
  6919. const b = j + 1;
  6920. const c = j + 2;
  6921. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6922. if ( intersection ) {
  6923. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6924. intersection.face.materialIndex = group.materialIndex;
  6925. intersects.push( intersection );
  6926. }
  6927. }
  6928. }
  6929. } else {
  6930. const start = Math.max( 0, drawRange.start );
  6931. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6932. for ( let i = start, il = end; i < il; i += 3 ) {
  6933. const a = i;
  6934. const b = i + 1;
  6935. const c = i + 2;
  6936. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  6937. if ( intersection ) {
  6938. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  6939. intersects.push( intersection );
  6940. }
  6941. }
  6942. }
  6943. }
  6944. }
  6945. }
  6946. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  6947. let intersect;
  6948. if ( material.side === BackSide ) {
  6949. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  6950. } else {
  6951. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  6952. }
  6953. if ( intersect === null ) return null;
  6954. _intersectionPointWorld.copy( point );
  6955. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  6956. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  6957. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  6958. return {
  6959. distance: distance,
  6960. point: _intersectionPointWorld.clone(),
  6961. object: object
  6962. };
  6963. }
  6964. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  6965. object.getVertexPosition( a, _vA$1 );
  6966. object.getVertexPosition( b, _vB$1 );
  6967. object.getVertexPosition( c, _vC$1 );
  6968. const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  6969. if ( intersection ) {
  6970. if ( uv ) {
  6971. _uvA$1.fromBufferAttribute( uv, a );
  6972. _uvB$1.fromBufferAttribute( uv, b );
  6973. _uvC$1.fromBufferAttribute( uv, c );
  6974. intersection.uv = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6975. }
  6976. if ( uv1 ) {
  6977. _uvA$1.fromBufferAttribute( uv1, a );
  6978. _uvB$1.fromBufferAttribute( uv1, b );
  6979. _uvC$1.fromBufferAttribute( uv1, c );
  6980. intersection.uv1 = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6981. intersection.uv2 = intersection.uv1; // @deprecated, r152
  6982. }
  6983. if ( normal ) {
  6984. _normalA.fromBufferAttribute( normal, a );
  6985. _normalB.fromBufferAttribute( normal, b );
  6986. _normalC.fromBufferAttribute( normal, c );
  6987. intersection.normal = Triangle.getInterpolation( _intersectionPoint, _vA$1, _vB$1, _vC$1, _normalA, _normalB, _normalC, new Vector3() );
  6988. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  6989. intersection.normal.multiplyScalar( - 1 );
  6990. }
  6991. }
  6992. const face = {
  6993. a: a,
  6994. b: b,
  6995. c: c,
  6996. normal: new Vector3(),
  6997. materialIndex: 0
  6998. };
  6999. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  7000. intersection.face = face;
  7001. }
  7002. return intersection;
  7003. }
  7004. class BoxGeometry extends BufferGeometry {
  7005. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  7006. super();
  7007. this.type = 'BoxGeometry';
  7008. this.parameters = {
  7009. width: width,
  7010. height: height,
  7011. depth: depth,
  7012. widthSegments: widthSegments,
  7013. heightSegments: heightSegments,
  7014. depthSegments: depthSegments
  7015. };
  7016. const scope = this;
  7017. // segments
  7018. widthSegments = Math.floor( widthSegments );
  7019. heightSegments = Math.floor( heightSegments );
  7020. depthSegments = Math.floor( depthSegments );
  7021. // buffers
  7022. const indices = [];
  7023. const vertices = [];
  7024. const normals = [];
  7025. const uvs = [];
  7026. // helper variables
  7027. let numberOfVertices = 0;
  7028. let groupStart = 0;
  7029. // build each side of the box geometry
  7030. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  7031. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  7032. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  7033. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  7034. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  7035. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  7036. // build geometry
  7037. this.setIndex( indices );
  7038. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7039. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7040. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7041. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  7042. const segmentWidth = width / gridX;
  7043. const segmentHeight = height / gridY;
  7044. const widthHalf = width / 2;
  7045. const heightHalf = height / 2;
  7046. const depthHalf = depth / 2;
  7047. const gridX1 = gridX + 1;
  7048. const gridY1 = gridY + 1;
  7049. let vertexCounter = 0;
  7050. let groupCount = 0;
  7051. const vector = new Vector3();
  7052. // generate vertices, normals and uvs
  7053. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7054. const y = iy * segmentHeight - heightHalf;
  7055. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7056. const x = ix * segmentWidth - widthHalf;
  7057. // set values to correct vector component
  7058. vector[ u ] = x * udir;
  7059. vector[ v ] = y * vdir;
  7060. vector[ w ] = depthHalf;
  7061. // now apply vector to vertex buffer
  7062. vertices.push( vector.x, vector.y, vector.z );
  7063. // set values to correct vector component
  7064. vector[ u ] = 0;
  7065. vector[ v ] = 0;
  7066. vector[ w ] = depth > 0 ? 1 : - 1;
  7067. // now apply vector to normal buffer
  7068. normals.push( vector.x, vector.y, vector.z );
  7069. // uvs
  7070. uvs.push( ix / gridX );
  7071. uvs.push( 1 - ( iy / gridY ) );
  7072. // counters
  7073. vertexCounter += 1;
  7074. }
  7075. }
  7076. // indices
  7077. // 1. you need three indices to draw a single face
  7078. // 2. a single segment consists of two faces
  7079. // 3. so we need to generate six (2*3) indices per segment
  7080. for ( let iy = 0; iy < gridY; iy ++ ) {
  7081. for ( let ix = 0; ix < gridX; ix ++ ) {
  7082. const a = numberOfVertices + ix + gridX1 * iy;
  7083. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  7084. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  7085. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  7086. // faces
  7087. indices.push( a, b, d );
  7088. indices.push( b, c, d );
  7089. // increase counter
  7090. groupCount += 6;
  7091. }
  7092. }
  7093. // add a group to the geometry. this will ensure multi material support
  7094. scope.addGroup( groupStart, groupCount, materialIndex );
  7095. // calculate new start value for groups
  7096. groupStart += groupCount;
  7097. // update total number of vertices
  7098. numberOfVertices += vertexCounter;
  7099. }
  7100. }
  7101. copy( source ) {
  7102. super.copy( source );
  7103. this.parameters = Object.assign( {}, source.parameters );
  7104. return this;
  7105. }
  7106. static fromJSON( data ) {
  7107. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  7108. }
  7109. }
  7110. /**
  7111. * Uniform Utilities
  7112. */
  7113. function cloneUniforms( src ) {
  7114. const dst = {};
  7115. for ( const u in src ) {
  7116. dst[ u ] = {};
  7117. for ( const p in src[ u ] ) {
  7118. const property = src[ u ][ p ];
  7119. if ( property && ( property.isColor ||
  7120. property.isMatrix3 || property.isMatrix4 ||
  7121. property.isVector2 || property.isVector3 || property.isVector4 ||
  7122. property.isTexture || property.isQuaternion ) ) {
  7123. if ( property.isRenderTargetTexture ) {
  7124. console.warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  7125. dst[ u ][ p ] = null;
  7126. } else {
  7127. dst[ u ][ p ] = property.clone();
  7128. }
  7129. } else if ( Array.isArray( property ) ) {
  7130. dst[ u ][ p ] = property.slice();
  7131. } else {
  7132. dst[ u ][ p ] = property;
  7133. }
  7134. }
  7135. }
  7136. return dst;
  7137. }
  7138. function mergeUniforms( uniforms ) {
  7139. const merged = {};
  7140. for ( let u = 0; u < uniforms.length; u ++ ) {
  7141. const tmp = cloneUniforms( uniforms[ u ] );
  7142. for ( const p in tmp ) {
  7143. merged[ p ] = tmp[ p ];
  7144. }
  7145. }
  7146. return merged;
  7147. }
  7148. function cloneUniformsGroups( src ) {
  7149. const dst = [];
  7150. for ( let u = 0; u < src.length; u ++ ) {
  7151. dst.push( src[ u ].clone() );
  7152. }
  7153. return dst;
  7154. }
  7155. function getUnlitUniformColorSpace( renderer ) {
  7156. if ( renderer.getRenderTarget() === null ) {
  7157. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  7158. return renderer.outputColorSpace;
  7159. }
  7160. return LinearSRGBColorSpace;
  7161. }
  7162. // Legacy
  7163. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  7164. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7165. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7166. class ShaderMaterial extends Material {
  7167. constructor( parameters ) {
  7168. super();
  7169. this.isShaderMaterial = true;
  7170. this.type = 'ShaderMaterial';
  7171. this.defines = {};
  7172. this.uniforms = {};
  7173. this.uniformsGroups = [];
  7174. this.vertexShader = default_vertex;
  7175. this.fragmentShader = default_fragment;
  7176. this.linewidth = 1;
  7177. this.wireframe = false;
  7178. this.wireframeLinewidth = 1;
  7179. this.fog = false; // set to use scene fog
  7180. this.lights = false; // set to use scene lights
  7181. this.clipping = false; // set to use user-defined clipping planes
  7182. this.forceSinglePass = true;
  7183. this.extensions = {
  7184. derivatives: false, // set to use derivatives
  7185. fragDepth: false, // set to use fragment depth values
  7186. drawBuffers: false, // set to use draw buffers
  7187. shaderTextureLOD: false // set to use shader texture LOD
  7188. };
  7189. // When rendered geometry doesn't include these attributes but the material does,
  7190. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7191. this.defaultAttributeValues = {
  7192. 'color': [ 1, 1, 1 ],
  7193. 'uv': [ 0, 0 ],
  7194. 'uv1': [ 0, 0 ]
  7195. };
  7196. this.index0AttributeName = undefined;
  7197. this.uniformsNeedUpdate = false;
  7198. this.glslVersion = null;
  7199. if ( parameters !== undefined ) {
  7200. this.setValues( parameters );
  7201. }
  7202. }
  7203. copy( source ) {
  7204. super.copy( source );
  7205. this.fragmentShader = source.fragmentShader;
  7206. this.vertexShader = source.vertexShader;
  7207. this.uniforms = cloneUniforms( source.uniforms );
  7208. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7209. this.defines = Object.assign( {}, source.defines );
  7210. this.wireframe = source.wireframe;
  7211. this.wireframeLinewidth = source.wireframeLinewidth;
  7212. this.fog = source.fog;
  7213. this.lights = source.lights;
  7214. this.clipping = source.clipping;
  7215. this.extensions = Object.assign( {}, source.extensions );
  7216. this.glslVersion = source.glslVersion;
  7217. return this;
  7218. }
  7219. toJSON( meta ) {
  7220. const data = super.toJSON( meta );
  7221. data.glslVersion = this.glslVersion;
  7222. data.uniforms = {};
  7223. for ( const name in this.uniforms ) {
  7224. const uniform = this.uniforms[ name ];
  7225. const value = uniform.value;
  7226. if ( value && value.isTexture ) {
  7227. data.uniforms[ name ] = {
  7228. type: 't',
  7229. value: value.toJSON( meta ).uuid
  7230. };
  7231. } else if ( value && value.isColor ) {
  7232. data.uniforms[ name ] = {
  7233. type: 'c',
  7234. value: value.getHex()
  7235. };
  7236. } else if ( value && value.isVector2 ) {
  7237. data.uniforms[ name ] = {
  7238. type: 'v2',
  7239. value: value.toArray()
  7240. };
  7241. } else if ( value && value.isVector3 ) {
  7242. data.uniforms[ name ] = {
  7243. type: 'v3',
  7244. value: value.toArray()
  7245. };
  7246. } else if ( value && value.isVector4 ) {
  7247. data.uniforms[ name ] = {
  7248. type: 'v4',
  7249. value: value.toArray()
  7250. };
  7251. } else if ( value && value.isMatrix3 ) {
  7252. data.uniforms[ name ] = {
  7253. type: 'm3',
  7254. value: value.toArray()
  7255. };
  7256. } else if ( value && value.isMatrix4 ) {
  7257. data.uniforms[ name ] = {
  7258. type: 'm4',
  7259. value: value.toArray()
  7260. };
  7261. } else {
  7262. data.uniforms[ name ] = {
  7263. value: value
  7264. };
  7265. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7266. }
  7267. }
  7268. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7269. data.vertexShader = this.vertexShader;
  7270. data.fragmentShader = this.fragmentShader;
  7271. data.lights = this.lights;
  7272. data.clipping = this.clipping;
  7273. const extensions = {};
  7274. for ( const key in this.extensions ) {
  7275. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7276. }
  7277. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7278. return data;
  7279. }
  7280. }
  7281. class Camera extends Object3D {
  7282. constructor() {
  7283. super();
  7284. this.isCamera = true;
  7285. this.type = 'Camera';
  7286. this.matrixWorldInverse = new Matrix4();
  7287. this.projectionMatrix = new Matrix4();
  7288. this.projectionMatrixInverse = new Matrix4();
  7289. this.coordinateSystem = WebGLCoordinateSystem;
  7290. }
  7291. copy( source, recursive ) {
  7292. super.copy( source, recursive );
  7293. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7294. this.projectionMatrix.copy( source.projectionMatrix );
  7295. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7296. this.coordinateSystem = source.coordinateSystem;
  7297. return this;
  7298. }
  7299. getWorldDirection( target ) {
  7300. this.updateWorldMatrix( true, false );
  7301. const e = this.matrixWorld.elements;
  7302. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  7303. }
  7304. updateMatrixWorld( force ) {
  7305. super.updateMatrixWorld( force );
  7306. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7307. }
  7308. updateWorldMatrix( updateParents, updateChildren ) {
  7309. super.updateWorldMatrix( updateParents, updateChildren );
  7310. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7311. }
  7312. clone() {
  7313. return new this.constructor().copy( this );
  7314. }
  7315. }
  7316. class PerspectiveCamera extends Camera {
  7317. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7318. super();
  7319. this.isPerspectiveCamera = true;
  7320. this.type = 'PerspectiveCamera';
  7321. this.fov = fov;
  7322. this.zoom = 1;
  7323. this.near = near;
  7324. this.far = far;
  7325. this.focus = 10;
  7326. this.aspect = aspect;
  7327. this.view = null;
  7328. this.filmGauge = 35; // width of the film (default in millimeters)
  7329. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7330. this.updateProjectionMatrix();
  7331. }
  7332. copy( source, recursive ) {
  7333. super.copy( source, recursive );
  7334. this.fov = source.fov;
  7335. this.zoom = source.zoom;
  7336. this.near = source.near;
  7337. this.far = source.far;
  7338. this.focus = source.focus;
  7339. this.aspect = source.aspect;
  7340. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7341. this.filmGauge = source.filmGauge;
  7342. this.filmOffset = source.filmOffset;
  7343. return this;
  7344. }
  7345. /**
  7346. * Sets the FOV by focal length in respect to the current .filmGauge.
  7347. *
  7348. * The default film gauge is 35, so that the focal length can be specified for
  7349. * a 35mm (full frame) camera.
  7350. *
  7351. * Values for focal length and film gauge must have the same unit.
  7352. */
  7353. setFocalLength( focalLength ) {
  7354. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7355. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7356. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7357. this.updateProjectionMatrix();
  7358. }
  7359. /**
  7360. * Calculates the focal length from the current .fov and .filmGauge.
  7361. */
  7362. getFocalLength() {
  7363. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7364. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7365. }
  7366. getEffectiveFOV() {
  7367. return RAD2DEG * 2 * Math.atan(
  7368. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7369. }
  7370. getFilmWidth() {
  7371. // film not completely covered in portrait format (aspect < 1)
  7372. return this.filmGauge * Math.min( this.aspect, 1 );
  7373. }
  7374. getFilmHeight() {
  7375. // film not completely covered in landscape format (aspect > 1)
  7376. return this.filmGauge / Math.max( this.aspect, 1 );
  7377. }
  7378. /**
  7379. * Sets an offset in a larger frustum. This is useful for multi-window or
  7380. * multi-monitor/multi-machine setups.
  7381. *
  7382. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7383. * the monitors are in grid like this
  7384. *
  7385. * +---+---+---+
  7386. * | A | B | C |
  7387. * +---+---+---+
  7388. * | D | E | F |
  7389. * +---+---+---+
  7390. *
  7391. * then for each monitor you would call it like this
  7392. *
  7393. * const w = 1920;
  7394. * const h = 1080;
  7395. * const fullWidth = w * 3;
  7396. * const fullHeight = h * 2;
  7397. *
  7398. * --A--
  7399. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7400. * --B--
  7401. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7402. * --C--
  7403. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7404. * --D--
  7405. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7406. * --E--
  7407. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7408. * --F--
  7409. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7410. *
  7411. * Note there is no reason monitors have to be the same size or in a grid.
  7412. */
  7413. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7414. this.aspect = fullWidth / fullHeight;
  7415. if ( this.view === null ) {
  7416. this.view = {
  7417. enabled: true,
  7418. fullWidth: 1,
  7419. fullHeight: 1,
  7420. offsetX: 0,
  7421. offsetY: 0,
  7422. width: 1,
  7423. height: 1
  7424. };
  7425. }
  7426. this.view.enabled = true;
  7427. this.view.fullWidth = fullWidth;
  7428. this.view.fullHeight = fullHeight;
  7429. this.view.offsetX = x;
  7430. this.view.offsetY = y;
  7431. this.view.width = width;
  7432. this.view.height = height;
  7433. this.updateProjectionMatrix();
  7434. }
  7435. clearViewOffset() {
  7436. if ( this.view !== null ) {
  7437. this.view.enabled = false;
  7438. }
  7439. this.updateProjectionMatrix();
  7440. }
  7441. updateProjectionMatrix() {
  7442. const near = this.near;
  7443. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7444. let height = 2 * top;
  7445. let width = this.aspect * height;
  7446. let left = - 0.5 * width;
  7447. const view = this.view;
  7448. if ( this.view !== null && this.view.enabled ) {
  7449. const fullWidth = view.fullWidth,
  7450. fullHeight = view.fullHeight;
  7451. left += view.offsetX * width / fullWidth;
  7452. top -= view.offsetY * height / fullHeight;
  7453. width *= view.width / fullWidth;
  7454. height *= view.height / fullHeight;
  7455. }
  7456. const skew = this.filmOffset;
  7457. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7458. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem );
  7459. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7460. }
  7461. toJSON( meta ) {
  7462. const data = super.toJSON( meta );
  7463. data.object.fov = this.fov;
  7464. data.object.zoom = this.zoom;
  7465. data.object.near = this.near;
  7466. data.object.far = this.far;
  7467. data.object.focus = this.focus;
  7468. data.object.aspect = this.aspect;
  7469. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7470. data.object.filmGauge = this.filmGauge;
  7471. data.object.filmOffset = this.filmOffset;
  7472. return data;
  7473. }
  7474. }
  7475. const fov = - 90; // negative fov is not an error
  7476. const aspect = 1;
  7477. class CubeCamera extends Object3D {
  7478. constructor( near, far, renderTarget ) {
  7479. super();
  7480. this.type = 'CubeCamera';
  7481. this.renderTarget = renderTarget;
  7482. this.coordinateSystem = null;
  7483. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7484. cameraPX.layers = this.layers;
  7485. this.add( cameraPX );
  7486. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7487. cameraNX.layers = this.layers;
  7488. this.add( cameraNX );
  7489. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7490. cameraPY.layers = this.layers;
  7491. this.add( cameraPY );
  7492. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7493. cameraNY.layers = this.layers;
  7494. this.add( cameraNY );
  7495. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7496. cameraPZ.layers = this.layers;
  7497. this.add( cameraPZ );
  7498. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7499. cameraNZ.layers = this.layers;
  7500. this.add( cameraNZ );
  7501. }
  7502. updateCoordinateSystem() {
  7503. const coordinateSystem = this.coordinateSystem;
  7504. const cameras = this.children.concat();
  7505. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  7506. for ( const camera of cameras ) this.remove( camera );
  7507. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7508. cameraPX.up.set( 0, 1, 0 );
  7509. cameraPX.lookAt( 1, 0, 0 );
  7510. cameraNX.up.set( 0, 1, 0 );
  7511. cameraNX.lookAt( - 1, 0, 0 );
  7512. cameraPY.up.set( 0, 0, - 1 );
  7513. cameraPY.lookAt( 0, 1, 0 );
  7514. cameraNY.up.set( 0, 0, 1 );
  7515. cameraNY.lookAt( 0, - 1, 0 );
  7516. cameraPZ.up.set( 0, 1, 0 );
  7517. cameraPZ.lookAt( 0, 0, 1 );
  7518. cameraNZ.up.set( 0, 1, 0 );
  7519. cameraNZ.lookAt( 0, 0, - 1 );
  7520. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7521. cameraPX.up.set( 0, - 1, 0 );
  7522. cameraPX.lookAt( - 1, 0, 0 );
  7523. cameraNX.up.set( 0, - 1, 0 );
  7524. cameraNX.lookAt( 1, 0, 0 );
  7525. cameraPY.up.set( 0, 0, 1 );
  7526. cameraPY.lookAt( 0, 1, 0 );
  7527. cameraNY.up.set( 0, 0, - 1 );
  7528. cameraNY.lookAt( 0, - 1, 0 );
  7529. cameraPZ.up.set( 0, - 1, 0 );
  7530. cameraPZ.lookAt( 0, 0, 1 );
  7531. cameraNZ.up.set( 0, - 1, 0 );
  7532. cameraNZ.lookAt( 0, 0, - 1 );
  7533. } else {
  7534. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  7535. }
  7536. for ( const camera of cameras ) {
  7537. this.add( camera );
  7538. camera.updateMatrixWorld();
  7539. }
  7540. }
  7541. update( renderer, scene ) {
  7542. if ( this.parent === null ) this.updateMatrixWorld();
  7543. const renderTarget = this.renderTarget;
  7544. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  7545. this.coordinateSystem = renderer.coordinateSystem;
  7546. this.updateCoordinateSystem();
  7547. }
  7548. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7549. const currentRenderTarget = renderer.getRenderTarget();
  7550. const currentToneMapping = renderer.toneMapping;
  7551. const currentXrEnabled = renderer.xr.enabled;
  7552. renderer.toneMapping = NoToneMapping;
  7553. renderer.xr.enabled = false;
  7554. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7555. renderTarget.texture.generateMipmaps = false;
  7556. renderer.setRenderTarget( renderTarget, 0 );
  7557. renderer.render( scene, cameraPX );
  7558. renderer.setRenderTarget( renderTarget, 1 );
  7559. renderer.render( scene, cameraNX );
  7560. renderer.setRenderTarget( renderTarget, 2 );
  7561. renderer.render( scene, cameraPY );
  7562. renderer.setRenderTarget( renderTarget, 3 );
  7563. renderer.render( scene, cameraNY );
  7564. renderer.setRenderTarget( renderTarget, 4 );
  7565. renderer.render( scene, cameraPZ );
  7566. renderTarget.texture.generateMipmaps = generateMipmaps;
  7567. renderer.setRenderTarget( renderTarget, 5 );
  7568. renderer.render( scene, cameraNZ );
  7569. renderer.setRenderTarget( currentRenderTarget );
  7570. renderer.toneMapping = currentToneMapping;
  7571. renderer.xr.enabled = currentXrEnabled;
  7572. renderTarget.texture.needsPMREMUpdate = true;
  7573. }
  7574. }
  7575. class CubeTexture extends Texture {
  7576. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  7577. images = images !== undefined ? images : [];
  7578. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7579. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  7580. this.isCubeTexture = true;
  7581. this.flipY = false;
  7582. }
  7583. get images() {
  7584. return this.image;
  7585. }
  7586. set images( value ) {
  7587. this.image = value;
  7588. }
  7589. }
  7590. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7591. constructor( size = 1, options = {} ) {
  7592. super( size, size, options );
  7593. this.isWebGLCubeRenderTarget = true;
  7594. const image = { width: size, height: size, depth: 1 };
  7595. const images = [ image, image, image, image, image, image ];
  7596. if ( options.encoding !== undefined ) {
  7597. // @deprecated, r152
  7598. warnOnce( 'THREE.WebGLCubeRenderTarget: option.encoding has been replaced by option.colorSpace.' );
  7599. options.colorSpace = options.encoding === sRGBEncoding ? SRGBColorSpace : NoColorSpace;
  7600. }
  7601. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.colorSpace );
  7602. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7603. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7604. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7605. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7606. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7607. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7608. this.texture.isRenderTargetTexture = true;
  7609. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7610. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7611. }
  7612. fromEquirectangularTexture( renderer, texture ) {
  7613. this.texture.type = texture.type;
  7614. this.texture.colorSpace = texture.colorSpace;
  7615. this.texture.generateMipmaps = texture.generateMipmaps;
  7616. this.texture.minFilter = texture.minFilter;
  7617. this.texture.magFilter = texture.magFilter;
  7618. const shader = {
  7619. uniforms: {
  7620. tEquirect: { value: null },
  7621. },
  7622. vertexShader: /* glsl */`
  7623. varying vec3 vWorldDirection;
  7624. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7625. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7626. }
  7627. void main() {
  7628. vWorldDirection = transformDirection( position, modelMatrix );
  7629. #include <begin_vertex>
  7630. #include <project_vertex>
  7631. }
  7632. `,
  7633. fragmentShader: /* glsl */`
  7634. uniform sampler2D tEquirect;
  7635. varying vec3 vWorldDirection;
  7636. #include <common>
  7637. void main() {
  7638. vec3 direction = normalize( vWorldDirection );
  7639. vec2 sampleUV = equirectUv( direction );
  7640. gl_FragColor = texture2D( tEquirect, sampleUV );
  7641. }
  7642. `
  7643. };
  7644. const geometry = new BoxGeometry( 5, 5, 5 );
  7645. const material = new ShaderMaterial( {
  7646. name: 'CubemapFromEquirect',
  7647. uniforms: cloneUniforms( shader.uniforms ),
  7648. vertexShader: shader.vertexShader,
  7649. fragmentShader: shader.fragmentShader,
  7650. side: BackSide,
  7651. blending: NoBlending
  7652. } );
  7653. material.uniforms.tEquirect.value = texture;
  7654. const mesh = new Mesh( geometry, material );
  7655. const currentMinFilter = texture.minFilter;
  7656. // Avoid blurred poles
  7657. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7658. const camera = new CubeCamera( 1, 10, this );
  7659. camera.update( renderer, mesh );
  7660. texture.minFilter = currentMinFilter;
  7661. mesh.geometry.dispose();
  7662. mesh.material.dispose();
  7663. return this;
  7664. }
  7665. clear( renderer, color, depth, stencil ) {
  7666. const currentRenderTarget = renderer.getRenderTarget();
  7667. for ( let i = 0; i < 6; i ++ ) {
  7668. renderer.setRenderTarget( this, i );
  7669. renderer.clear( color, depth, stencil );
  7670. }
  7671. renderer.setRenderTarget( currentRenderTarget );
  7672. }
  7673. }
  7674. const _vector1 = /*@__PURE__*/ new Vector3();
  7675. const _vector2 = /*@__PURE__*/ new Vector3();
  7676. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  7677. class Plane {
  7678. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  7679. this.isPlane = true;
  7680. // normal is assumed to be normalized
  7681. this.normal = normal;
  7682. this.constant = constant;
  7683. }
  7684. set( normal, constant ) {
  7685. this.normal.copy( normal );
  7686. this.constant = constant;
  7687. return this;
  7688. }
  7689. setComponents( x, y, z, w ) {
  7690. this.normal.set( x, y, z );
  7691. this.constant = w;
  7692. return this;
  7693. }
  7694. setFromNormalAndCoplanarPoint( normal, point ) {
  7695. this.normal.copy( normal );
  7696. this.constant = - point.dot( this.normal );
  7697. return this;
  7698. }
  7699. setFromCoplanarPoints( a, b, c ) {
  7700. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  7701. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7702. this.setFromNormalAndCoplanarPoint( normal, a );
  7703. return this;
  7704. }
  7705. copy( plane ) {
  7706. this.normal.copy( plane.normal );
  7707. this.constant = plane.constant;
  7708. return this;
  7709. }
  7710. normalize() {
  7711. // Note: will lead to a divide by zero if the plane is invalid.
  7712. const inverseNormalLength = 1.0 / this.normal.length();
  7713. this.normal.multiplyScalar( inverseNormalLength );
  7714. this.constant *= inverseNormalLength;
  7715. return this;
  7716. }
  7717. negate() {
  7718. this.constant *= - 1;
  7719. this.normal.negate();
  7720. return this;
  7721. }
  7722. distanceToPoint( point ) {
  7723. return this.normal.dot( point ) + this.constant;
  7724. }
  7725. distanceToSphere( sphere ) {
  7726. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7727. }
  7728. projectPoint( point, target ) {
  7729. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  7730. }
  7731. intersectLine( line, target ) {
  7732. const direction = line.delta( _vector1 );
  7733. const denominator = this.normal.dot( direction );
  7734. if ( denominator === 0 ) {
  7735. // line is coplanar, return origin
  7736. if ( this.distanceToPoint( line.start ) === 0 ) {
  7737. return target.copy( line.start );
  7738. }
  7739. // Unsure if this is the correct method to handle this case.
  7740. return null;
  7741. }
  7742. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7743. if ( t < 0 || t > 1 ) {
  7744. return null;
  7745. }
  7746. return target.copy( line.start ).addScaledVector( direction, t );
  7747. }
  7748. intersectsLine( line ) {
  7749. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7750. const startSign = this.distanceToPoint( line.start );
  7751. const endSign = this.distanceToPoint( line.end );
  7752. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7753. }
  7754. intersectsBox( box ) {
  7755. return box.intersectsPlane( this );
  7756. }
  7757. intersectsSphere( sphere ) {
  7758. return sphere.intersectsPlane( this );
  7759. }
  7760. coplanarPoint( target ) {
  7761. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7762. }
  7763. applyMatrix4( matrix, optionalNormalMatrix ) {
  7764. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  7765. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  7766. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7767. this.constant = - referencePoint.dot( normal );
  7768. return this;
  7769. }
  7770. translate( offset ) {
  7771. this.constant -= offset.dot( this.normal );
  7772. return this;
  7773. }
  7774. equals( plane ) {
  7775. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7776. }
  7777. clone() {
  7778. return new this.constructor().copy( this );
  7779. }
  7780. }
  7781. const _sphere$4 = /*@__PURE__*/ new Sphere();
  7782. const _vector$6 = /*@__PURE__*/ new Vector3();
  7783. class Frustum {
  7784. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7785. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7786. }
  7787. set( p0, p1, p2, p3, p4, p5 ) {
  7788. const planes = this.planes;
  7789. planes[ 0 ].copy( p0 );
  7790. planes[ 1 ].copy( p1 );
  7791. planes[ 2 ].copy( p2 );
  7792. planes[ 3 ].copy( p3 );
  7793. planes[ 4 ].copy( p4 );
  7794. planes[ 5 ].copy( p5 );
  7795. return this;
  7796. }
  7797. copy( frustum ) {
  7798. const planes = this.planes;
  7799. for ( let i = 0; i < 6; i ++ ) {
  7800. planes[ i ].copy( frustum.planes[ i ] );
  7801. }
  7802. return this;
  7803. }
  7804. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem ) {
  7805. const planes = this.planes;
  7806. const me = m.elements;
  7807. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7808. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7809. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7810. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7811. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7812. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7813. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7814. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7815. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7816. if ( coordinateSystem === WebGLCoordinateSystem ) {
  7817. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7818. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  7819. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize();
  7820. } else {
  7821. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  7822. }
  7823. return this;
  7824. }
  7825. intersectsObject( object ) {
  7826. if ( object.boundingSphere !== undefined ) {
  7827. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  7828. _sphere$4.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  7829. } else {
  7830. const geometry = object.geometry;
  7831. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7832. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7833. }
  7834. return this.intersectsSphere( _sphere$4 );
  7835. }
  7836. intersectsSprite( sprite ) {
  7837. _sphere$4.center.set( 0, 0, 0 );
  7838. _sphere$4.radius = 0.7071067811865476;
  7839. _sphere$4.applyMatrix4( sprite.matrixWorld );
  7840. return this.intersectsSphere( _sphere$4 );
  7841. }
  7842. intersectsSphere( sphere ) {
  7843. const planes = this.planes;
  7844. const center = sphere.center;
  7845. const negRadius = - sphere.radius;
  7846. for ( let i = 0; i < 6; i ++ ) {
  7847. const distance = planes[ i ].distanceToPoint( center );
  7848. if ( distance < negRadius ) {
  7849. return false;
  7850. }
  7851. }
  7852. return true;
  7853. }
  7854. intersectsBox( box ) {
  7855. const planes = this.planes;
  7856. for ( let i = 0; i < 6; i ++ ) {
  7857. const plane = planes[ i ];
  7858. // corner at max distance
  7859. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7860. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7861. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7862. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  7863. return false;
  7864. }
  7865. }
  7866. return true;
  7867. }
  7868. containsPoint( point ) {
  7869. const planes = this.planes;
  7870. for ( let i = 0; i < 6; i ++ ) {
  7871. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7872. return false;
  7873. }
  7874. }
  7875. return true;
  7876. }
  7877. clone() {
  7878. return new this.constructor().copy( this );
  7879. }
  7880. }
  7881. function WebGLAnimation() {
  7882. let context = null;
  7883. let isAnimating = false;
  7884. let animationLoop = null;
  7885. let requestId = null;
  7886. function onAnimationFrame( time, frame ) {
  7887. animationLoop( time, frame );
  7888. requestId = context.requestAnimationFrame( onAnimationFrame );
  7889. }
  7890. return {
  7891. start: function () {
  7892. if ( isAnimating === true ) return;
  7893. if ( animationLoop === null ) return;
  7894. requestId = context.requestAnimationFrame( onAnimationFrame );
  7895. isAnimating = true;
  7896. },
  7897. stop: function () {
  7898. context.cancelAnimationFrame( requestId );
  7899. isAnimating = false;
  7900. },
  7901. setAnimationLoop: function ( callback ) {
  7902. animationLoop = callback;
  7903. },
  7904. setContext: function ( value ) {
  7905. context = value;
  7906. }
  7907. };
  7908. }
  7909. function WebGLAttributes( gl, capabilities ) {
  7910. const isWebGL2 = capabilities.isWebGL2;
  7911. const buffers = new WeakMap();
  7912. function createBuffer( attribute, bufferType ) {
  7913. const array = attribute.array;
  7914. const usage = attribute.usage;
  7915. const buffer = gl.createBuffer();
  7916. gl.bindBuffer( bufferType, buffer );
  7917. gl.bufferData( bufferType, array, usage );
  7918. attribute.onUploadCallback();
  7919. let type;
  7920. if ( array instanceof Float32Array ) {
  7921. type = gl.FLOAT;
  7922. } else if ( array instanceof Uint16Array ) {
  7923. if ( attribute.isFloat16BufferAttribute ) {
  7924. if ( isWebGL2 ) {
  7925. type = gl.HALF_FLOAT;
  7926. } else {
  7927. throw new Error( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  7928. }
  7929. } else {
  7930. type = gl.UNSIGNED_SHORT;
  7931. }
  7932. } else if ( array instanceof Int16Array ) {
  7933. type = gl.SHORT;
  7934. } else if ( array instanceof Uint32Array ) {
  7935. type = gl.UNSIGNED_INT;
  7936. } else if ( array instanceof Int32Array ) {
  7937. type = gl.INT;
  7938. } else if ( array instanceof Int8Array ) {
  7939. type = gl.BYTE;
  7940. } else if ( array instanceof Uint8Array ) {
  7941. type = gl.UNSIGNED_BYTE;
  7942. } else if ( array instanceof Uint8ClampedArray ) {
  7943. type = gl.UNSIGNED_BYTE;
  7944. } else {
  7945. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  7946. }
  7947. return {
  7948. buffer: buffer,
  7949. type: type,
  7950. bytesPerElement: array.BYTES_PER_ELEMENT,
  7951. version: attribute.version
  7952. };
  7953. }
  7954. function updateBuffer( buffer, attribute, bufferType ) {
  7955. const array = attribute.array;
  7956. const updateRange = attribute.updateRange;
  7957. gl.bindBuffer( bufferType, buffer );
  7958. if ( updateRange.count === - 1 ) {
  7959. // Not using update ranges
  7960. gl.bufferSubData( bufferType, 0, array );
  7961. } else {
  7962. if ( isWebGL2 ) {
  7963. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7964. array, updateRange.offset, updateRange.count );
  7965. } else {
  7966. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7967. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  7968. }
  7969. updateRange.count = - 1; // reset range
  7970. }
  7971. attribute.onUploadCallback();
  7972. }
  7973. //
  7974. function get( attribute ) {
  7975. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7976. return buffers.get( attribute );
  7977. }
  7978. function remove( attribute ) {
  7979. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7980. const data = buffers.get( attribute );
  7981. if ( data ) {
  7982. gl.deleteBuffer( data.buffer );
  7983. buffers.delete( attribute );
  7984. }
  7985. }
  7986. function update( attribute, bufferType ) {
  7987. if ( attribute.isGLBufferAttribute ) {
  7988. const cached = buffers.get( attribute );
  7989. if ( ! cached || cached.version < attribute.version ) {
  7990. buffers.set( attribute, {
  7991. buffer: attribute.buffer,
  7992. type: attribute.type,
  7993. bytesPerElement: attribute.elementSize,
  7994. version: attribute.version
  7995. } );
  7996. }
  7997. return;
  7998. }
  7999. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  8000. const data = buffers.get( attribute );
  8001. if ( data === undefined ) {
  8002. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  8003. } else if ( data.version < attribute.version ) {
  8004. updateBuffer( data.buffer, attribute, bufferType );
  8005. data.version = attribute.version;
  8006. }
  8007. }
  8008. return {
  8009. get: get,
  8010. remove: remove,
  8011. update: update
  8012. };
  8013. }
  8014. class PlaneGeometry extends BufferGeometry {
  8015. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  8016. super();
  8017. this.type = 'PlaneGeometry';
  8018. this.parameters = {
  8019. width: width,
  8020. height: height,
  8021. widthSegments: widthSegments,
  8022. heightSegments: heightSegments
  8023. };
  8024. const width_half = width / 2;
  8025. const height_half = height / 2;
  8026. const gridX = Math.floor( widthSegments );
  8027. const gridY = Math.floor( heightSegments );
  8028. const gridX1 = gridX + 1;
  8029. const gridY1 = gridY + 1;
  8030. const segment_width = width / gridX;
  8031. const segment_height = height / gridY;
  8032. //
  8033. const indices = [];
  8034. const vertices = [];
  8035. const normals = [];
  8036. const uvs = [];
  8037. for ( let iy = 0; iy < gridY1; iy ++ ) {
  8038. const y = iy * segment_height - height_half;
  8039. for ( let ix = 0; ix < gridX1; ix ++ ) {
  8040. const x = ix * segment_width - width_half;
  8041. vertices.push( x, - y, 0 );
  8042. normals.push( 0, 0, 1 );
  8043. uvs.push( ix / gridX );
  8044. uvs.push( 1 - ( iy / gridY ) );
  8045. }
  8046. }
  8047. for ( let iy = 0; iy < gridY; iy ++ ) {
  8048. for ( let ix = 0; ix < gridX; ix ++ ) {
  8049. const a = ix + gridX1 * iy;
  8050. const b = ix + gridX1 * ( iy + 1 );
  8051. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  8052. const d = ( ix + 1 ) + gridX1 * iy;
  8053. indices.push( a, b, d );
  8054. indices.push( b, c, d );
  8055. }
  8056. }
  8057. this.setIndex( indices );
  8058. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  8059. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  8060. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  8061. }
  8062. copy( source ) {
  8063. super.copy( source );
  8064. this.parameters = Object.assign( {}, source.parameters );
  8065. return this;
  8066. }
  8067. static fromJSON( data ) {
  8068. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  8069. }
  8070. }
  8071. var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif";
  8072. var alphahash_pars_fragment = "#ifdef USE_ALPHAHASH\n\tconst float ALPHA_HASH_SCALE = 0.05;\n\tfloat hash2D( vec2 value ) {\n\t\treturn fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );\n\t}\n\tfloat hash3D( vec3 value ) {\n\t\treturn hash2D( vec2( hash2D( value.xy ), value.z ) );\n\t}\n\tfloat getAlphaHashThreshold( vec3 position ) {\n\t\tfloat maxDeriv = max(\n\t\t\tlength( dFdx( position.xyz ) ),\n\t\t\tlength( dFdy( position.xyz ) )\n\t\t);\n\t\tfloat pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );\n\t\tvec2 pixScales = vec2(\n\t\t\texp2( floor( log2( pixScale ) ) ),\n\t\t\texp2( ceil( log2( pixScale ) ) )\n\t\t);\n\t\tvec2 alpha = vec2(\n\t\t\thash3D( floor( pixScales.x * position.xyz ) ),\n\t\t\thash3D( floor( pixScales.y * position.xyz ) )\n\t\t);\n\t\tfloat lerpFactor = fract( log2( pixScale ) );\n\t\tfloat x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;\n\t\tfloat a = min( lerpFactor, 1.0 - lerpFactor );\n\t\tvec3 cases = vec3(\n\t\t\tx * x / ( 2.0 * a * ( 1.0 - a ) ),\n\t\t\t( x - 0.5 * a ) / ( 1.0 - a ),\n\t\t\t1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )\n\t\t);\n\t\tfloat threshold = ( x < ( 1.0 - a ) )\n\t\t\t? ( ( x < a ) ? cases.x : cases.y )\n\t\t\t: cases.z;\n\t\treturn clamp( threshold , 1.0e-6, 1.0 );\n\t}\n#endif";
  8073. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  8074. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8075. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  8076. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  8077. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif";
  8078. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  8079. var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif";
  8080. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  8081. var bsdfs = "float G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n} // validated";
  8082. 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";
  8083. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vBumpMapUv );\n\t\tvec2 dSTdy = dFdy( vBumpMapUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = dFdx( surf_pos.xyz );\n\t\tvec3 vSigmaY = dFdy( surf_pos.xyz );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif";
  8084. 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";
  8085. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  8086. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  8087. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  8088. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  8089. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  8090. 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";
  8091. 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";
  8092. 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};\n#ifdef USE_ALPHAHASH\n\tvarying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat luminance( const in vec3 rgb ) {\n\tconst vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );\n\treturn dot( weights, rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated";
  8093. 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";
  8094. 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";
  8095. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  8096. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  8097. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  8098. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  8099. var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  8100. var colorspace_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}";
  8101. 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";
  8102. 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";
  8103. 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";
  8104. 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";
  8105. 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";
  8106. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  8107. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  8108. 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";
  8109. 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";
  8110. 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}";
  8111. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  8112. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  8113. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  8114. 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";
  8115. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( LEGACY_LIGHTS )\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#else\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif";
  8116. var envmap_physical_pars_fragment = "#ifdef USE_ENVMAP\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n#endif";
  8117. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  8118. 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";
  8119. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  8120. 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";
  8121. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef USE_SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULAR_COLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n\t\t#endif\n\t\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tanisotropyV /= material.anisotropy;\n\tmaterial.anisotropy = saturate( material.anisotropy );\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x - tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x + tbn[ 0 ] * anisotropyV.y;\n#endif";
  8122. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat anisotropy;\n\t\tfloat alphaT;\n\t\tvec3 anisotropyT;\n\t\tvec3 anisotropyB;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n\tfloat V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n\t\tfloat gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n\t\tfloat gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n\t\tfloat v = 0.5 / ( gv + gl );\n\t\treturn saturate(v);\n\t}\n\tfloat D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n\t\tfloat a2 = alphaT * alphaB;\n\t\thighp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n\t\thighp float v2 = dot( v, v );\n\t\tfloat w2 = a2 / v2;\n\t\treturn RECIPROCAL_PI * a2 * pow2 ( w2 );\n\t}\n#endif\n#ifdef USE_CLEARCOAT\n\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n\t\tvec3 f0 = material.clearcoatF0;\n\t\tfloat f90 = material.clearcoatF90;\n\t\tfloat roughness = material.clearcoatRoughness;\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 f0 = material.specularColor;\n\tfloat f90 = material.specularF90;\n\tfloat roughness = material.roughness;\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t#ifdef USE_IRIDESCENCE\n\t\tF = mix( F, material.iridescenceFresnel, material.iridescence );\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat dotTL = dot( material.anisotropyT, lightDir );\n\t\tfloat dotTV = dot( material.anisotropyT, viewDir );\n\t\tfloat dotTH = dot( material.anisotropyT, halfDir );\n\t\tfloat dotBL = dot( material.anisotropyB, lightDir );\n\t\tfloat dotBV = dot( material.anisotropyB, viewDir );\n\t\tfloat dotBH = dot( material.anisotropyB, halfDir );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n\t#else\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t#endif\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  8123. 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";
  8124. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\t#ifdef USE_ANISOTROPY\n\t\tradiance += getIBLAnisotropyRadiance( geometry.viewDir, geometry.normal, material.roughness, material.anisotropyB, material.anisotropy );\n\t#else\n\t\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
  8125. 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";
  8126. 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";
  8127. 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";
  8128. 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";
  8129. 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";
  8130. var map_fragment = "#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, vMapUv );\n#endif";
  8131. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  8132. var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t#if defined( USE_POINTS_UV )\n\t\tvec2 uv = vUv;\n\t#else\n\t\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
  8133. var map_particle_pars_fragment = "#if defined( USE_POINTS_UV )\n\tvarying vec2 vUv;\n#else\n\t#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t\tuniform mat3 uvTransform;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  8134. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  8135. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  8136. 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";
  8137. 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";
  8138. 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";
  8139. 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";
  8140. var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal *= faceDirection;\n\t#endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn = getTangentFrame( - vViewPosition, normal,\n\t\t#if defined( USE_NORMALMAP )\n\t\t\tvNormalMapUv\n\t\t#elif defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tvClearcoatNormalMapUv\n\t\t#else\n\t\t\tvUv\n\t\t#endif\n\t\t);\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn[0] *= faceDirection;\n\t\ttbn[1] *= faceDirection;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn2[0] *= faceDirection;\n\t\ttbn2[1] *= faceDirection;\n\t#endif\n#endif\nvec3 geometryNormal = normal;";
  8141. var normal_fragment_maps = "#ifdef USE_NORMALMAP_OBJECTSPACE\n\tnormal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n\tvec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\tnormal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif";
  8142. 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";
  8143. 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";
  8144. 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";
  8145. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n\tmat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( uv.st );\n\t\tvec2 st1 = dFdy( uv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n\t\treturn mat3( T * scale, B * scale, N );\n\t}\n#endif";
  8146. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  8147. var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\tclearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif";
  8148. var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif";
  8149. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  8150. var opaque_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  8151. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec2 packDepthToRG( in highp float v ) {\n\treturn packDepthToRGBA( v ).yx;\n}\nfloat unpackRGToDepth( const in highp vec2 v ) {\n\treturn unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn depth * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * depth - far );\n}";
  8152. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  8153. 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;";
  8154. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  8155. 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";
  8156. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  8157. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  8158. var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tvec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {\n\t\treturn unpackRGBATo2Half( texture2D( shadow, uv ) );\n\t}\n\tfloat VSMShadow (sampler2D shadow, vec2 uv, float compare ){\n\t\tfloat occlusion = 1.0;\n\t\tvec2 distribution = texture2DDistribution( shadow, uv );\n\t\tfloat hard_shadow = step( compare , distribution.x );\n\t\tif (hard_shadow != 1.0 ) {\n\t\t\tfloat distance = compare - distribution.x ;\n\t\t\tfloat variance = max( 0.00000, distribution.y * distribution.y );\n\t\t\tfloat softness_probability = variance / (variance + distance * distance );\t\t\tsoftness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );\t\t\tocclusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );\n\t\t}\n\t\treturn occlusion;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tfloat shadow = 1.0;\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\tfloat dx2 = dx0 / 2.0;\n\t\t\tfloat dy2 = dy0 / 2.0;\n\t\t\tfloat dx3 = dx1 / 2.0;\n\t\t\tfloat dy3 = dy1 / 2.0;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 17.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx = texelSize.x;\n\t\t\tfloat dy = texelSize.y;\n\t\t\tvec2 uv = shadowCoord.xy;\n\t\t\tvec2 f = fract( uv * shadowMapSize + 0.5 );\n\t\t\tuv -= f * texelSize;\n\t\t\tshadow = (\n\t\t\t\ttexture2DCompare( shadowMap, uv, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),\n\t\t\t\t\t f.x ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t f.y ) +\n\t\t\t\tmix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),\n\t\t\t\t\t\t f.x ),\n\t\t\t\t\t f.y )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\t\tshadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#else\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn shadow;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );\t\tdp += shadowBias;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif";
  8159. var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";
  8160. 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";
  8161. 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}";
  8162. 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";
  8163. 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";
  8164. 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";
  8165. 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";
  8166. var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
  8167. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  8168. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  8169. var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
  8170. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmitted = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif";
  8171. var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n\t}\n\tvec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn vec3( 1.0 );\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 attenuatedColor = transmittance * transmittedLight.rgb;\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\tfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n\t}\n#endif";
  8172. var uv_pars_fragment = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif";
  8173. var uv_pars_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tuniform mat3 mapTransform;\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform mat3 alphaMapTransform;\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tuniform mat3 lightMapTransform;\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tuniform mat3 aoMapTransform;\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tuniform mat3 bumpMapTransform;\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tuniform mat3 normalMapTransform;\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tuniform mat3 displacementMapTransform;\n\tvarying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tuniform mat3 emissiveMapTransform;\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tuniform mat3 metalnessMapTransform;\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tuniform mat3 roughnessMapTransform;\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tuniform mat3 anisotropyMapTransform;\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tuniform mat3 clearcoatMapTransform;\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform mat3 clearcoatNormalMapTransform;\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform mat3 clearcoatRoughnessMapTransform;\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tuniform mat3 sheenColorMapTransform;\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tuniform mat3 sheenRoughnessMapTransform;\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tuniform mat3 iridescenceMapTransform;\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform mat3 iridescenceThicknessMapTransform;\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tuniform mat3 specularMapTransform;\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tuniform mat3 specularColorMapTransform;\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tuniform mat3 specularIntensityMapTransform;\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif";
  8174. var uv_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n\tvMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n\tvAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n\tvLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n\tvAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n\tvBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n\tvNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tvDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n\tvMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n\tvSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tvTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n\tvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif";
  8175. 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";
  8176. 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}";
  8177. const fragment$h = "uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}";
  8178. 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}";
  8179. const fragment$g = "#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}";
  8180. 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}";
  8181. const fragment$f = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}";
  8182. 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}";
  8183. const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
  8184. 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}";
  8185. const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  8186. 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}";
  8187. const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}";
  8188. const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  8189. const fragment$b = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8190. const vertex$a = "#include <common>\n#include <uv_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  8191. const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8192. const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8193. const fragment$9 = "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_lambert_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_lambert_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8194. 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}";
  8195. const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8196. const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  8197. const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}";
  8198. const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8199. const fragment$6 = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8200. const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}";
  8201. const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef USE_SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULAR_COLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\tuniform vec2 anisotropyVector;\n\t#ifdef USE_ANISOTROPYMAP\n\t\tuniform sampler2D anisotropyMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <iridescence_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <iridescence_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( 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 <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8202. const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8203. const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8204. const vertex$3 = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n#ifdef USE_POINTS_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\nvoid main() {\n\t#ifdef USE_POINTS_UV\n\t\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\t#endif\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";
  8205. const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8206. const vertex$2 = "#include <common>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8207. const fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <logdepthbuf_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n}";
  8208. 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}";
  8209. const fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n}";
  8210. const ShaderChunk = {
  8211. alphahash_fragment: alphahash_fragment,
  8212. alphahash_pars_fragment: alphahash_pars_fragment,
  8213. alphamap_fragment: alphamap_fragment,
  8214. alphamap_pars_fragment: alphamap_pars_fragment,
  8215. alphatest_fragment: alphatest_fragment,
  8216. alphatest_pars_fragment: alphatest_pars_fragment,
  8217. aomap_fragment: aomap_fragment,
  8218. aomap_pars_fragment: aomap_pars_fragment,
  8219. begin_vertex: begin_vertex,
  8220. beginnormal_vertex: beginnormal_vertex,
  8221. bsdfs: bsdfs,
  8222. iridescence_fragment: iridescence_fragment,
  8223. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8224. clipping_planes_fragment: clipping_planes_fragment,
  8225. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8226. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8227. clipping_planes_vertex: clipping_planes_vertex,
  8228. color_fragment: color_fragment,
  8229. color_pars_fragment: color_pars_fragment,
  8230. color_pars_vertex: color_pars_vertex,
  8231. color_vertex: color_vertex,
  8232. common: common,
  8233. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8234. defaultnormal_vertex: defaultnormal_vertex,
  8235. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8236. displacementmap_vertex: displacementmap_vertex,
  8237. emissivemap_fragment: emissivemap_fragment,
  8238. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8239. colorspace_fragment: colorspace_fragment,
  8240. colorspace_pars_fragment: colorspace_pars_fragment,
  8241. envmap_fragment: envmap_fragment,
  8242. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8243. envmap_pars_fragment: envmap_pars_fragment,
  8244. envmap_pars_vertex: envmap_pars_vertex,
  8245. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8246. envmap_vertex: envmap_vertex,
  8247. fog_vertex: fog_vertex,
  8248. fog_pars_vertex: fog_pars_vertex,
  8249. fog_fragment: fog_fragment,
  8250. fog_pars_fragment: fog_pars_fragment,
  8251. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8252. lightmap_fragment: lightmap_fragment,
  8253. lightmap_pars_fragment: lightmap_pars_fragment,
  8254. lights_lambert_fragment: lights_lambert_fragment,
  8255. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  8256. lights_pars_begin: lights_pars_begin,
  8257. lights_toon_fragment: lights_toon_fragment,
  8258. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8259. lights_phong_fragment: lights_phong_fragment,
  8260. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8261. lights_physical_fragment: lights_physical_fragment,
  8262. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8263. lights_fragment_begin: lights_fragment_begin,
  8264. lights_fragment_maps: lights_fragment_maps,
  8265. lights_fragment_end: lights_fragment_end,
  8266. logdepthbuf_fragment: logdepthbuf_fragment,
  8267. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8268. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8269. logdepthbuf_vertex: logdepthbuf_vertex,
  8270. map_fragment: map_fragment,
  8271. map_pars_fragment: map_pars_fragment,
  8272. map_particle_fragment: map_particle_fragment,
  8273. map_particle_pars_fragment: map_particle_pars_fragment,
  8274. metalnessmap_fragment: metalnessmap_fragment,
  8275. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8276. morphcolor_vertex: morphcolor_vertex,
  8277. morphnormal_vertex: morphnormal_vertex,
  8278. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8279. morphtarget_vertex: morphtarget_vertex,
  8280. normal_fragment_begin: normal_fragment_begin,
  8281. normal_fragment_maps: normal_fragment_maps,
  8282. normal_pars_fragment: normal_pars_fragment,
  8283. normal_pars_vertex: normal_pars_vertex,
  8284. normal_vertex: normal_vertex,
  8285. normalmap_pars_fragment: normalmap_pars_fragment,
  8286. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8287. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8288. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8289. iridescence_pars_fragment: iridescence_pars_fragment,
  8290. opaque_fragment: opaque_fragment,
  8291. packing: packing,
  8292. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8293. project_vertex: project_vertex,
  8294. dithering_fragment: dithering_fragment,
  8295. dithering_pars_fragment: dithering_pars_fragment,
  8296. roughnessmap_fragment: roughnessmap_fragment,
  8297. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8298. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8299. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8300. shadowmap_vertex: shadowmap_vertex,
  8301. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8302. skinbase_vertex: skinbase_vertex,
  8303. skinning_pars_vertex: skinning_pars_vertex,
  8304. skinning_vertex: skinning_vertex,
  8305. skinnormal_vertex: skinnormal_vertex,
  8306. specularmap_fragment: specularmap_fragment,
  8307. specularmap_pars_fragment: specularmap_pars_fragment,
  8308. tonemapping_fragment: tonemapping_fragment,
  8309. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8310. transmission_fragment: transmission_fragment,
  8311. transmission_pars_fragment: transmission_pars_fragment,
  8312. uv_pars_fragment: uv_pars_fragment,
  8313. uv_pars_vertex: uv_pars_vertex,
  8314. uv_vertex: uv_vertex,
  8315. worldpos_vertex: worldpos_vertex,
  8316. background_vert: vertex$h,
  8317. background_frag: fragment$h,
  8318. backgroundCube_vert: vertex$g,
  8319. backgroundCube_frag: fragment$g,
  8320. cube_vert: vertex$f,
  8321. cube_frag: fragment$f,
  8322. depth_vert: vertex$e,
  8323. depth_frag: fragment$e,
  8324. distanceRGBA_vert: vertex$d,
  8325. distanceRGBA_frag: fragment$d,
  8326. equirect_vert: vertex$c,
  8327. equirect_frag: fragment$c,
  8328. linedashed_vert: vertex$b,
  8329. linedashed_frag: fragment$b,
  8330. meshbasic_vert: vertex$a,
  8331. meshbasic_frag: fragment$a,
  8332. meshlambert_vert: vertex$9,
  8333. meshlambert_frag: fragment$9,
  8334. meshmatcap_vert: vertex$8,
  8335. meshmatcap_frag: fragment$8,
  8336. meshnormal_vert: vertex$7,
  8337. meshnormal_frag: fragment$7,
  8338. meshphong_vert: vertex$6,
  8339. meshphong_frag: fragment$6,
  8340. meshphysical_vert: vertex$5,
  8341. meshphysical_frag: fragment$5,
  8342. meshtoon_vert: vertex$4,
  8343. meshtoon_frag: fragment$4,
  8344. points_vert: vertex$3,
  8345. points_frag: fragment$3,
  8346. shadow_vert: vertex$2,
  8347. shadow_frag: fragment$2,
  8348. sprite_vert: vertex$1,
  8349. sprite_frag: fragment$1
  8350. };
  8351. /**
  8352. * Uniforms library for shared webgl shaders
  8353. */
  8354. const UniformsLib = {
  8355. common: {
  8356. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8357. opacity: { value: 1.0 },
  8358. map: { value: null },
  8359. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8360. alphaMap: { value: null },
  8361. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8362. alphaTest: { value: 0 }
  8363. },
  8364. specularmap: {
  8365. specularMap: { value: null },
  8366. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8367. },
  8368. envmap: {
  8369. envMap: { value: null },
  8370. flipEnvMap: { value: - 1 },
  8371. reflectivity: { value: 1.0 }, // basic, lambert, phong
  8372. ior: { value: 1.5 }, // physical
  8373. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  8374. },
  8375. aomap: {
  8376. aoMap: { value: null },
  8377. aoMapIntensity: { value: 1 },
  8378. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8379. },
  8380. lightmap: {
  8381. lightMap: { value: null },
  8382. lightMapIntensity: { value: 1 },
  8383. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8384. },
  8385. bumpmap: {
  8386. bumpMap: { value: null },
  8387. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8388. bumpScale: { value: 1 }
  8389. },
  8390. normalmap: {
  8391. normalMap: { value: null },
  8392. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8393. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  8394. },
  8395. displacementmap: {
  8396. displacementMap: { value: null },
  8397. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8398. displacementScale: { value: 1 },
  8399. displacementBias: { value: 0 }
  8400. },
  8401. emissivemap: {
  8402. emissiveMap: { value: null },
  8403. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8404. },
  8405. metalnessmap: {
  8406. metalnessMap: { value: null },
  8407. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8408. },
  8409. roughnessmap: {
  8410. roughnessMap: { value: null },
  8411. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  8412. },
  8413. gradientmap: {
  8414. gradientMap: { value: null }
  8415. },
  8416. fog: {
  8417. fogDensity: { value: 0.00025 },
  8418. fogNear: { value: 1 },
  8419. fogFar: { value: 2000 },
  8420. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  8421. },
  8422. lights: {
  8423. ambientLightColor: { value: [] },
  8424. lightProbe: { value: [] },
  8425. directionalLights: { value: [], properties: {
  8426. direction: {},
  8427. color: {}
  8428. } },
  8429. directionalLightShadows: { value: [], properties: {
  8430. shadowBias: {},
  8431. shadowNormalBias: {},
  8432. shadowRadius: {},
  8433. shadowMapSize: {}
  8434. } },
  8435. directionalShadowMap: { value: [] },
  8436. directionalShadowMatrix: { value: [] },
  8437. spotLights: { value: [], properties: {
  8438. color: {},
  8439. position: {},
  8440. direction: {},
  8441. distance: {},
  8442. coneCos: {},
  8443. penumbraCos: {},
  8444. decay: {}
  8445. } },
  8446. spotLightShadows: { value: [], properties: {
  8447. shadowBias: {},
  8448. shadowNormalBias: {},
  8449. shadowRadius: {},
  8450. shadowMapSize: {}
  8451. } },
  8452. spotLightMap: { value: [] },
  8453. spotShadowMap: { value: [] },
  8454. spotLightMatrix: { value: [] },
  8455. pointLights: { value: [], properties: {
  8456. color: {},
  8457. position: {},
  8458. decay: {},
  8459. distance: {}
  8460. } },
  8461. pointLightShadows: { value: [], properties: {
  8462. shadowBias: {},
  8463. shadowNormalBias: {},
  8464. shadowRadius: {},
  8465. shadowMapSize: {},
  8466. shadowCameraNear: {},
  8467. shadowCameraFar: {}
  8468. } },
  8469. pointShadowMap: { value: [] },
  8470. pointShadowMatrix: { value: [] },
  8471. hemisphereLights: { value: [], properties: {
  8472. direction: {},
  8473. skyColor: {},
  8474. groundColor: {}
  8475. } },
  8476. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8477. rectAreaLights: { value: [], properties: {
  8478. color: {},
  8479. position: {},
  8480. width: {},
  8481. height: {}
  8482. } },
  8483. ltc_1: { value: null },
  8484. ltc_2: { value: null }
  8485. },
  8486. points: {
  8487. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8488. opacity: { value: 1.0 },
  8489. size: { value: 1.0 },
  8490. scale: { value: 1.0 },
  8491. map: { value: null },
  8492. alphaMap: { value: null },
  8493. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8494. alphaTest: { value: 0 },
  8495. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8496. },
  8497. sprite: {
  8498. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8499. opacity: { value: 1.0 },
  8500. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  8501. rotation: { value: 0.0 },
  8502. map: { value: null },
  8503. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8504. alphaMap: { value: null },
  8505. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8506. alphaTest: { value: 0 }
  8507. }
  8508. };
  8509. const ShaderLib = {
  8510. basic: {
  8511. uniforms: /*@__PURE__*/ mergeUniforms( [
  8512. UniformsLib.common,
  8513. UniformsLib.specularmap,
  8514. UniformsLib.envmap,
  8515. UniformsLib.aomap,
  8516. UniformsLib.lightmap,
  8517. UniformsLib.fog
  8518. ] ),
  8519. vertexShader: ShaderChunk.meshbasic_vert,
  8520. fragmentShader: ShaderChunk.meshbasic_frag
  8521. },
  8522. lambert: {
  8523. uniforms: /*@__PURE__*/ mergeUniforms( [
  8524. UniformsLib.common,
  8525. UniformsLib.specularmap,
  8526. UniformsLib.envmap,
  8527. UniformsLib.aomap,
  8528. UniformsLib.lightmap,
  8529. UniformsLib.emissivemap,
  8530. UniformsLib.bumpmap,
  8531. UniformsLib.normalmap,
  8532. UniformsLib.displacementmap,
  8533. UniformsLib.fog,
  8534. UniformsLib.lights,
  8535. {
  8536. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8537. }
  8538. ] ),
  8539. vertexShader: ShaderChunk.meshlambert_vert,
  8540. fragmentShader: ShaderChunk.meshlambert_frag
  8541. },
  8542. phong: {
  8543. uniforms: /*@__PURE__*/ mergeUniforms( [
  8544. UniformsLib.common,
  8545. UniformsLib.specularmap,
  8546. UniformsLib.envmap,
  8547. UniformsLib.aomap,
  8548. UniformsLib.lightmap,
  8549. UniformsLib.emissivemap,
  8550. UniformsLib.bumpmap,
  8551. UniformsLib.normalmap,
  8552. UniformsLib.displacementmap,
  8553. UniformsLib.fog,
  8554. UniformsLib.lights,
  8555. {
  8556. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8557. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  8558. shininess: { value: 30 }
  8559. }
  8560. ] ),
  8561. vertexShader: ShaderChunk.meshphong_vert,
  8562. fragmentShader: ShaderChunk.meshphong_frag
  8563. },
  8564. standard: {
  8565. uniforms: /*@__PURE__*/ mergeUniforms( [
  8566. UniformsLib.common,
  8567. UniformsLib.envmap,
  8568. UniformsLib.aomap,
  8569. UniformsLib.lightmap,
  8570. UniformsLib.emissivemap,
  8571. UniformsLib.bumpmap,
  8572. UniformsLib.normalmap,
  8573. UniformsLib.displacementmap,
  8574. UniformsLib.roughnessmap,
  8575. UniformsLib.metalnessmap,
  8576. UniformsLib.fog,
  8577. UniformsLib.lights,
  8578. {
  8579. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8580. roughness: { value: 1.0 },
  8581. metalness: { value: 0.0 },
  8582. envMapIntensity: { value: 1 } // temporary
  8583. }
  8584. ] ),
  8585. vertexShader: ShaderChunk.meshphysical_vert,
  8586. fragmentShader: ShaderChunk.meshphysical_frag
  8587. },
  8588. toon: {
  8589. uniforms: /*@__PURE__*/ mergeUniforms( [
  8590. UniformsLib.common,
  8591. UniformsLib.aomap,
  8592. UniformsLib.lightmap,
  8593. UniformsLib.emissivemap,
  8594. UniformsLib.bumpmap,
  8595. UniformsLib.normalmap,
  8596. UniformsLib.displacementmap,
  8597. UniformsLib.gradientmap,
  8598. UniformsLib.fog,
  8599. UniformsLib.lights,
  8600. {
  8601. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8602. }
  8603. ] ),
  8604. vertexShader: ShaderChunk.meshtoon_vert,
  8605. fragmentShader: ShaderChunk.meshtoon_frag
  8606. },
  8607. matcap: {
  8608. uniforms: /*@__PURE__*/ mergeUniforms( [
  8609. UniformsLib.common,
  8610. UniformsLib.bumpmap,
  8611. UniformsLib.normalmap,
  8612. UniformsLib.displacementmap,
  8613. UniformsLib.fog,
  8614. {
  8615. matcap: { value: null }
  8616. }
  8617. ] ),
  8618. vertexShader: ShaderChunk.meshmatcap_vert,
  8619. fragmentShader: ShaderChunk.meshmatcap_frag
  8620. },
  8621. points: {
  8622. uniforms: /*@__PURE__*/ mergeUniforms( [
  8623. UniformsLib.points,
  8624. UniformsLib.fog
  8625. ] ),
  8626. vertexShader: ShaderChunk.points_vert,
  8627. fragmentShader: ShaderChunk.points_frag
  8628. },
  8629. dashed: {
  8630. uniforms: /*@__PURE__*/ mergeUniforms( [
  8631. UniformsLib.common,
  8632. UniformsLib.fog,
  8633. {
  8634. scale: { value: 1 },
  8635. dashSize: { value: 1 },
  8636. totalSize: { value: 2 }
  8637. }
  8638. ] ),
  8639. vertexShader: ShaderChunk.linedashed_vert,
  8640. fragmentShader: ShaderChunk.linedashed_frag
  8641. },
  8642. depth: {
  8643. uniforms: /*@__PURE__*/ mergeUniforms( [
  8644. UniformsLib.common,
  8645. UniformsLib.displacementmap
  8646. ] ),
  8647. vertexShader: ShaderChunk.depth_vert,
  8648. fragmentShader: ShaderChunk.depth_frag
  8649. },
  8650. normal: {
  8651. uniforms: /*@__PURE__*/ mergeUniforms( [
  8652. UniformsLib.common,
  8653. UniformsLib.bumpmap,
  8654. UniformsLib.normalmap,
  8655. UniformsLib.displacementmap,
  8656. {
  8657. opacity: { value: 1.0 }
  8658. }
  8659. ] ),
  8660. vertexShader: ShaderChunk.meshnormal_vert,
  8661. fragmentShader: ShaderChunk.meshnormal_frag
  8662. },
  8663. sprite: {
  8664. uniforms: /*@__PURE__*/ mergeUniforms( [
  8665. UniformsLib.sprite,
  8666. UniformsLib.fog
  8667. ] ),
  8668. vertexShader: ShaderChunk.sprite_vert,
  8669. fragmentShader: ShaderChunk.sprite_frag
  8670. },
  8671. background: {
  8672. uniforms: {
  8673. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  8674. t2D: { value: null },
  8675. backgroundIntensity: { value: 1 }
  8676. },
  8677. vertexShader: ShaderChunk.background_vert,
  8678. fragmentShader: ShaderChunk.background_frag
  8679. },
  8680. backgroundCube: {
  8681. uniforms: {
  8682. envMap: { value: null },
  8683. flipEnvMap: { value: - 1 },
  8684. backgroundBlurriness: { value: 0 },
  8685. backgroundIntensity: { value: 1 }
  8686. },
  8687. vertexShader: ShaderChunk.backgroundCube_vert,
  8688. fragmentShader: ShaderChunk.backgroundCube_frag
  8689. },
  8690. cube: {
  8691. uniforms: {
  8692. tCube: { value: null },
  8693. tFlip: { value: - 1 },
  8694. opacity: { value: 1.0 }
  8695. },
  8696. vertexShader: ShaderChunk.cube_vert,
  8697. fragmentShader: ShaderChunk.cube_frag
  8698. },
  8699. equirect: {
  8700. uniforms: {
  8701. tEquirect: { value: null },
  8702. },
  8703. vertexShader: ShaderChunk.equirect_vert,
  8704. fragmentShader: ShaderChunk.equirect_frag
  8705. },
  8706. distanceRGBA: {
  8707. uniforms: /*@__PURE__*/ mergeUniforms( [
  8708. UniformsLib.common,
  8709. UniformsLib.displacementmap,
  8710. {
  8711. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  8712. nearDistance: { value: 1 },
  8713. farDistance: { value: 1000 }
  8714. }
  8715. ] ),
  8716. vertexShader: ShaderChunk.distanceRGBA_vert,
  8717. fragmentShader: ShaderChunk.distanceRGBA_frag
  8718. },
  8719. shadow: {
  8720. uniforms: /*@__PURE__*/ mergeUniforms( [
  8721. UniformsLib.lights,
  8722. UniformsLib.fog,
  8723. {
  8724. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  8725. opacity: { value: 1.0 }
  8726. },
  8727. ] ),
  8728. vertexShader: ShaderChunk.shadow_vert,
  8729. fragmentShader: ShaderChunk.shadow_frag
  8730. }
  8731. };
  8732. ShaderLib.physical = {
  8733. uniforms: /*@__PURE__*/ mergeUniforms( [
  8734. ShaderLib.standard.uniforms,
  8735. {
  8736. clearcoat: { value: 0 },
  8737. clearcoatMap: { value: null },
  8738. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8739. clearcoatNormalMap: { value: null },
  8740. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8741. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  8742. clearcoatRoughness: { value: 0 },
  8743. clearcoatRoughnessMap: { value: null },
  8744. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8745. iridescence: { value: 0 },
  8746. iridescenceMap: { value: null },
  8747. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8748. iridescenceIOR: { value: 1.3 },
  8749. iridescenceThicknessMinimum: { value: 100 },
  8750. iridescenceThicknessMaximum: { value: 400 },
  8751. iridescenceThicknessMap: { value: null },
  8752. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8753. sheen: { value: 0 },
  8754. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8755. sheenColorMap: { value: null },
  8756. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8757. sheenRoughness: { value: 1 },
  8758. sheenRoughnessMap: { value: null },
  8759. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8760. transmission: { value: 0 },
  8761. transmissionMap: { value: null },
  8762. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8763. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  8764. transmissionSamplerMap: { value: null },
  8765. thickness: { value: 0 },
  8766. thicknessMap: { value: null },
  8767. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8768. attenuationDistance: { value: 0 },
  8769. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8770. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  8771. specularColorMap: { value: null },
  8772. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8773. specularIntensity: { value: 1 },
  8774. specularIntensityMap: { value: null },
  8775. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8776. anisotropyVector: { value: /*@__PURE__*/ new Vector2() },
  8777. anisotropyMap: { value: null },
  8778. anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  8779. }
  8780. ] ),
  8781. vertexShader: ShaderChunk.meshphysical_vert,
  8782. fragmentShader: ShaderChunk.meshphysical_frag
  8783. };
  8784. const _rgb = { r: 0, b: 0, g: 0 };
  8785. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  8786. const clearColor = new Color( 0x000000 );
  8787. let clearAlpha = alpha === true ? 0 : 1;
  8788. let planeMesh;
  8789. let boxMesh;
  8790. let currentBackground = null;
  8791. let currentBackgroundVersion = 0;
  8792. let currentTonemapping = null;
  8793. function render( renderList, scene ) {
  8794. let forceClear = false;
  8795. let background = scene.isScene === true ? scene.background : null;
  8796. if ( background && background.isTexture ) {
  8797. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  8798. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  8799. }
  8800. if ( background === null ) {
  8801. setClear( clearColor, clearAlpha );
  8802. } else if ( background && background.isColor ) {
  8803. setClear( background, 1 );
  8804. forceClear = true;
  8805. }
  8806. const xr = renderer.xr;
  8807. const environmentBlendMode = xr.getEnvironmentBlendMode();
  8808. switch ( environmentBlendMode ) {
  8809. case 'opaque':
  8810. forceClear = true;
  8811. break;
  8812. case 'additive':
  8813. state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );
  8814. forceClear = true;
  8815. break;
  8816. case 'alpha-blend':
  8817. state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );
  8818. forceClear = true;
  8819. break;
  8820. }
  8821. if ( renderer.autoClear || forceClear ) {
  8822. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8823. }
  8824. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8825. if ( boxMesh === undefined ) {
  8826. boxMesh = new Mesh(
  8827. new BoxGeometry( 1, 1, 1 ),
  8828. new ShaderMaterial( {
  8829. name: 'BackgroundCubeMaterial',
  8830. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  8831. vertexShader: ShaderLib.backgroundCube.vertexShader,
  8832. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  8833. side: BackSide,
  8834. depthTest: false,
  8835. depthWrite: false,
  8836. fog: false
  8837. } )
  8838. );
  8839. boxMesh.geometry.deleteAttribute( 'normal' );
  8840. boxMesh.geometry.deleteAttribute( 'uv' );
  8841. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8842. this.matrixWorld.copyPosition( camera.matrixWorld );
  8843. };
  8844. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  8845. Object.defineProperty( boxMesh.material, 'envMap', {
  8846. get: function () {
  8847. return this.uniforms.envMap.value;
  8848. }
  8849. } );
  8850. objects.update( boxMesh );
  8851. }
  8852. boxMesh.material.uniforms.envMap.value = background;
  8853. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  8854. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  8855. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8856. boxMesh.material.toneMapped = ( background.colorSpace === SRGBColorSpace ) ? false : true;
  8857. if ( currentBackground !== background ||
  8858. currentBackgroundVersion !== background.version ||
  8859. currentTonemapping !== renderer.toneMapping ) {
  8860. boxMesh.material.needsUpdate = true;
  8861. currentBackground = background;
  8862. currentBackgroundVersion = background.version;
  8863. currentTonemapping = renderer.toneMapping;
  8864. }
  8865. boxMesh.layers.enableAll();
  8866. // push to the pre-sorted opaque render list
  8867. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  8868. } else if ( background && background.isTexture ) {
  8869. if ( planeMesh === undefined ) {
  8870. planeMesh = new Mesh(
  8871. new PlaneGeometry( 2, 2 ),
  8872. new ShaderMaterial( {
  8873. name: 'BackgroundMaterial',
  8874. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  8875. vertexShader: ShaderLib.background.vertexShader,
  8876. fragmentShader: ShaderLib.background.fragmentShader,
  8877. side: FrontSide,
  8878. depthTest: false,
  8879. depthWrite: false,
  8880. fog: false
  8881. } )
  8882. );
  8883. planeMesh.geometry.deleteAttribute( 'normal' );
  8884. // add "map" material property so the renderer can evaluate it like for built-in materials
  8885. Object.defineProperty( planeMesh.material, 'map', {
  8886. get: function () {
  8887. return this.uniforms.t2D.value;
  8888. }
  8889. } );
  8890. objects.update( planeMesh );
  8891. }
  8892. planeMesh.material.uniforms.t2D.value = background;
  8893. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8894. planeMesh.material.toneMapped = ( background.colorSpace === SRGBColorSpace ) ? false : true;
  8895. if ( background.matrixAutoUpdate === true ) {
  8896. background.updateMatrix();
  8897. }
  8898. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  8899. if ( currentBackground !== background ||
  8900. currentBackgroundVersion !== background.version ||
  8901. currentTonemapping !== renderer.toneMapping ) {
  8902. planeMesh.material.needsUpdate = true;
  8903. currentBackground = background;
  8904. currentBackgroundVersion = background.version;
  8905. currentTonemapping = renderer.toneMapping;
  8906. }
  8907. planeMesh.layers.enableAll();
  8908. // push to the pre-sorted opaque render list
  8909. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  8910. }
  8911. }
  8912. function setClear( color, alpha ) {
  8913. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  8914. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  8915. }
  8916. return {
  8917. getClearColor: function () {
  8918. return clearColor;
  8919. },
  8920. setClearColor: function ( color, alpha = 1 ) {
  8921. clearColor.set( color );
  8922. clearAlpha = alpha;
  8923. setClear( clearColor, clearAlpha );
  8924. },
  8925. getClearAlpha: function () {
  8926. return clearAlpha;
  8927. },
  8928. setClearAlpha: function ( alpha ) {
  8929. clearAlpha = alpha;
  8930. setClear( clearColor, clearAlpha );
  8931. },
  8932. render: render
  8933. };
  8934. }
  8935. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  8936. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  8937. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  8938. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8939. const bindingStates = {};
  8940. const defaultState = createBindingState( null );
  8941. let currentState = defaultState;
  8942. let forceUpdate = false;
  8943. function setup( object, material, program, geometry, index ) {
  8944. let updateBuffers = false;
  8945. if ( vaoAvailable ) {
  8946. const state = getBindingState( geometry, program, material );
  8947. if ( currentState !== state ) {
  8948. currentState = state;
  8949. bindVertexArrayObject( currentState.object );
  8950. }
  8951. updateBuffers = needsUpdate( object, geometry, program, index );
  8952. if ( updateBuffers ) saveCache( object, geometry, program, index );
  8953. } else {
  8954. const wireframe = ( material.wireframe === true );
  8955. if ( currentState.geometry !== geometry.id ||
  8956. currentState.program !== program.id ||
  8957. currentState.wireframe !== wireframe ) {
  8958. currentState.geometry = geometry.id;
  8959. currentState.program = program.id;
  8960. currentState.wireframe = wireframe;
  8961. updateBuffers = true;
  8962. }
  8963. }
  8964. if ( index !== null ) {
  8965. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  8966. }
  8967. if ( updateBuffers || forceUpdate ) {
  8968. forceUpdate = false;
  8969. setupVertexAttributes( object, material, program, geometry );
  8970. if ( index !== null ) {
  8971. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  8972. }
  8973. }
  8974. }
  8975. function createVertexArrayObject() {
  8976. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  8977. return extension.createVertexArrayOES();
  8978. }
  8979. function bindVertexArrayObject( vao ) {
  8980. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  8981. return extension.bindVertexArrayOES( vao );
  8982. }
  8983. function deleteVertexArrayObject( vao ) {
  8984. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  8985. return extension.deleteVertexArrayOES( vao );
  8986. }
  8987. function getBindingState( geometry, program, material ) {
  8988. const wireframe = ( material.wireframe === true );
  8989. let programMap = bindingStates[ geometry.id ];
  8990. if ( programMap === undefined ) {
  8991. programMap = {};
  8992. bindingStates[ geometry.id ] = programMap;
  8993. }
  8994. let stateMap = programMap[ program.id ];
  8995. if ( stateMap === undefined ) {
  8996. stateMap = {};
  8997. programMap[ program.id ] = stateMap;
  8998. }
  8999. let state = stateMap[ wireframe ];
  9000. if ( state === undefined ) {
  9001. state = createBindingState( createVertexArrayObject() );
  9002. stateMap[ wireframe ] = state;
  9003. }
  9004. return state;
  9005. }
  9006. function createBindingState( vao ) {
  9007. const newAttributes = [];
  9008. const enabledAttributes = [];
  9009. const attributeDivisors = [];
  9010. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  9011. newAttributes[ i ] = 0;
  9012. enabledAttributes[ i ] = 0;
  9013. attributeDivisors[ i ] = 0;
  9014. }
  9015. return {
  9016. // for backward compatibility on non-VAO support browser
  9017. geometry: null,
  9018. program: null,
  9019. wireframe: false,
  9020. newAttributes: newAttributes,
  9021. enabledAttributes: enabledAttributes,
  9022. attributeDivisors: attributeDivisors,
  9023. object: vao,
  9024. attributes: {},
  9025. index: null
  9026. };
  9027. }
  9028. function needsUpdate( object, geometry, program, index ) {
  9029. const cachedAttributes = currentState.attributes;
  9030. const geometryAttributes = geometry.attributes;
  9031. let attributesNum = 0;
  9032. const programAttributes = program.getAttributes();
  9033. for ( const name in programAttributes ) {
  9034. const programAttribute = programAttributes[ name ];
  9035. if ( programAttribute.location >= 0 ) {
  9036. const cachedAttribute = cachedAttributes[ name ];
  9037. let geometryAttribute = geometryAttributes[ name ];
  9038. if ( geometryAttribute === undefined ) {
  9039. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  9040. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  9041. }
  9042. if ( cachedAttribute === undefined ) return true;
  9043. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  9044. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  9045. attributesNum ++;
  9046. }
  9047. }
  9048. if ( currentState.attributesNum !== attributesNum ) return true;
  9049. if ( currentState.index !== index ) return true;
  9050. return false;
  9051. }
  9052. function saveCache( object, geometry, program, index ) {
  9053. const cache = {};
  9054. const attributes = geometry.attributes;
  9055. let attributesNum = 0;
  9056. const programAttributes = program.getAttributes();
  9057. for ( const name in programAttributes ) {
  9058. const programAttribute = programAttributes[ name ];
  9059. if ( programAttribute.location >= 0 ) {
  9060. let attribute = attributes[ name ];
  9061. if ( attribute === undefined ) {
  9062. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  9063. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  9064. }
  9065. const data = {};
  9066. data.attribute = attribute;
  9067. if ( attribute && attribute.data ) {
  9068. data.data = attribute.data;
  9069. }
  9070. cache[ name ] = data;
  9071. attributesNum ++;
  9072. }
  9073. }
  9074. currentState.attributes = cache;
  9075. currentState.attributesNum = attributesNum;
  9076. currentState.index = index;
  9077. }
  9078. function initAttributes() {
  9079. const newAttributes = currentState.newAttributes;
  9080. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  9081. newAttributes[ i ] = 0;
  9082. }
  9083. }
  9084. function enableAttribute( attribute ) {
  9085. enableAttributeAndDivisor( attribute, 0 );
  9086. }
  9087. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  9088. const newAttributes = currentState.newAttributes;
  9089. const enabledAttributes = currentState.enabledAttributes;
  9090. const attributeDivisors = currentState.attributeDivisors;
  9091. newAttributes[ attribute ] = 1;
  9092. if ( enabledAttributes[ attribute ] === 0 ) {
  9093. gl.enableVertexAttribArray( attribute );
  9094. enabledAttributes[ attribute ] = 1;
  9095. }
  9096. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  9097. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  9098. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  9099. attributeDivisors[ attribute ] = meshPerAttribute;
  9100. }
  9101. }
  9102. function disableUnusedAttributes() {
  9103. const newAttributes = currentState.newAttributes;
  9104. const enabledAttributes = currentState.enabledAttributes;
  9105. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  9106. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  9107. gl.disableVertexAttribArray( i );
  9108. enabledAttributes[ i ] = 0;
  9109. }
  9110. }
  9111. }
  9112. function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) {
  9113. if ( integer === true ) {
  9114. gl.vertexAttribIPointer( index, size, type, stride, offset );
  9115. } else {
  9116. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  9117. }
  9118. }
  9119. function setupVertexAttributes( object, material, program, geometry ) {
  9120. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  9121. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  9122. }
  9123. initAttributes();
  9124. const geometryAttributes = geometry.attributes;
  9125. const programAttributes = program.getAttributes();
  9126. const materialDefaultAttributeValues = material.defaultAttributeValues;
  9127. for ( const name in programAttributes ) {
  9128. const programAttribute = programAttributes[ name ];
  9129. if ( programAttribute.location >= 0 ) {
  9130. let geometryAttribute = geometryAttributes[ name ];
  9131. if ( geometryAttribute === undefined ) {
  9132. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  9133. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  9134. }
  9135. if ( geometryAttribute !== undefined ) {
  9136. const normalized = geometryAttribute.normalized;
  9137. const size = geometryAttribute.itemSize;
  9138. const attribute = attributes.get( geometryAttribute );
  9139. // TODO Attribute may not be available on context restore
  9140. if ( attribute === undefined ) continue;
  9141. const buffer = attribute.buffer;
  9142. const type = attribute.type;
  9143. const bytesPerElement = attribute.bytesPerElement;
  9144. // check for integer attributes (WebGL 2 only)
  9145. const integer = ( capabilities.isWebGL2 === true && ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType ) );
  9146. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  9147. const data = geometryAttribute.data;
  9148. const stride = data.stride;
  9149. const offset = geometryAttribute.offset;
  9150. if ( data.isInstancedInterleavedBuffer ) {
  9151. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9152. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  9153. }
  9154. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  9155. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  9156. }
  9157. } else {
  9158. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9159. enableAttribute( programAttribute.location + i );
  9160. }
  9161. }
  9162. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  9163. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9164. vertexAttribPointer(
  9165. programAttribute.location + i,
  9166. size / programAttribute.locationSize,
  9167. type,
  9168. normalized,
  9169. stride * bytesPerElement,
  9170. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement,
  9171. integer
  9172. );
  9173. }
  9174. } else {
  9175. if ( geometryAttribute.isInstancedBufferAttribute ) {
  9176. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9177. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  9178. }
  9179. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  9180. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  9181. }
  9182. } else {
  9183. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9184. enableAttribute( programAttribute.location + i );
  9185. }
  9186. }
  9187. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  9188. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  9189. vertexAttribPointer(
  9190. programAttribute.location + i,
  9191. size / programAttribute.locationSize,
  9192. type,
  9193. normalized,
  9194. size * bytesPerElement,
  9195. ( size / programAttribute.locationSize ) * i * bytesPerElement,
  9196. integer
  9197. );
  9198. }
  9199. }
  9200. } else if ( materialDefaultAttributeValues !== undefined ) {
  9201. const value = materialDefaultAttributeValues[ name ];
  9202. if ( value !== undefined ) {
  9203. switch ( value.length ) {
  9204. case 2:
  9205. gl.vertexAttrib2fv( programAttribute.location, value );
  9206. break;
  9207. case 3:
  9208. gl.vertexAttrib3fv( programAttribute.location, value );
  9209. break;
  9210. case 4:
  9211. gl.vertexAttrib4fv( programAttribute.location, value );
  9212. break;
  9213. default:
  9214. gl.vertexAttrib1fv( programAttribute.location, value );
  9215. }
  9216. }
  9217. }
  9218. }
  9219. }
  9220. disableUnusedAttributes();
  9221. }
  9222. function dispose() {
  9223. reset();
  9224. for ( const geometryId in bindingStates ) {
  9225. const programMap = bindingStates[ geometryId ];
  9226. for ( const programId in programMap ) {
  9227. const stateMap = programMap[ programId ];
  9228. for ( const wireframe in stateMap ) {
  9229. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9230. delete stateMap[ wireframe ];
  9231. }
  9232. delete programMap[ programId ];
  9233. }
  9234. delete bindingStates[ geometryId ];
  9235. }
  9236. }
  9237. function releaseStatesOfGeometry( geometry ) {
  9238. if ( bindingStates[ geometry.id ] === undefined ) return;
  9239. const programMap = bindingStates[ geometry.id ];
  9240. for ( const programId in programMap ) {
  9241. const stateMap = programMap[ programId ];
  9242. for ( const wireframe in stateMap ) {
  9243. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9244. delete stateMap[ wireframe ];
  9245. }
  9246. delete programMap[ programId ];
  9247. }
  9248. delete bindingStates[ geometry.id ];
  9249. }
  9250. function releaseStatesOfProgram( program ) {
  9251. for ( const geometryId in bindingStates ) {
  9252. const programMap = bindingStates[ geometryId ];
  9253. if ( programMap[ program.id ] === undefined ) continue;
  9254. const stateMap = programMap[ program.id ];
  9255. for ( const wireframe in stateMap ) {
  9256. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9257. delete stateMap[ wireframe ];
  9258. }
  9259. delete programMap[ program.id ];
  9260. }
  9261. }
  9262. function reset() {
  9263. resetDefaultState();
  9264. forceUpdate = true;
  9265. if ( currentState === defaultState ) return;
  9266. currentState = defaultState;
  9267. bindVertexArrayObject( currentState.object );
  9268. }
  9269. // for backward-compatibility
  9270. function resetDefaultState() {
  9271. defaultState.geometry = null;
  9272. defaultState.program = null;
  9273. defaultState.wireframe = false;
  9274. }
  9275. return {
  9276. setup: setup,
  9277. reset: reset,
  9278. resetDefaultState: resetDefaultState,
  9279. dispose: dispose,
  9280. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9281. releaseStatesOfProgram: releaseStatesOfProgram,
  9282. initAttributes: initAttributes,
  9283. enableAttribute: enableAttribute,
  9284. disableUnusedAttributes: disableUnusedAttributes
  9285. };
  9286. }
  9287. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  9288. const isWebGL2 = capabilities.isWebGL2;
  9289. let mode;
  9290. function setMode( value ) {
  9291. mode = value;
  9292. }
  9293. function render( start, count ) {
  9294. gl.drawArrays( mode, start, count );
  9295. info.update( count, mode, 1 );
  9296. }
  9297. function renderInstances( start, count, primcount ) {
  9298. if ( primcount === 0 ) return;
  9299. let extension, methodName;
  9300. if ( isWebGL2 ) {
  9301. extension = gl;
  9302. methodName = 'drawArraysInstanced';
  9303. } else {
  9304. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9305. methodName = 'drawArraysInstancedANGLE';
  9306. if ( extension === null ) {
  9307. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9308. return;
  9309. }
  9310. }
  9311. extension[ methodName ]( mode, start, count, primcount );
  9312. info.update( count, mode, primcount );
  9313. }
  9314. //
  9315. this.setMode = setMode;
  9316. this.render = render;
  9317. this.renderInstances = renderInstances;
  9318. }
  9319. function WebGLCapabilities( gl, extensions, parameters ) {
  9320. let maxAnisotropy;
  9321. function getMaxAnisotropy() {
  9322. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  9323. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  9324. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  9325. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  9326. } else {
  9327. maxAnisotropy = 0;
  9328. }
  9329. return maxAnisotropy;
  9330. }
  9331. function getMaxPrecision( precision ) {
  9332. if ( precision === 'highp' ) {
  9333. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  9334. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  9335. return 'highp';
  9336. }
  9337. precision = 'mediump';
  9338. }
  9339. if ( precision === 'mediump' ) {
  9340. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  9341. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  9342. return 'mediump';
  9343. }
  9344. }
  9345. return 'lowp';
  9346. }
  9347. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl.constructor.name === 'WebGL2RenderingContext';
  9348. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9349. const maxPrecision = getMaxPrecision( precision );
  9350. if ( maxPrecision !== precision ) {
  9351. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  9352. precision = maxPrecision;
  9353. }
  9354. const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' );
  9355. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9356. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  9357. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  9358. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  9359. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  9360. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  9361. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  9362. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  9363. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  9364. const vertexTextures = maxVertexTextures > 0;
  9365. const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );
  9366. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9367. const maxSamples = isWebGL2 ? gl.getParameter( gl.MAX_SAMPLES ) : 0;
  9368. return {
  9369. isWebGL2: isWebGL2,
  9370. drawBuffers: drawBuffers,
  9371. getMaxAnisotropy: getMaxAnisotropy,
  9372. getMaxPrecision: getMaxPrecision,
  9373. precision: precision,
  9374. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9375. maxTextures: maxTextures,
  9376. maxVertexTextures: maxVertexTextures,
  9377. maxTextureSize: maxTextureSize,
  9378. maxCubemapSize: maxCubemapSize,
  9379. maxAttributes: maxAttributes,
  9380. maxVertexUniforms: maxVertexUniforms,
  9381. maxVaryings: maxVaryings,
  9382. maxFragmentUniforms: maxFragmentUniforms,
  9383. vertexTextures: vertexTextures,
  9384. floatFragmentTextures: floatFragmentTextures,
  9385. floatVertexTextures: floatVertexTextures,
  9386. maxSamples: maxSamples
  9387. };
  9388. }
  9389. function WebGLClipping( properties ) {
  9390. const scope = this;
  9391. let globalState = null,
  9392. numGlobalPlanes = 0,
  9393. localClippingEnabled = false,
  9394. renderingShadows = false;
  9395. const plane = new Plane(),
  9396. viewNormalMatrix = new Matrix3(),
  9397. uniform = { value: null, needsUpdate: false };
  9398. this.uniform = uniform;
  9399. this.numPlanes = 0;
  9400. this.numIntersection = 0;
  9401. this.init = function ( planes, enableLocalClipping ) {
  9402. const enabled =
  9403. planes.length !== 0 ||
  9404. enableLocalClipping ||
  9405. // enable state of previous frame - the clipping code has to
  9406. // run another frame in order to reset the state:
  9407. numGlobalPlanes !== 0 ||
  9408. localClippingEnabled;
  9409. localClippingEnabled = enableLocalClipping;
  9410. numGlobalPlanes = planes.length;
  9411. return enabled;
  9412. };
  9413. this.beginShadows = function () {
  9414. renderingShadows = true;
  9415. projectPlanes( null );
  9416. };
  9417. this.endShadows = function () {
  9418. renderingShadows = false;
  9419. };
  9420. this.setGlobalState = function ( planes, camera ) {
  9421. globalState = projectPlanes( planes, camera, 0 );
  9422. };
  9423. this.setState = function ( material, camera, useCache ) {
  9424. const planes = material.clippingPlanes,
  9425. clipIntersection = material.clipIntersection,
  9426. clipShadows = material.clipShadows;
  9427. const materialProperties = properties.get( material );
  9428. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  9429. // there's no local clipping
  9430. if ( renderingShadows ) {
  9431. // there's no global clipping
  9432. projectPlanes( null );
  9433. } else {
  9434. resetGlobalState();
  9435. }
  9436. } else {
  9437. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9438. lGlobal = nGlobal * 4;
  9439. let dstArray = materialProperties.clippingState || null;
  9440. uniform.value = dstArray; // ensure unique state
  9441. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  9442. for ( let i = 0; i !== lGlobal; ++ i ) {
  9443. dstArray[ i ] = globalState[ i ];
  9444. }
  9445. materialProperties.clippingState = dstArray;
  9446. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9447. this.numPlanes += nGlobal;
  9448. }
  9449. };
  9450. function resetGlobalState() {
  9451. if ( uniform.value !== globalState ) {
  9452. uniform.value = globalState;
  9453. uniform.needsUpdate = numGlobalPlanes > 0;
  9454. }
  9455. scope.numPlanes = numGlobalPlanes;
  9456. scope.numIntersection = 0;
  9457. }
  9458. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  9459. const nPlanes = planes !== null ? planes.length : 0;
  9460. let dstArray = null;
  9461. if ( nPlanes !== 0 ) {
  9462. dstArray = uniform.value;
  9463. if ( skipTransform !== true || dstArray === null ) {
  9464. const flatSize = dstOffset + nPlanes * 4,
  9465. viewMatrix = camera.matrixWorldInverse;
  9466. viewNormalMatrix.getNormalMatrix( viewMatrix );
  9467. if ( dstArray === null || dstArray.length < flatSize ) {
  9468. dstArray = new Float32Array( flatSize );
  9469. }
  9470. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  9471. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  9472. plane.normal.toArray( dstArray, i4 );
  9473. dstArray[ i4 + 3 ] = plane.constant;
  9474. }
  9475. }
  9476. uniform.value = dstArray;
  9477. uniform.needsUpdate = true;
  9478. }
  9479. scope.numPlanes = nPlanes;
  9480. scope.numIntersection = 0;
  9481. return dstArray;
  9482. }
  9483. }
  9484. function WebGLCubeMaps( renderer ) {
  9485. let cubemaps = new WeakMap();
  9486. function mapTextureMapping( texture, mapping ) {
  9487. if ( mapping === EquirectangularReflectionMapping ) {
  9488. texture.mapping = CubeReflectionMapping;
  9489. } else if ( mapping === EquirectangularRefractionMapping ) {
  9490. texture.mapping = CubeRefractionMapping;
  9491. }
  9492. return texture;
  9493. }
  9494. function get( texture ) {
  9495. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  9496. const mapping = texture.mapping;
  9497. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  9498. if ( cubemaps.has( texture ) ) {
  9499. const cubemap = cubemaps.get( texture ).texture;
  9500. return mapTextureMapping( cubemap, texture.mapping );
  9501. } else {
  9502. const image = texture.image;
  9503. if ( image && image.height > 0 ) {
  9504. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  9505. renderTarget.fromEquirectangularTexture( renderer, texture );
  9506. cubemaps.set( texture, renderTarget );
  9507. texture.addEventListener( 'dispose', onTextureDispose );
  9508. return mapTextureMapping( renderTarget.texture, texture.mapping );
  9509. } else {
  9510. // image not yet ready. try the conversion next frame
  9511. return null;
  9512. }
  9513. }
  9514. }
  9515. }
  9516. return texture;
  9517. }
  9518. function onTextureDispose( event ) {
  9519. const texture = event.target;
  9520. texture.removeEventListener( 'dispose', onTextureDispose );
  9521. const cubemap = cubemaps.get( texture );
  9522. if ( cubemap !== undefined ) {
  9523. cubemaps.delete( texture );
  9524. cubemap.dispose();
  9525. }
  9526. }
  9527. function dispose() {
  9528. cubemaps = new WeakMap();
  9529. }
  9530. return {
  9531. get: get,
  9532. dispose: dispose
  9533. };
  9534. }
  9535. class OrthographicCamera extends Camera {
  9536. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  9537. super();
  9538. this.isOrthographicCamera = true;
  9539. this.type = 'OrthographicCamera';
  9540. this.zoom = 1;
  9541. this.view = null;
  9542. this.left = left;
  9543. this.right = right;
  9544. this.top = top;
  9545. this.bottom = bottom;
  9546. this.near = near;
  9547. this.far = far;
  9548. this.updateProjectionMatrix();
  9549. }
  9550. copy( source, recursive ) {
  9551. super.copy( source, recursive );
  9552. this.left = source.left;
  9553. this.right = source.right;
  9554. this.top = source.top;
  9555. this.bottom = source.bottom;
  9556. this.near = source.near;
  9557. this.far = source.far;
  9558. this.zoom = source.zoom;
  9559. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9560. return this;
  9561. }
  9562. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  9563. if ( this.view === null ) {
  9564. this.view = {
  9565. enabled: true,
  9566. fullWidth: 1,
  9567. fullHeight: 1,
  9568. offsetX: 0,
  9569. offsetY: 0,
  9570. width: 1,
  9571. height: 1
  9572. };
  9573. }
  9574. this.view.enabled = true;
  9575. this.view.fullWidth = fullWidth;
  9576. this.view.fullHeight = fullHeight;
  9577. this.view.offsetX = x;
  9578. this.view.offsetY = y;
  9579. this.view.width = width;
  9580. this.view.height = height;
  9581. this.updateProjectionMatrix();
  9582. }
  9583. clearViewOffset() {
  9584. if ( this.view !== null ) {
  9585. this.view.enabled = false;
  9586. }
  9587. this.updateProjectionMatrix();
  9588. }
  9589. updateProjectionMatrix() {
  9590. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9591. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9592. const cx = ( this.right + this.left ) / 2;
  9593. const cy = ( this.top + this.bottom ) / 2;
  9594. let left = cx - dx;
  9595. let right = cx + dx;
  9596. let top = cy + dy;
  9597. let bottom = cy - dy;
  9598. if ( this.view !== null && this.view.enabled ) {
  9599. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  9600. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  9601. left += scaleW * this.view.offsetX;
  9602. right = left + scaleW * this.view.width;
  9603. top -= scaleH * this.view.offsetY;
  9604. bottom = top - scaleH * this.view.height;
  9605. }
  9606. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem );
  9607. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  9608. }
  9609. toJSON( meta ) {
  9610. const data = super.toJSON( meta );
  9611. data.object.zoom = this.zoom;
  9612. data.object.left = this.left;
  9613. data.object.right = this.right;
  9614. data.object.top = this.top;
  9615. data.object.bottom = this.bottom;
  9616. data.object.near = this.near;
  9617. data.object.far = this.far;
  9618. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9619. return data;
  9620. }
  9621. }
  9622. const LOD_MIN = 4;
  9623. // The standard deviations (radians) associated with the extra mips. These are
  9624. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9625. // geometric shadowing function. These sigma values squared must match the
  9626. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9627. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  9628. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9629. // samples and exit early, but not recompile the shader.
  9630. const MAX_SAMPLES = 20;
  9631. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  9632. const _clearColor = /*@__PURE__*/ new Color();
  9633. let _oldTarget = null;
  9634. // Golden Ratio
  9635. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  9636. const INV_PHI = 1 / PHI;
  9637. // Vertices of a dodecahedron (except the opposites, which represent the
  9638. // same axis), used as axis directions evenly spread on a sphere.
  9639. const _axisDirections = [
  9640. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  9641. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  9642. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  9643. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  9644. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  9645. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  9646. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  9647. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  9648. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  9649. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  9650. /**
  9651. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9652. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9653. * blur to be quickly accessed based on material roughness. It is packed into a
  9654. * special CubeUV format that allows us to perform custom interpolation so that
  9655. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9656. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9657. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9658. * higher roughness levels. In this way we maintain resolution to smoothly
  9659. * interpolate diffuse lighting while limiting sampling computation.
  9660. *
  9661. * Paper: Fast, Accurate Image-Based Lighting
  9662. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9663. */
  9664. class PMREMGenerator {
  9665. constructor( renderer ) {
  9666. this._renderer = renderer;
  9667. this._pingPongRenderTarget = null;
  9668. this._lodMax = 0;
  9669. this._cubeSize = 0;
  9670. this._lodPlanes = [];
  9671. this._sizeLods = [];
  9672. this._sigmas = [];
  9673. this._blurMaterial = null;
  9674. this._cubemapMaterial = null;
  9675. this._equirectMaterial = null;
  9676. this._compileMaterial( this._blurMaterial );
  9677. }
  9678. /**
  9679. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9680. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9681. * in radians to be applied to the scene before PMREM generation. Optional near
  9682. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9683. * is placed at the origin).
  9684. */
  9685. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  9686. _oldTarget = this._renderer.getRenderTarget();
  9687. this._setSize( 256 );
  9688. const cubeUVRenderTarget = this._allocateTargets();
  9689. cubeUVRenderTarget.depthBuffer = true;
  9690. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  9691. if ( sigma > 0 ) {
  9692. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  9693. }
  9694. this._applyPMREM( cubeUVRenderTarget );
  9695. this._cleanup( cubeUVRenderTarget );
  9696. return cubeUVRenderTarget;
  9697. }
  9698. /**
  9699. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9700. * or HDR. The ideal input image size is 1k (1024 x 512),
  9701. * as this matches best with the 256 x 256 cubemap output.
  9702. */
  9703. fromEquirectangular( equirectangular, renderTarget = null ) {
  9704. return this._fromTexture( equirectangular, renderTarget );
  9705. }
  9706. /**
  9707. * Generates a PMREM from an cubemap texture, which can be either LDR
  9708. * or HDR. The ideal input cube size is 256 x 256,
  9709. * as this matches best with the 256 x 256 cubemap output.
  9710. */
  9711. fromCubemap( cubemap, renderTarget = null ) {
  9712. return this._fromTexture( cubemap, renderTarget );
  9713. }
  9714. /**
  9715. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9716. * your texture's network fetch for increased concurrency.
  9717. */
  9718. compileCubemapShader() {
  9719. if ( this._cubemapMaterial === null ) {
  9720. this._cubemapMaterial = _getCubemapMaterial();
  9721. this._compileMaterial( this._cubemapMaterial );
  9722. }
  9723. }
  9724. /**
  9725. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9726. * your texture's network fetch for increased concurrency.
  9727. */
  9728. compileEquirectangularShader() {
  9729. if ( this._equirectMaterial === null ) {
  9730. this._equirectMaterial = _getEquirectMaterial();
  9731. this._compileMaterial( this._equirectMaterial );
  9732. }
  9733. }
  9734. /**
  9735. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9736. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9737. * one of them will cause any others to also become unusable.
  9738. */
  9739. dispose() {
  9740. this._dispose();
  9741. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  9742. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  9743. }
  9744. // private interface
  9745. _setSize( cubeSize ) {
  9746. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  9747. this._cubeSize = Math.pow( 2, this._lodMax );
  9748. }
  9749. _dispose() {
  9750. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  9751. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  9752. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  9753. this._lodPlanes[ i ].dispose();
  9754. }
  9755. }
  9756. _cleanup( outputTarget ) {
  9757. this._renderer.setRenderTarget( _oldTarget );
  9758. outputTarget.scissorTest = false;
  9759. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  9760. }
  9761. _fromTexture( texture, renderTarget ) {
  9762. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  9763. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  9764. } else { // Equirectangular
  9765. this._setSize( texture.image.width / 4 );
  9766. }
  9767. _oldTarget = this._renderer.getRenderTarget();
  9768. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9769. this._textureToCubeUV( texture, cubeUVRenderTarget );
  9770. this._applyPMREM( cubeUVRenderTarget );
  9771. this._cleanup( cubeUVRenderTarget );
  9772. return cubeUVRenderTarget;
  9773. }
  9774. _allocateTargets() {
  9775. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  9776. const height = 4 * this._cubeSize;
  9777. const params = {
  9778. magFilter: LinearFilter,
  9779. minFilter: LinearFilter,
  9780. generateMipmaps: false,
  9781. type: HalfFloatType,
  9782. format: RGBAFormat,
  9783. colorSpace: LinearSRGBColorSpace,
  9784. depthBuffer: false
  9785. };
  9786. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  9787. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  9788. if ( this._pingPongRenderTarget !== null ) {
  9789. this._dispose();
  9790. }
  9791. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  9792. const { _lodMax } = this;
  9793. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  9794. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  9795. }
  9796. return cubeUVRenderTarget;
  9797. }
  9798. _compileMaterial( material ) {
  9799. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  9800. this._renderer.compile( tmpMesh, _flatCamera );
  9801. }
  9802. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  9803. const fov = 90;
  9804. const aspect = 1;
  9805. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  9806. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  9807. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  9808. const renderer = this._renderer;
  9809. const originalAutoClear = renderer.autoClear;
  9810. const toneMapping = renderer.toneMapping;
  9811. renderer.getClearColor( _clearColor );
  9812. renderer.toneMapping = NoToneMapping;
  9813. renderer.autoClear = false;
  9814. const backgroundMaterial = new MeshBasicMaterial( {
  9815. name: 'PMREM.Background',
  9816. side: BackSide,
  9817. depthWrite: false,
  9818. depthTest: false,
  9819. } );
  9820. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  9821. let useSolidColor = false;
  9822. const background = scene.background;
  9823. if ( background ) {
  9824. if ( background.isColor ) {
  9825. backgroundMaterial.color.copy( background );
  9826. scene.background = null;
  9827. useSolidColor = true;
  9828. }
  9829. } else {
  9830. backgroundMaterial.color.copy( _clearColor );
  9831. useSolidColor = true;
  9832. }
  9833. for ( let i = 0; i < 6; i ++ ) {
  9834. const col = i % 3;
  9835. if ( col === 0 ) {
  9836. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9837. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  9838. } else if ( col === 1 ) {
  9839. cubeCamera.up.set( 0, 0, upSign[ i ] );
  9840. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  9841. } else {
  9842. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9843. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  9844. }
  9845. const size = this._cubeSize;
  9846. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  9847. renderer.setRenderTarget( cubeUVRenderTarget );
  9848. if ( useSolidColor ) {
  9849. renderer.render( backgroundBox, cubeCamera );
  9850. }
  9851. renderer.render( scene, cubeCamera );
  9852. }
  9853. backgroundBox.geometry.dispose();
  9854. backgroundBox.material.dispose();
  9855. renderer.toneMapping = toneMapping;
  9856. renderer.autoClear = originalAutoClear;
  9857. scene.background = background;
  9858. }
  9859. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  9860. const renderer = this._renderer;
  9861. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  9862. if ( isCubeTexture ) {
  9863. if ( this._cubemapMaterial === null ) {
  9864. this._cubemapMaterial = _getCubemapMaterial();
  9865. }
  9866. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;
  9867. } else {
  9868. if ( this._equirectMaterial === null ) {
  9869. this._equirectMaterial = _getEquirectMaterial();
  9870. }
  9871. }
  9872. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  9873. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  9874. const uniforms = material.uniforms;
  9875. uniforms[ 'envMap' ].value = texture;
  9876. const size = this._cubeSize;
  9877. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  9878. renderer.setRenderTarget( cubeUVRenderTarget );
  9879. renderer.render( mesh, _flatCamera );
  9880. }
  9881. _applyPMREM( cubeUVRenderTarget ) {
  9882. const renderer = this._renderer;
  9883. const autoClear = renderer.autoClear;
  9884. renderer.autoClear = false;
  9885. for ( let i = 1; i < this._lodPlanes.length; i ++ ) {
  9886. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  9887. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  9888. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  9889. }
  9890. renderer.autoClear = autoClear;
  9891. }
  9892. /**
  9893. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9894. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9895. * the blur latitudinally (around the poles), and then longitudinally (towards
  9896. * the poles) to approximate the orthogonally-separable blur. It is least
  9897. * accurate at the poles, but still does a decent job.
  9898. */
  9899. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  9900. const pingPongRenderTarget = this._pingPongRenderTarget;
  9901. this._halfBlur(
  9902. cubeUVRenderTarget,
  9903. pingPongRenderTarget,
  9904. lodIn,
  9905. lodOut,
  9906. sigma,
  9907. 'latitudinal',
  9908. poleAxis );
  9909. this._halfBlur(
  9910. pingPongRenderTarget,
  9911. cubeUVRenderTarget,
  9912. lodOut,
  9913. lodOut,
  9914. sigma,
  9915. 'longitudinal',
  9916. poleAxis );
  9917. }
  9918. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  9919. const renderer = this._renderer;
  9920. const blurMaterial = this._blurMaterial;
  9921. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  9922. console.error(
  9923. 'blur direction must be either latitudinal or longitudinal!' );
  9924. }
  9925. // Number of standard deviations at which to cut off the discrete approximation.
  9926. const STANDARD_DEVIATIONS = 3;
  9927. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  9928. const blurUniforms = blurMaterial.uniforms;
  9929. const pixels = this._sizeLods[ lodIn ] - 1;
  9930. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  9931. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9932. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  9933. if ( samples > MAX_SAMPLES ) {
  9934. console.warn( `sigmaRadians, ${
  9935. sigmaRadians}, is too large and will clip, as it requested ${
  9936. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  9937. }
  9938. const weights = [];
  9939. let sum = 0;
  9940. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  9941. const x = i / sigmaPixels;
  9942. const weight = Math.exp( - x * x / 2 );
  9943. weights.push( weight );
  9944. if ( i === 0 ) {
  9945. sum += weight;
  9946. } else if ( i < samples ) {
  9947. sum += 2 * weight;
  9948. }
  9949. }
  9950. for ( let i = 0; i < weights.length; i ++ ) {
  9951. weights[ i ] = weights[ i ] / sum;
  9952. }
  9953. blurUniforms[ 'envMap' ].value = targetIn.texture;
  9954. blurUniforms[ 'samples' ].value = samples;
  9955. blurUniforms[ 'weights' ].value = weights;
  9956. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  9957. if ( poleAxis ) {
  9958. blurUniforms[ 'poleAxis' ].value = poleAxis;
  9959. }
  9960. const { _lodMax } = this;
  9961. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  9962. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  9963. const outputSize = this._sizeLods[ lodOut ];
  9964. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  9965. const y = 4 * ( this._cubeSize - outputSize );
  9966. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  9967. renderer.setRenderTarget( targetOut );
  9968. renderer.render( blurMesh, _flatCamera );
  9969. }
  9970. }
  9971. function _createPlanes( lodMax ) {
  9972. const lodPlanes = [];
  9973. const sizeLods = [];
  9974. const sigmas = [];
  9975. let lod = lodMax;
  9976. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  9977. for ( let i = 0; i < totalLods; i ++ ) {
  9978. const sizeLod = Math.pow( 2, lod );
  9979. sizeLods.push( sizeLod );
  9980. let sigma = 1.0 / sizeLod;
  9981. if ( i > lodMax - LOD_MIN ) {
  9982. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  9983. } else if ( i === 0 ) {
  9984. sigma = 0;
  9985. }
  9986. sigmas.push( sigma );
  9987. const texelSize = 1.0 / ( sizeLod - 2 );
  9988. const min = - texelSize;
  9989. const max = 1 + texelSize;
  9990. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  9991. const cubeFaces = 6;
  9992. const vertices = 6;
  9993. const positionSize = 3;
  9994. const uvSize = 2;
  9995. const faceIndexSize = 1;
  9996. const position = new Float32Array( positionSize * vertices * cubeFaces );
  9997. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  9998. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  9999. for ( let face = 0; face < cubeFaces; face ++ ) {
  10000. const x = ( face % 3 ) * 2 / 3 - 1;
  10001. const y = face > 2 ? 0 : - 1;
  10002. const coordinates = [
  10003. x, y, 0,
  10004. x + 2 / 3, y, 0,
  10005. x + 2 / 3, y + 1, 0,
  10006. x, y, 0,
  10007. x + 2 / 3, y + 1, 0,
  10008. x, y + 1, 0
  10009. ];
  10010. position.set( coordinates, positionSize * vertices * face );
  10011. uv.set( uv1, uvSize * vertices * face );
  10012. const fill = [ face, face, face, face, face, face ];
  10013. faceIndex.set( fill, faceIndexSize * vertices * face );
  10014. }
  10015. const planes = new BufferGeometry();
  10016. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  10017. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  10018. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  10019. lodPlanes.push( planes );
  10020. if ( lod > LOD_MIN ) {
  10021. lod --;
  10022. }
  10023. }
  10024. return { lodPlanes, sizeLods, sigmas };
  10025. }
  10026. function _createRenderTarget( width, height, params ) {
  10027. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  10028. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  10029. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  10030. cubeUVRenderTarget.scissorTest = true;
  10031. return cubeUVRenderTarget;
  10032. }
  10033. function _setViewport( target, x, y, width, height ) {
  10034. target.viewport.set( x, y, width, height );
  10035. target.scissor.set( x, y, width, height );
  10036. }
  10037. function _getBlurShader( lodMax, width, height ) {
  10038. const weights = new Float32Array( MAX_SAMPLES );
  10039. const poleAxis = new Vector3( 0, 1, 0 );
  10040. const shaderMaterial = new ShaderMaterial( {
  10041. name: 'SphericalGaussianBlur',
  10042. defines: {
  10043. 'n': MAX_SAMPLES,
  10044. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  10045. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  10046. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  10047. },
  10048. uniforms: {
  10049. 'envMap': { value: null },
  10050. 'samples': { value: 1 },
  10051. 'weights': { value: weights },
  10052. 'latitudinal': { value: false },
  10053. 'dTheta': { value: 0 },
  10054. 'mipInt': { value: 0 },
  10055. 'poleAxis': { value: poleAxis }
  10056. },
  10057. vertexShader: _getCommonVertexShader(),
  10058. fragmentShader: /* glsl */`
  10059. precision mediump float;
  10060. precision mediump int;
  10061. varying vec3 vOutputDirection;
  10062. uniform sampler2D envMap;
  10063. uniform int samples;
  10064. uniform float weights[ n ];
  10065. uniform bool latitudinal;
  10066. uniform float dTheta;
  10067. uniform float mipInt;
  10068. uniform vec3 poleAxis;
  10069. #define ENVMAP_TYPE_CUBE_UV
  10070. #include <cube_uv_reflection_fragment>
  10071. vec3 getSample( float theta, vec3 axis ) {
  10072. float cosTheta = cos( theta );
  10073. // Rodrigues' axis-angle rotation
  10074. vec3 sampleDirection = vOutputDirection * cosTheta
  10075. + cross( axis, vOutputDirection ) * sin( theta )
  10076. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  10077. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  10078. }
  10079. void main() {
  10080. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  10081. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  10082. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  10083. }
  10084. axis = normalize( axis );
  10085. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  10086. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  10087. for ( int i = 1; i < n; i++ ) {
  10088. if ( i >= samples ) {
  10089. break;
  10090. }
  10091. float theta = dTheta * float( i );
  10092. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  10093. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  10094. }
  10095. }
  10096. `,
  10097. blending: NoBlending,
  10098. depthTest: false,
  10099. depthWrite: false
  10100. } );
  10101. return shaderMaterial;
  10102. }
  10103. function _getEquirectMaterial() {
  10104. return new ShaderMaterial( {
  10105. name: 'EquirectangularToCubeUV',
  10106. uniforms: {
  10107. 'envMap': { value: null }
  10108. },
  10109. vertexShader: _getCommonVertexShader(),
  10110. fragmentShader: /* glsl */`
  10111. precision mediump float;
  10112. precision mediump int;
  10113. varying vec3 vOutputDirection;
  10114. uniform sampler2D envMap;
  10115. #include <common>
  10116. void main() {
  10117. vec3 outputDirection = normalize( vOutputDirection );
  10118. vec2 uv = equirectUv( outputDirection );
  10119. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  10120. }
  10121. `,
  10122. blending: NoBlending,
  10123. depthTest: false,
  10124. depthWrite: false
  10125. } );
  10126. }
  10127. function _getCubemapMaterial() {
  10128. return new ShaderMaterial( {
  10129. name: 'CubemapToCubeUV',
  10130. uniforms: {
  10131. 'envMap': { value: null },
  10132. 'flipEnvMap': { value: - 1 }
  10133. },
  10134. vertexShader: _getCommonVertexShader(),
  10135. fragmentShader: /* glsl */`
  10136. precision mediump float;
  10137. precision mediump int;
  10138. uniform float flipEnvMap;
  10139. varying vec3 vOutputDirection;
  10140. uniform samplerCube envMap;
  10141. void main() {
  10142. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  10143. }
  10144. `,
  10145. blending: NoBlending,
  10146. depthTest: false,
  10147. depthWrite: false
  10148. } );
  10149. }
  10150. function _getCommonVertexShader() {
  10151. return /* glsl */`
  10152. precision mediump float;
  10153. precision mediump int;
  10154. attribute float faceIndex;
  10155. varying vec3 vOutputDirection;
  10156. // RH coordinate system; PMREM face-indexing convention
  10157. vec3 getDirection( vec2 uv, float face ) {
  10158. uv = 2.0 * uv - 1.0;
  10159. vec3 direction = vec3( uv, 1.0 );
  10160. if ( face == 0.0 ) {
  10161. direction = direction.zyx; // ( 1, v, u ) pos x
  10162. } else if ( face == 1.0 ) {
  10163. direction = direction.xzy;
  10164. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  10165. } else if ( face == 2.0 ) {
  10166. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  10167. } else if ( face == 3.0 ) {
  10168. direction = direction.zyx;
  10169. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  10170. } else if ( face == 4.0 ) {
  10171. direction = direction.xzy;
  10172. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  10173. } else if ( face == 5.0 ) {
  10174. direction.z *= -1.0; // ( u, v, -1 ) neg z
  10175. }
  10176. return direction;
  10177. }
  10178. void main() {
  10179. vOutputDirection = getDirection( uv, faceIndex );
  10180. gl_Position = vec4( position, 1.0 );
  10181. }
  10182. `;
  10183. }
  10184. function WebGLCubeUVMaps( renderer ) {
  10185. let cubeUVmaps = new WeakMap();
  10186. let pmremGenerator = null;
  10187. function get( texture ) {
  10188. if ( texture && texture.isTexture ) {
  10189. const mapping = texture.mapping;
  10190. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  10191. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  10192. // equirect/cube map to cubeUV conversion
  10193. if ( isEquirectMap || isCubeMap ) {
  10194. if ( texture.isRenderTargetTexture && texture.needsPMREMUpdate === true ) {
  10195. texture.needsPMREMUpdate = false;
  10196. let renderTarget = cubeUVmaps.get( texture );
  10197. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  10198. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  10199. cubeUVmaps.set( texture, renderTarget );
  10200. return renderTarget.texture;
  10201. } else {
  10202. if ( cubeUVmaps.has( texture ) ) {
  10203. return cubeUVmaps.get( texture ).texture;
  10204. } else {
  10205. const image = texture.image;
  10206. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  10207. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  10208. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  10209. cubeUVmaps.set( texture, renderTarget );
  10210. texture.addEventListener( 'dispose', onTextureDispose );
  10211. return renderTarget.texture;
  10212. } else {
  10213. // image not yet ready. try the conversion next frame
  10214. return null;
  10215. }
  10216. }
  10217. }
  10218. }
  10219. }
  10220. return texture;
  10221. }
  10222. function isCubeTextureComplete( image ) {
  10223. let count = 0;
  10224. const length = 6;
  10225. for ( let i = 0; i < length; i ++ ) {
  10226. if ( image[ i ] !== undefined ) count ++;
  10227. }
  10228. return count === length;
  10229. }
  10230. function onTextureDispose( event ) {
  10231. const texture = event.target;
  10232. texture.removeEventListener( 'dispose', onTextureDispose );
  10233. const cubemapUV = cubeUVmaps.get( texture );
  10234. if ( cubemapUV !== undefined ) {
  10235. cubeUVmaps.delete( texture );
  10236. cubemapUV.dispose();
  10237. }
  10238. }
  10239. function dispose() {
  10240. cubeUVmaps = new WeakMap();
  10241. if ( pmremGenerator !== null ) {
  10242. pmremGenerator.dispose();
  10243. pmremGenerator = null;
  10244. }
  10245. }
  10246. return {
  10247. get: get,
  10248. dispose: dispose
  10249. };
  10250. }
  10251. function WebGLExtensions( gl ) {
  10252. const extensions = {};
  10253. function getExtension( name ) {
  10254. if ( extensions[ name ] !== undefined ) {
  10255. return extensions[ name ];
  10256. }
  10257. let extension;
  10258. switch ( name ) {
  10259. case 'WEBGL_depth_texture':
  10260. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  10261. break;
  10262. case 'EXT_texture_filter_anisotropic':
  10263. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  10264. break;
  10265. case 'WEBGL_compressed_texture_s3tc':
  10266. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  10267. break;
  10268. case 'WEBGL_compressed_texture_pvrtc':
  10269. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  10270. break;
  10271. default:
  10272. extension = gl.getExtension( name );
  10273. }
  10274. extensions[ name ] = extension;
  10275. return extension;
  10276. }
  10277. return {
  10278. has: function ( name ) {
  10279. return getExtension( name ) !== null;
  10280. },
  10281. init: function ( capabilities ) {
  10282. if ( capabilities.isWebGL2 ) {
  10283. getExtension( 'EXT_color_buffer_float' );
  10284. } else {
  10285. getExtension( 'WEBGL_depth_texture' );
  10286. getExtension( 'OES_texture_float' );
  10287. getExtension( 'OES_texture_half_float' );
  10288. getExtension( 'OES_texture_half_float_linear' );
  10289. getExtension( 'OES_standard_derivatives' );
  10290. getExtension( 'OES_element_index_uint' );
  10291. getExtension( 'OES_vertex_array_object' );
  10292. getExtension( 'ANGLE_instanced_arrays' );
  10293. }
  10294. getExtension( 'OES_texture_float_linear' );
  10295. getExtension( 'EXT_color_buffer_half_float' );
  10296. getExtension( 'WEBGL_multisampled_render_to_texture' );
  10297. },
  10298. get: function ( name ) {
  10299. const extension = getExtension( name );
  10300. if ( extension === null ) {
  10301. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  10302. }
  10303. return extension;
  10304. }
  10305. };
  10306. }
  10307. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  10308. const geometries = {};
  10309. const wireframeAttributes = new WeakMap();
  10310. function onGeometryDispose( event ) {
  10311. const geometry = event.target;
  10312. if ( geometry.index !== null ) {
  10313. attributes.remove( geometry.index );
  10314. }
  10315. for ( const name in geometry.attributes ) {
  10316. attributes.remove( geometry.attributes[ name ] );
  10317. }
  10318. for ( const name in geometry.morphAttributes ) {
  10319. const array = geometry.morphAttributes[ name ];
  10320. for ( let i = 0, l = array.length; i < l; i ++ ) {
  10321. attributes.remove( array[ i ] );
  10322. }
  10323. }
  10324. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10325. delete geometries[ geometry.id ];
  10326. const attribute = wireframeAttributes.get( geometry );
  10327. if ( attribute ) {
  10328. attributes.remove( attribute );
  10329. wireframeAttributes.delete( geometry );
  10330. }
  10331. bindingStates.releaseStatesOfGeometry( geometry );
  10332. if ( geometry.isInstancedBufferGeometry === true ) {
  10333. delete geometry._maxInstanceCount;
  10334. }
  10335. //
  10336. info.memory.geometries --;
  10337. }
  10338. function get( object, geometry ) {
  10339. if ( geometries[ geometry.id ] === true ) return geometry;
  10340. geometry.addEventListener( 'dispose', onGeometryDispose );
  10341. geometries[ geometry.id ] = true;
  10342. info.memory.geometries ++;
  10343. return geometry;
  10344. }
  10345. function update( geometry ) {
  10346. const geometryAttributes = geometry.attributes;
  10347. // Updating index buffer in VAO now. See WebGLBindingStates.
  10348. for ( const name in geometryAttributes ) {
  10349. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  10350. }
  10351. // morph targets
  10352. const morphAttributes = geometry.morphAttributes;
  10353. for ( const name in morphAttributes ) {
  10354. const array = morphAttributes[ name ];
  10355. for ( let i = 0, l = array.length; i < l; i ++ ) {
  10356. attributes.update( array[ i ], gl.ARRAY_BUFFER );
  10357. }
  10358. }
  10359. }
  10360. function updateWireframeAttribute( geometry ) {
  10361. const indices = [];
  10362. const geometryIndex = geometry.index;
  10363. const geometryPosition = geometry.attributes.position;
  10364. let version = 0;
  10365. if ( geometryIndex !== null ) {
  10366. const array = geometryIndex.array;
  10367. version = geometryIndex.version;
  10368. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  10369. const a = array[ i + 0 ];
  10370. const b = array[ i + 1 ];
  10371. const c = array[ i + 2 ];
  10372. indices.push( a, b, b, c, c, a );
  10373. }
  10374. } else {
  10375. const array = geometryPosition.array;
  10376. version = geometryPosition.version;
  10377. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10378. const a = i + 0;
  10379. const b = i + 1;
  10380. const c = i + 2;
  10381. indices.push( a, b, b, c, c, a );
  10382. }
  10383. }
  10384. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  10385. attribute.version = version;
  10386. // Updating index buffer in VAO now. See WebGLBindingStates
  10387. //
  10388. const previousAttribute = wireframeAttributes.get( geometry );
  10389. if ( previousAttribute ) attributes.remove( previousAttribute );
  10390. //
  10391. wireframeAttributes.set( geometry, attribute );
  10392. }
  10393. function getWireframeAttribute( geometry ) {
  10394. const currentAttribute = wireframeAttributes.get( geometry );
  10395. if ( currentAttribute ) {
  10396. const geometryIndex = geometry.index;
  10397. if ( geometryIndex !== null ) {
  10398. // if the attribute is obsolete, create a new one
  10399. if ( currentAttribute.version < geometryIndex.version ) {
  10400. updateWireframeAttribute( geometry );
  10401. }
  10402. }
  10403. } else {
  10404. updateWireframeAttribute( geometry );
  10405. }
  10406. return wireframeAttributes.get( geometry );
  10407. }
  10408. return {
  10409. get: get,
  10410. update: update,
  10411. getWireframeAttribute: getWireframeAttribute
  10412. };
  10413. }
  10414. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  10415. const isWebGL2 = capabilities.isWebGL2;
  10416. let mode;
  10417. function setMode( value ) {
  10418. mode = value;
  10419. }
  10420. let type, bytesPerElement;
  10421. function setIndex( value ) {
  10422. type = value.type;
  10423. bytesPerElement = value.bytesPerElement;
  10424. }
  10425. function render( start, count ) {
  10426. gl.drawElements( mode, count, type, start * bytesPerElement );
  10427. info.update( count, mode, 1 );
  10428. }
  10429. function renderInstances( start, count, primcount ) {
  10430. if ( primcount === 0 ) return;
  10431. let extension, methodName;
  10432. if ( isWebGL2 ) {
  10433. extension = gl;
  10434. methodName = 'drawElementsInstanced';
  10435. } else {
  10436. extension = extensions.get( 'ANGLE_instanced_arrays' );
  10437. methodName = 'drawElementsInstancedANGLE';
  10438. if ( extension === null ) {
  10439. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  10440. return;
  10441. }
  10442. }
  10443. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  10444. info.update( count, mode, primcount );
  10445. }
  10446. //
  10447. this.setMode = setMode;
  10448. this.setIndex = setIndex;
  10449. this.render = render;
  10450. this.renderInstances = renderInstances;
  10451. }
  10452. function WebGLInfo( gl ) {
  10453. const memory = {
  10454. geometries: 0,
  10455. textures: 0
  10456. };
  10457. const render = {
  10458. frame: 0,
  10459. calls: 0,
  10460. triangles: 0,
  10461. points: 0,
  10462. lines: 0
  10463. };
  10464. function update( count, mode, instanceCount ) {
  10465. render.calls ++;
  10466. switch ( mode ) {
  10467. case gl.TRIANGLES:
  10468. render.triangles += instanceCount * ( count / 3 );
  10469. break;
  10470. case gl.LINES:
  10471. render.lines += instanceCount * ( count / 2 );
  10472. break;
  10473. case gl.LINE_STRIP:
  10474. render.lines += instanceCount * ( count - 1 );
  10475. break;
  10476. case gl.LINE_LOOP:
  10477. render.lines += instanceCount * count;
  10478. break;
  10479. case gl.POINTS:
  10480. render.points += instanceCount * count;
  10481. break;
  10482. default:
  10483. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  10484. break;
  10485. }
  10486. }
  10487. function reset() {
  10488. render.calls = 0;
  10489. render.triangles = 0;
  10490. render.points = 0;
  10491. render.lines = 0;
  10492. }
  10493. return {
  10494. memory: memory,
  10495. render: render,
  10496. programs: null,
  10497. autoReset: true,
  10498. reset: reset,
  10499. update: update
  10500. };
  10501. }
  10502. function numericalSort( a, b ) {
  10503. return a[ 0 ] - b[ 0 ];
  10504. }
  10505. function absNumericalSort( a, b ) {
  10506. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  10507. }
  10508. function WebGLMorphtargets( gl, capabilities, textures ) {
  10509. const influencesList = {};
  10510. const morphInfluences = new Float32Array( 8 );
  10511. const morphTextures = new WeakMap();
  10512. const morph = new Vector4();
  10513. const workInfluences = [];
  10514. for ( let i = 0; i < 8; i ++ ) {
  10515. workInfluences[ i ] = [ i, 0 ];
  10516. }
  10517. function update( object, geometry, program ) {
  10518. const objectInfluences = object.morphTargetInfluences;
  10519. if ( capabilities.isWebGL2 === true ) {
  10520. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10521. // into an array of data textures. Each layer represents a single morph target.
  10522. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10523. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10524. let entry = morphTextures.get( geometry );
  10525. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10526. if ( entry !== undefined ) entry.texture.dispose();
  10527. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10528. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10529. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10530. const morphTargets = geometry.morphAttributes.position || [];
  10531. const morphNormals = geometry.morphAttributes.normal || [];
  10532. const morphColors = geometry.morphAttributes.color || [];
  10533. let vertexDataCount = 0;
  10534. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10535. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10536. if ( hasMorphColors === true ) vertexDataCount = 3;
  10537. let width = geometry.attributes.position.count * vertexDataCount;
  10538. let height = 1;
  10539. if ( width > capabilities.maxTextureSize ) {
  10540. height = Math.ceil( width / capabilities.maxTextureSize );
  10541. width = capabilities.maxTextureSize;
  10542. }
  10543. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10544. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10545. texture.type = FloatType;
  10546. texture.needsUpdate = true;
  10547. // fill buffer
  10548. const vertexDataStride = vertexDataCount * 4;
  10549. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10550. const morphTarget = morphTargets[ i ];
  10551. const morphNormal = morphNormals[ i ];
  10552. const morphColor = morphColors[ i ];
  10553. const offset = width * height * 4 * i;
  10554. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10555. const stride = j * vertexDataStride;
  10556. if ( hasMorphPosition === true ) {
  10557. morph.fromBufferAttribute( morphTarget, j );
  10558. buffer[ offset + stride + 0 ] = morph.x;
  10559. buffer[ offset + stride + 1 ] = morph.y;
  10560. buffer[ offset + stride + 2 ] = morph.z;
  10561. buffer[ offset + stride + 3 ] = 0;
  10562. }
  10563. if ( hasMorphNormals === true ) {
  10564. morph.fromBufferAttribute( morphNormal, j );
  10565. buffer[ offset + stride + 4 ] = morph.x;
  10566. buffer[ offset + stride + 5 ] = morph.y;
  10567. buffer[ offset + stride + 6 ] = morph.z;
  10568. buffer[ offset + stride + 7 ] = 0;
  10569. }
  10570. if ( hasMorphColors === true ) {
  10571. morph.fromBufferAttribute( morphColor, j );
  10572. buffer[ offset + stride + 8 ] = morph.x;
  10573. buffer[ offset + stride + 9 ] = morph.y;
  10574. buffer[ offset + stride + 10 ] = morph.z;
  10575. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  10576. }
  10577. }
  10578. }
  10579. entry = {
  10580. count: morphTargetsCount,
  10581. texture: texture,
  10582. size: new Vector2( width, height )
  10583. };
  10584. morphTextures.set( geometry, entry );
  10585. function disposeTexture() {
  10586. texture.dispose();
  10587. morphTextures.delete( geometry );
  10588. geometry.removeEventListener( 'dispose', disposeTexture );
  10589. }
  10590. geometry.addEventListener( 'dispose', disposeTexture );
  10591. }
  10592. //
  10593. let morphInfluencesSum = 0;
  10594. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10595. morphInfluencesSum += objectInfluences[ i ];
  10596. }
  10597. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10598. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10599. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  10600. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  10601. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  10602. } else {
  10603. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10604. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10605. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10606. let influences = influencesList[ geometry.id ];
  10607. if ( influences === undefined || influences.length !== length ) {
  10608. // initialise list
  10609. influences = [];
  10610. for ( let i = 0; i < length; i ++ ) {
  10611. influences[ i ] = [ i, 0 ];
  10612. }
  10613. influencesList[ geometry.id ] = influences;
  10614. }
  10615. // Collect influences
  10616. for ( let i = 0; i < length; i ++ ) {
  10617. const influence = influences[ i ];
  10618. influence[ 0 ] = i;
  10619. influence[ 1 ] = objectInfluences[ i ];
  10620. }
  10621. influences.sort( absNumericalSort );
  10622. for ( let i = 0; i < 8; i ++ ) {
  10623. if ( i < length && influences[ i ][ 1 ] ) {
  10624. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  10625. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  10626. } else {
  10627. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  10628. workInfluences[ i ][ 1 ] = 0;
  10629. }
  10630. }
  10631. workInfluences.sort( numericalSort );
  10632. const morphTargets = geometry.morphAttributes.position;
  10633. const morphNormals = geometry.morphAttributes.normal;
  10634. let morphInfluencesSum = 0;
  10635. for ( let i = 0; i < 8; i ++ ) {
  10636. const influence = workInfluences[ i ];
  10637. const index = influence[ 0 ];
  10638. const value = influence[ 1 ];
  10639. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  10640. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  10641. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  10642. }
  10643. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  10644. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  10645. }
  10646. morphInfluences[ i ] = value;
  10647. morphInfluencesSum += value;
  10648. } else {
  10649. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  10650. geometry.deleteAttribute( 'morphTarget' + i );
  10651. }
  10652. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  10653. geometry.deleteAttribute( 'morphNormal' + i );
  10654. }
  10655. morphInfluences[ i ] = 0;
  10656. }
  10657. }
  10658. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10659. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10660. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10661. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10662. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10663. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  10664. }
  10665. }
  10666. return {
  10667. update: update
  10668. };
  10669. }
  10670. function WebGLObjects( gl, geometries, attributes, info ) {
  10671. let updateMap = new WeakMap();
  10672. function update( object ) {
  10673. const frame = info.render.frame;
  10674. const geometry = object.geometry;
  10675. const buffergeometry = geometries.get( object, geometry );
  10676. // Update once per frame
  10677. if ( updateMap.get( buffergeometry ) !== frame ) {
  10678. geometries.update( buffergeometry );
  10679. updateMap.set( buffergeometry, frame );
  10680. }
  10681. if ( object.isInstancedMesh ) {
  10682. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10683. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10684. }
  10685. if ( updateMap.get( object ) !== frame ) {
  10686. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  10687. if ( object.instanceColor !== null ) {
  10688. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  10689. }
  10690. updateMap.set( object, frame );
  10691. }
  10692. }
  10693. if ( object.isSkinnedMesh ) {
  10694. const skeleton = object.skeleton;
  10695. if ( updateMap.get( skeleton ) !== frame ) {
  10696. skeleton.update();
  10697. updateMap.set( skeleton, frame );
  10698. }
  10699. }
  10700. return buffergeometry;
  10701. }
  10702. function dispose() {
  10703. updateMap = new WeakMap();
  10704. }
  10705. function onInstancedMeshDispose( event ) {
  10706. const instancedMesh = event.target;
  10707. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10708. attributes.remove( instancedMesh.instanceMatrix );
  10709. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10710. }
  10711. return {
  10712. update: update,
  10713. dispose: dispose
  10714. };
  10715. }
  10716. /**
  10717. * Uniforms of a program.
  10718. * Those form a tree structure with a special top-level container for the root,
  10719. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10720. *
  10721. *
  10722. * Properties of inner nodes including the top-level container:
  10723. *
  10724. * .seq - array of nested uniforms
  10725. * .map - nested uniforms by name
  10726. *
  10727. *
  10728. * Methods of all nodes except the top-level container:
  10729. *
  10730. * .setValue( gl, value, [textures] )
  10731. *
  10732. * uploads a uniform value(s)
  10733. * the 'textures' parameter is needed for sampler uniforms
  10734. *
  10735. *
  10736. * Static methods of the top-level container (textures factorizations):
  10737. *
  10738. * .upload( gl, seq, values, textures )
  10739. *
  10740. * sets uniforms in 'seq' to 'values[id].value'
  10741. *
  10742. * .seqWithValue( seq, values ) : filteredSeq
  10743. *
  10744. * filters 'seq' entries with corresponding entry in values
  10745. *
  10746. *
  10747. * Methods of the top-level container (textures factorizations):
  10748. *
  10749. * .setValue( gl, name, value, textures )
  10750. *
  10751. * sets uniform with name 'name' to 'value'
  10752. *
  10753. * .setOptional( gl, obj, prop )
  10754. *
  10755. * like .set for an optional property of the object
  10756. *
  10757. */
  10758. const emptyTexture = /*@__PURE__*/ new Texture();
  10759. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  10760. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  10761. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  10762. // --- Utilities ---
  10763. // Array Caches (provide typed arrays for temporary by size)
  10764. const arrayCacheF32 = [];
  10765. const arrayCacheI32 = [];
  10766. // Float32Array caches used for uploading Matrix uniforms
  10767. const mat4array = new Float32Array( 16 );
  10768. const mat3array = new Float32Array( 9 );
  10769. const mat2array = new Float32Array( 4 );
  10770. // Flattening for arrays of vectors and matrices
  10771. function flatten( array, nBlocks, blockSize ) {
  10772. const firstElem = array[ 0 ];
  10773. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10774. // unoptimized: ! isNaN( firstElem )
  10775. // see http://jacksondunstan.com/articles/983
  10776. const n = nBlocks * blockSize;
  10777. let r = arrayCacheF32[ n ];
  10778. if ( r === undefined ) {
  10779. r = new Float32Array( n );
  10780. arrayCacheF32[ n ] = r;
  10781. }
  10782. if ( nBlocks !== 0 ) {
  10783. firstElem.toArray( r, 0 );
  10784. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10785. offset += blockSize;
  10786. array[ i ].toArray( r, offset );
  10787. }
  10788. }
  10789. return r;
  10790. }
  10791. function arraysEqual( a, b ) {
  10792. if ( a.length !== b.length ) return false;
  10793. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10794. if ( a[ i ] !== b[ i ] ) return false;
  10795. }
  10796. return true;
  10797. }
  10798. function copyArray( a, b ) {
  10799. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10800. a[ i ] = b[ i ];
  10801. }
  10802. }
  10803. // Texture unit allocation
  10804. function allocTexUnits( textures, n ) {
  10805. let r = arrayCacheI32[ n ];
  10806. if ( r === undefined ) {
  10807. r = new Int32Array( n );
  10808. arrayCacheI32[ n ] = r;
  10809. }
  10810. for ( let i = 0; i !== n; ++ i ) {
  10811. r[ i ] = textures.allocateTextureUnit();
  10812. }
  10813. return r;
  10814. }
  10815. // --- Setters ---
  10816. // Note: Defining these methods externally, because they come in a bunch
  10817. // and this way their names minify.
  10818. // Single scalar
  10819. function setValueV1f( gl, v ) {
  10820. const cache = this.cache;
  10821. if ( cache[ 0 ] === v ) return;
  10822. gl.uniform1f( this.addr, v );
  10823. cache[ 0 ] = v;
  10824. }
  10825. // Single float vector (from flat array or THREE.VectorN)
  10826. function setValueV2f( gl, v ) {
  10827. const cache = this.cache;
  10828. if ( v.x !== undefined ) {
  10829. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10830. gl.uniform2f( this.addr, v.x, v.y );
  10831. cache[ 0 ] = v.x;
  10832. cache[ 1 ] = v.y;
  10833. }
  10834. } else {
  10835. if ( arraysEqual( cache, v ) ) return;
  10836. gl.uniform2fv( this.addr, v );
  10837. copyArray( cache, v );
  10838. }
  10839. }
  10840. function setValueV3f( gl, v ) {
  10841. const cache = this.cache;
  10842. if ( v.x !== undefined ) {
  10843. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10844. gl.uniform3f( this.addr, v.x, v.y, v.z );
  10845. cache[ 0 ] = v.x;
  10846. cache[ 1 ] = v.y;
  10847. cache[ 2 ] = v.z;
  10848. }
  10849. } else if ( v.r !== undefined ) {
  10850. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  10851. gl.uniform3f( this.addr, v.r, v.g, v.b );
  10852. cache[ 0 ] = v.r;
  10853. cache[ 1 ] = v.g;
  10854. cache[ 2 ] = v.b;
  10855. }
  10856. } else {
  10857. if ( arraysEqual( cache, v ) ) return;
  10858. gl.uniform3fv( this.addr, v );
  10859. copyArray( cache, v );
  10860. }
  10861. }
  10862. function setValueV4f( gl, v ) {
  10863. const cache = this.cache;
  10864. if ( v.x !== undefined ) {
  10865. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10866. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  10867. cache[ 0 ] = v.x;
  10868. cache[ 1 ] = v.y;
  10869. cache[ 2 ] = v.z;
  10870. cache[ 3 ] = v.w;
  10871. }
  10872. } else {
  10873. if ( arraysEqual( cache, v ) ) return;
  10874. gl.uniform4fv( this.addr, v );
  10875. copyArray( cache, v );
  10876. }
  10877. }
  10878. // Single matrix (from flat array or THREE.MatrixN)
  10879. function setValueM2( gl, v ) {
  10880. const cache = this.cache;
  10881. const elements = v.elements;
  10882. if ( elements === undefined ) {
  10883. if ( arraysEqual( cache, v ) ) return;
  10884. gl.uniformMatrix2fv( this.addr, false, v );
  10885. copyArray( cache, v );
  10886. } else {
  10887. if ( arraysEqual( cache, elements ) ) return;
  10888. mat2array.set( elements );
  10889. gl.uniformMatrix2fv( this.addr, false, mat2array );
  10890. copyArray( cache, elements );
  10891. }
  10892. }
  10893. function setValueM3( gl, v ) {
  10894. const cache = this.cache;
  10895. const elements = v.elements;
  10896. if ( elements === undefined ) {
  10897. if ( arraysEqual( cache, v ) ) return;
  10898. gl.uniformMatrix3fv( this.addr, false, v );
  10899. copyArray( cache, v );
  10900. } else {
  10901. if ( arraysEqual( cache, elements ) ) return;
  10902. mat3array.set( elements );
  10903. gl.uniformMatrix3fv( this.addr, false, mat3array );
  10904. copyArray( cache, elements );
  10905. }
  10906. }
  10907. function setValueM4( gl, v ) {
  10908. const cache = this.cache;
  10909. const elements = v.elements;
  10910. if ( elements === undefined ) {
  10911. if ( arraysEqual( cache, v ) ) return;
  10912. gl.uniformMatrix4fv( this.addr, false, v );
  10913. copyArray( cache, v );
  10914. } else {
  10915. if ( arraysEqual( cache, elements ) ) return;
  10916. mat4array.set( elements );
  10917. gl.uniformMatrix4fv( this.addr, false, mat4array );
  10918. copyArray( cache, elements );
  10919. }
  10920. }
  10921. // Single integer / boolean
  10922. function setValueV1i( gl, v ) {
  10923. const cache = this.cache;
  10924. if ( cache[ 0 ] === v ) return;
  10925. gl.uniform1i( this.addr, v );
  10926. cache[ 0 ] = v;
  10927. }
  10928. // Single integer / boolean vector (from flat array or THREE.VectorN)
  10929. function setValueV2i( gl, v ) {
  10930. const cache = this.cache;
  10931. if ( v.x !== undefined ) {
  10932. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10933. gl.uniform2i( this.addr, v.x, v.y );
  10934. cache[ 0 ] = v.x;
  10935. cache[ 1 ] = v.y;
  10936. }
  10937. } else {
  10938. if ( arraysEqual( cache, v ) ) return;
  10939. gl.uniform2iv( this.addr, v );
  10940. copyArray( cache, v );
  10941. }
  10942. }
  10943. function setValueV3i( gl, v ) {
  10944. const cache = this.cache;
  10945. if ( v.x !== undefined ) {
  10946. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10947. gl.uniform3i( this.addr, v.x, v.y, v.z );
  10948. cache[ 0 ] = v.x;
  10949. cache[ 1 ] = v.y;
  10950. cache[ 2 ] = v.z;
  10951. }
  10952. } else {
  10953. if ( arraysEqual( cache, v ) ) return;
  10954. gl.uniform3iv( this.addr, v );
  10955. copyArray( cache, v );
  10956. }
  10957. }
  10958. function setValueV4i( gl, v ) {
  10959. const cache = this.cache;
  10960. if ( v.x !== undefined ) {
  10961. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10962. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  10963. cache[ 0 ] = v.x;
  10964. cache[ 1 ] = v.y;
  10965. cache[ 2 ] = v.z;
  10966. cache[ 3 ] = v.w;
  10967. }
  10968. } else {
  10969. if ( arraysEqual( cache, v ) ) return;
  10970. gl.uniform4iv( this.addr, v );
  10971. copyArray( cache, v );
  10972. }
  10973. }
  10974. // Single unsigned integer
  10975. function setValueV1ui( gl, v ) {
  10976. const cache = this.cache;
  10977. if ( cache[ 0 ] === v ) return;
  10978. gl.uniform1ui( this.addr, v );
  10979. cache[ 0 ] = v;
  10980. }
  10981. // Single unsigned integer vector (from flat array or THREE.VectorN)
  10982. function setValueV2ui( gl, v ) {
  10983. const cache = this.cache;
  10984. if ( v.x !== undefined ) {
  10985. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10986. gl.uniform2ui( this.addr, v.x, v.y );
  10987. cache[ 0 ] = v.x;
  10988. cache[ 1 ] = v.y;
  10989. }
  10990. } else {
  10991. if ( arraysEqual( cache, v ) ) return;
  10992. gl.uniform2uiv( this.addr, v );
  10993. copyArray( cache, v );
  10994. }
  10995. }
  10996. function setValueV3ui( gl, v ) {
  10997. const cache = this.cache;
  10998. if ( v.x !== undefined ) {
  10999. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  11000. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  11001. cache[ 0 ] = v.x;
  11002. cache[ 1 ] = v.y;
  11003. cache[ 2 ] = v.z;
  11004. }
  11005. } else {
  11006. if ( arraysEqual( cache, v ) ) return;
  11007. gl.uniform3uiv( this.addr, v );
  11008. copyArray( cache, v );
  11009. }
  11010. }
  11011. function setValueV4ui( gl, v ) {
  11012. const cache = this.cache;
  11013. if ( v.x !== undefined ) {
  11014. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  11015. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  11016. cache[ 0 ] = v.x;
  11017. cache[ 1 ] = v.y;
  11018. cache[ 2 ] = v.z;
  11019. cache[ 3 ] = v.w;
  11020. }
  11021. } else {
  11022. if ( arraysEqual( cache, v ) ) return;
  11023. gl.uniform4uiv( this.addr, v );
  11024. copyArray( cache, v );
  11025. }
  11026. }
  11027. // Single texture (2D / Cube)
  11028. function setValueT1( gl, v, textures ) {
  11029. const cache = this.cache;
  11030. const unit = textures.allocateTextureUnit();
  11031. if ( cache[ 0 ] !== unit ) {
  11032. gl.uniform1i( this.addr, unit );
  11033. cache[ 0 ] = unit;
  11034. }
  11035. textures.setTexture2D( v || emptyTexture, unit );
  11036. }
  11037. function setValueT3D1( gl, v, textures ) {
  11038. const cache = this.cache;
  11039. const unit = textures.allocateTextureUnit();
  11040. if ( cache[ 0 ] !== unit ) {
  11041. gl.uniform1i( this.addr, unit );
  11042. cache[ 0 ] = unit;
  11043. }
  11044. textures.setTexture3D( v || empty3dTexture, unit );
  11045. }
  11046. function setValueT6( gl, v, textures ) {
  11047. const cache = this.cache;
  11048. const unit = textures.allocateTextureUnit();
  11049. if ( cache[ 0 ] !== unit ) {
  11050. gl.uniform1i( this.addr, unit );
  11051. cache[ 0 ] = unit;
  11052. }
  11053. textures.setTextureCube( v || emptyCubeTexture, unit );
  11054. }
  11055. function setValueT2DArray1( gl, v, textures ) {
  11056. const cache = this.cache;
  11057. const unit = textures.allocateTextureUnit();
  11058. if ( cache[ 0 ] !== unit ) {
  11059. gl.uniform1i( this.addr, unit );
  11060. cache[ 0 ] = unit;
  11061. }
  11062. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  11063. }
  11064. // Helper to pick the right setter for the singular case
  11065. function getSingularSetter( type ) {
  11066. switch ( type ) {
  11067. case 0x1406: return setValueV1f; // FLOAT
  11068. case 0x8b50: return setValueV2f; // _VEC2
  11069. case 0x8b51: return setValueV3f; // _VEC3
  11070. case 0x8b52: return setValueV4f; // _VEC4
  11071. case 0x8b5a: return setValueM2; // _MAT2
  11072. case 0x8b5b: return setValueM3; // _MAT3
  11073. case 0x8b5c: return setValueM4; // _MAT4
  11074. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  11075. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  11076. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  11077. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  11078. case 0x1405: return setValueV1ui; // UINT
  11079. case 0x8dc6: return setValueV2ui; // _VEC2
  11080. case 0x8dc7: return setValueV3ui; // _VEC3
  11081. case 0x8dc8: return setValueV4ui; // _VEC4
  11082. case 0x8b5e: // SAMPLER_2D
  11083. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11084. case 0x8dca: // INT_SAMPLER_2D
  11085. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11086. case 0x8b62: // SAMPLER_2D_SHADOW
  11087. return setValueT1;
  11088. case 0x8b5f: // SAMPLER_3D
  11089. case 0x8dcb: // INT_SAMPLER_3D
  11090. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  11091. return setValueT3D1;
  11092. case 0x8b60: // SAMPLER_CUBE
  11093. case 0x8dcc: // INT_SAMPLER_CUBE
  11094. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11095. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  11096. return setValueT6;
  11097. case 0x8dc1: // SAMPLER_2D_ARRAY
  11098. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11099. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11100. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  11101. return setValueT2DArray1;
  11102. }
  11103. }
  11104. // Array of scalars
  11105. function setValueV1fArray( gl, v ) {
  11106. gl.uniform1fv( this.addr, v );
  11107. }
  11108. // Array of vectors (from flat array or array of THREE.VectorN)
  11109. function setValueV2fArray( gl, v ) {
  11110. const data = flatten( v, this.size, 2 );
  11111. gl.uniform2fv( this.addr, data );
  11112. }
  11113. function setValueV3fArray( gl, v ) {
  11114. const data = flatten( v, this.size, 3 );
  11115. gl.uniform3fv( this.addr, data );
  11116. }
  11117. function setValueV4fArray( gl, v ) {
  11118. const data = flatten( v, this.size, 4 );
  11119. gl.uniform4fv( this.addr, data );
  11120. }
  11121. // Array of matrices (from flat array or array of THREE.MatrixN)
  11122. function setValueM2Array( gl, v ) {
  11123. const data = flatten( v, this.size, 4 );
  11124. gl.uniformMatrix2fv( this.addr, false, data );
  11125. }
  11126. function setValueM3Array( gl, v ) {
  11127. const data = flatten( v, this.size, 9 );
  11128. gl.uniformMatrix3fv( this.addr, false, data );
  11129. }
  11130. function setValueM4Array( gl, v ) {
  11131. const data = flatten( v, this.size, 16 );
  11132. gl.uniformMatrix4fv( this.addr, false, data );
  11133. }
  11134. // Array of integer / boolean
  11135. function setValueV1iArray( gl, v ) {
  11136. gl.uniform1iv( this.addr, v );
  11137. }
  11138. // Array of integer / boolean vectors (from flat array)
  11139. function setValueV2iArray( gl, v ) {
  11140. gl.uniform2iv( this.addr, v );
  11141. }
  11142. function setValueV3iArray( gl, v ) {
  11143. gl.uniform3iv( this.addr, v );
  11144. }
  11145. function setValueV4iArray( gl, v ) {
  11146. gl.uniform4iv( this.addr, v );
  11147. }
  11148. // Array of unsigned integer
  11149. function setValueV1uiArray( gl, v ) {
  11150. gl.uniform1uiv( this.addr, v );
  11151. }
  11152. // Array of unsigned integer vectors (from flat array)
  11153. function setValueV2uiArray( gl, v ) {
  11154. gl.uniform2uiv( this.addr, v );
  11155. }
  11156. function setValueV3uiArray( gl, v ) {
  11157. gl.uniform3uiv( this.addr, v );
  11158. }
  11159. function setValueV4uiArray( gl, v ) {
  11160. gl.uniform4uiv( this.addr, v );
  11161. }
  11162. // Array of textures (2D / 3D / Cube / 2DArray)
  11163. function setValueT1Array( gl, v, textures ) {
  11164. const cache = this.cache;
  11165. const n = v.length;
  11166. const units = allocTexUnits( textures, n );
  11167. if ( ! arraysEqual( cache, units ) ) {
  11168. gl.uniform1iv( this.addr, units );
  11169. copyArray( cache, units );
  11170. }
  11171. for ( let i = 0; i !== n; ++ i ) {
  11172. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  11173. }
  11174. }
  11175. function setValueT3DArray( gl, v, textures ) {
  11176. const cache = this.cache;
  11177. const n = v.length;
  11178. const units = allocTexUnits( textures, n );
  11179. if ( ! arraysEqual( cache, units ) ) {
  11180. gl.uniform1iv( this.addr, units );
  11181. copyArray( cache, units );
  11182. }
  11183. for ( let i = 0; i !== n; ++ i ) {
  11184. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  11185. }
  11186. }
  11187. function setValueT6Array( gl, v, textures ) {
  11188. const cache = this.cache;
  11189. const n = v.length;
  11190. const units = allocTexUnits( textures, n );
  11191. if ( ! arraysEqual( cache, units ) ) {
  11192. gl.uniform1iv( this.addr, units );
  11193. copyArray( cache, units );
  11194. }
  11195. for ( let i = 0; i !== n; ++ i ) {
  11196. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  11197. }
  11198. }
  11199. function setValueT2DArrayArray( gl, v, textures ) {
  11200. const cache = this.cache;
  11201. const n = v.length;
  11202. const units = allocTexUnits( textures, n );
  11203. if ( ! arraysEqual( cache, units ) ) {
  11204. gl.uniform1iv( this.addr, units );
  11205. copyArray( cache, units );
  11206. }
  11207. for ( let i = 0; i !== n; ++ i ) {
  11208. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  11209. }
  11210. }
  11211. // Helper to pick the right setter for a pure (bottom-level) array
  11212. function getPureArraySetter( type ) {
  11213. switch ( type ) {
  11214. case 0x1406: return setValueV1fArray; // FLOAT
  11215. case 0x8b50: return setValueV2fArray; // _VEC2
  11216. case 0x8b51: return setValueV3fArray; // _VEC3
  11217. case 0x8b52: return setValueV4fArray; // _VEC4
  11218. case 0x8b5a: return setValueM2Array; // _MAT2
  11219. case 0x8b5b: return setValueM3Array; // _MAT3
  11220. case 0x8b5c: return setValueM4Array; // _MAT4
  11221. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  11222. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  11223. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  11224. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  11225. case 0x1405: return setValueV1uiArray; // UINT
  11226. case 0x8dc6: return setValueV2uiArray; // _VEC2
  11227. case 0x8dc7: return setValueV3uiArray; // _VEC3
  11228. case 0x8dc8: return setValueV4uiArray; // _VEC4
  11229. case 0x8b5e: // SAMPLER_2D
  11230. case 0x8d66: // SAMPLER_EXTERNAL_OES
  11231. case 0x8dca: // INT_SAMPLER_2D
  11232. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11233. case 0x8b62: // SAMPLER_2D_SHADOW
  11234. return setValueT1Array;
  11235. case 0x8b5f: // SAMPLER_3D
  11236. case 0x8dcb: // INT_SAMPLER_3D
  11237. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  11238. return setValueT3DArray;
  11239. case 0x8b60: // SAMPLER_CUBE
  11240. case 0x8dcc: // INT_SAMPLER_CUBE
  11241. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11242. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  11243. return setValueT6Array;
  11244. case 0x8dc1: // SAMPLER_2D_ARRAY
  11245. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11246. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11247. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  11248. return setValueT2DArrayArray;
  11249. }
  11250. }
  11251. // --- Uniform Classes ---
  11252. class SingleUniform {
  11253. constructor( id, activeInfo, addr ) {
  11254. this.id = id;
  11255. this.addr = addr;
  11256. this.cache = [];
  11257. this.setValue = getSingularSetter( activeInfo.type );
  11258. // this.path = activeInfo.name; // DEBUG
  11259. }
  11260. }
  11261. class PureArrayUniform {
  11262. constructor( id, activeInfo, addr ) {
  11263. this.id = id;
  11264. this.addr = addr;
  11265. this.cache = [];
  11266. this.size = activeInfo.size;
  11267. this.setValue = getPureArraySetter( activeInfo.type );
  11268. // this.path = activeInfo.name; // DEBUG
  11269. }
  11270. }
  11271. class StructuredUniform {
  11272. constructor( id ) {
  11273. this.id = id;
  11274. this.seq = [];
  11275. this.map = {};
  11276. }
  11277. setValue( gl, value, textures ) {
  11278. const seq = this.seq;
  11279. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11280. const u = seq[ i ];
  11281. u.setValue( gl, value[ u.id ], textures );
  11282. }
  11283. }
  11284. }
  11285. // --- Top-level ---
  11286. // Parser - builds up the property tree from the path strings
  11287. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  11288. // extracts
  11289. // - the identifier (member name or array index)
  11290. // - followed by an optional right bracket (found when array index)
  11291. // - followed by an optional left bracket or dot (type of subscript)
  11292. //
  11293. // Note: These portions can be read in a non-overlapping fashion and
  11294. // allow straightforward parsing of the hierarchy that WebGL encodes
  11295. // in the uniform names.
  11296. function addUniform( container, uniformObject ) {
  11297. container.seq.push( uniformObject );
  11298. container.map[ uniformObject.id ] = uniformObject;
  11299. }
  11300. function parseUniform( activeInfo, addr, container ) {
  11301. const path = activeInfo.name,
  11302. pathLength = path.length;
  11303. // reset RegExp object, because of the early exit of a previous run
  11304. RePathPart.lastIndex = 0;
  11305. while ( true ) {
  11306. const match = RePathPart.exec( path ),
  11307. matchEnd = RePathPart.lastIndex;
  11308. let id = match[ 1 ];
  11309. const idIsIndex = match[ 2 ] === ']',
  11310. subscript = match[ 3 ];
  11311. if ( idIsIndex ) id = id | 0; // convert to integer
  11312. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  11313. // bare name or "pure" bottom-level array "[0]" suffix
  11314. addUniform( container, subscript === undefined ?
  11315. new SingleUniform( id, activeInfo, addr ) :
  11316. new PureArrayUniform( id, activeInfo, addr ) );
  11317. break;
  11318. } else {
  11319. // step into inner node / create it in case it doesn't exist
  11320. const map = container.map;
  11321. let next = map[ id ];
  11322. if ( next === undefined ) {
  11323. next = new StructuredUniform( id );
  11324. addUniform( container, next );
  11325. }
  11326. container = next;
  11327. }
  11328. }
  11329. }
  11330. // Root Container
  11331. class WebGLUniforms {
  11332. constructor( gl, program ) {
  11333. this.seq = [];
  11334. this.map = {};
  11335. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  11336. for ( let i = 0; i < n; ++ i ) {
  11337. const info = gl.getActiveUniform( program, i ),
  11338. addr = gl.getUniformLocation( program, info.name );
  11339. parseUniform( info, addr, this );
  11340. }
  11341. }
  11342. setValue( gl, name, value, textures ) {
  11343. const u = this.map[ name ];
  11344. if ( u !== undefined ) u.setValue( gl, value, textures );
  11345. }
  11346. setOptional( gl, object, name ) {
  11347. const v = object[ name ];
  11348. if ( v !== undefined ) this.setValue( gl, name, v );
  11349. }
  11350. static upload( gl, seq, values, textures ) {
  11351. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11352. const u = seq[ i ],
  11353. v = values[ u.id ];
  11354. if ( v.needsUpdate !== false ) {
  11355. // note: always updating when .needsUpdate is undefined
  11356. u.setValue( gl, v.value, textures );
  11357. }
  11358. }
  11359. }
  11360. static seqWithValue( seq, values ) {
  11361. const r = [];
  11362. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11363. const u = seq[ i ];
  11364. if ( u.id in values ) r.push( u );
  11365. }
  11366. return r;
  11367. }
  11368. }
  11369. function WebGLShader( gl, type, string ) {
  11370. const shader = gl.createShader( type );
  11371. gl.shaderSource( shader, string );
  11372. gl.compileShader( shader );
  11373. return shader;
  11374. }
  11375. let programIdCount = 0;
  11376. function handleSource( string, errorLine ) {
  11377. const lines = string.split( '\n' );
  11378. const lines2 = [];
  11379. const from = Math.max( errorLine - 6, 0 );
  11380. const to = Math.min( errorLine + 6, lines.length );
  11381. for ( let i = from; i < to; i ++ ) {
  11382. const line = i + 1;
  11383. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  11384. }
  11385. return lines2.join( '\n' );
  11386. }
  11387. function getEncodingComponents( colorSpace ) {
  11388. switch ( colorSpace ) {
  11389. case LinearSRGBColorSpace:
  11390. return [ 'Linear', '( value )' ];
  11391. case SRGBColorSpace:
  11392. return [ 'sRGB', '( value )' ];
  11393. default:
  11394. console.warn( 'THREE.WebGLProgram: Unsupported color space:', colorSpace );
  11395. return [ 'Linear', '( value )' ];
  11396. }
  11397. }
  11398. function getShaderErrors( gl, shader, type ) {
  11399. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  11400. const errors = gl.getShaderInfoLog( shader ).trim();
  11401. if ( status && errors === '' ) return '';
  11402. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  11403. if ( errorMatches ) {
  11404. // --enable-privileged-webgl-extension
  11405. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11406. const errorLine = parseInt( errorMatches[ 1 ] );
  11407. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  11408. } else {
  11409. return errors;
  11410. }
  11411. }
  11412. function getTexelEncodingFunction( functionName, colorSpace ) {
  11413. const components = getEncodingComponents( colorSpace );
  11414. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  11415. }
  11416. function getToneMappingFunction( functionName, toneMapping ) {
  11417. let toneMappingName;
  11418. switch ( toneMapping ) {
  11419. case LinearToneMapping:
  11420. toneMappingName = 'Linear';
  11421. break;
  11422. case ReinhardToneMapping:
  11423. toneMappingName = 'Reinhard';
  11424. break;
  11425. case CineonToneMapping:
  11426. toneMappingName = 'OptimizedCineon';
  11427. break;
  11428. case ACESFilmicToneMapping:
  11429. toneMappingName = 'ACESFilmic';
  11430. break;
  11431. case CustomToneMapping:
  11432. toneMappingName = 'Custom';
  11433. break;
  11434. default:
  11435. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  11436. toneMappingName = 'Linear';
  11437. }
  11438. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11439. }
  11440. function generateExtensions( parameters ) {
  11441. const chunks = [
  11442. ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.normalMapTangentSpace || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  11443. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  11444. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  11445. ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  11446. ];
  11447. return chunks.filter( filterEmptyLine ).join( '\n' );
  11448. }
  11449. function generateDefines( defines ) {
  11450. const chunks = [];
  11451. for ( const name in defines ) {
  11452. const value = defines[ name ];
  11453. if ( value === false ) continue;
  11454. chunks.push( '#define ' + name + ' ' + value );
  11455. }
  11456. return chunks.join( '\n' );
  11457. }
  11458. function fetchAttributeLocations( gl, program ) {
  11459. const attributes = {};
  11460. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  11461. for ( let i = 0; i < n; i ++ ) {
  11462. const info = gl.getActiveAttrib( program, i );
  11463. const name = info.name;
  11464. let locationSize = 1;
  11465. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  11466. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  11467. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  11468. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11469. attributes[ name ] = {
  11470. type: info.type,
  11471. location: gl.getAttribLocation( program, name ),
  11472. locationSize: locationSize
  11473. };
  11474. }
  11475. return attributes;
  11476. }
  11477. function filterEmptyLine( string ) {
  11478. return string !== '';
  11479. }
  11480. function replaceLightNums( string, parameters ) {
  11481. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  11482. return string
  11483. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  11484. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  11485. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  11486. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  11487. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  11488. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  11489. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  11490. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  11491. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  11492. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  11493. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  11494. }
  11495. function replaceClippingPlaneNums( string, parameters ) {
  11496. return string
  11497. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  11498. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  11499. }
  11500. // Resolve Includes
  11501. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11502. function resolveIncludes( string ) {
  11503. return string.replace( includePattern, includeReplacer );
  11504. }
  11505. const shaderChunkMap = new Map( [
  11506. [ 'encodings_fragment', 'colorspace_fragment' ], // @deprecated, r154
  11507. [ 'encodings_pars_fragment', 'colorspace_pars_fragment' ], // @deprecated, r154
  11508. [ 'output_fragment', 'opaque_fragment' ], // @deprecated, r154
  11509. ] );
  11510. function includeReplacer( match, include ) {
  11511. let string = ShaderChunk[ include ];
  11512. if ( string === undefined ) {
  11513. const newInclude = shaderChunkMap.get( include );
  11514. if ( newInclude !== undefined ) {
  11515. string = ShaderChunk[ newInclude ];
  11516. console.warn( 'THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude );
  11517. } else {
  11518. throw new Error( 'Can not resolve #include <' + include + '>' );
  11519. }
  11520. }
  11521. return resolveIncludes( string );
  11522. }
  11523. // Unroll Loops
  11524. 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;
  11525. function unrollLoops( string ) {
  11526. return string.replace( unrollLoopPattern, loopReplacer );
  11527. }
  11528. function loopReplacer( match, start, end, snippet ) {
  11529. let string = '';
  11530. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  11531. string += snippet
  11532. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  11533. .replace( /UNROLLED_LOOP_INDEX/g, i );
  11534. }
  11535. return string;
  11536. }
  11537. //
  11538. function generatePrecision( parameters ) {
  11539. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11540. if ( parameters.precision === 'highp' ) {
  11541. precisionstring += '\n#define HIGH_PRECISION';
  11542. } else if ( parameters.precision === 'mediump' ) {
  11543. precisionstring += '\n#define MEDIUM_PRECISION';
  11544. } else if ( parameters.precision === 'lowp' ) {
  11545. precisionstring += '\n#define LOW_PRECISION';
  11546. }
  11547. return precisionstring;
  11548. }
  11549. function generateShadowMapTypeDefine( parameters ) {
  11550. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11551. if ( parameters.shadowMapType === PCFShadowMap ) {
  11552. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11553. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  11554. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11555. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  11556. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11557. }
  11558. return shadowMapTypeDefine;
  11559. }
  11560. function generateEnvMapTypeDefine( parameters ) {
  11561. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11562. if ( parameters.envMap ) {
  11563. switch ( parameters.envMapMode ) {
  11564. case CubeReflectionMapping:
  11565. case CubeRefractionMapping:
  11566. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11567. break;
  11568. case CubeUVReflectionMapping:
  11569. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11570. break;
  11571. }
  11572. }
  11573. return envMapTypeDefine;
  11574. }
  11575. function generateEnvMapModeDefine( parameters ) {
  11576. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11577. if ( parameters.envMap ) {
  11578. switch ( parameters.envMapMode ) {
  11579. case CubeRefractionMapping:
  11580. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11581. break;
  11582. }
  11583. }
  11584. return envMapModeDefine;
  11585. }
  11586. function generateEnvMapBlendingDefine( parameters ) {
  11587. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11588. if ( parameters.envMap ) {
  11589. switch ( parameters.combine ) {
  11590. case MultiplyOperation:
  11591. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11592. break;
  11593. case MixOperation:
  11594. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11595. break;
  11596. case AddOperation:
  11597. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11598. break;
  11599. }
  11600. }
  11601. return envMapBlendingDefine;
  11602. }
  11603. function generateCubeUVSize( parameters ) {
  11604. const imageHeight = parameters.envMapCubeUVHeight;
  11605. if ( imageHeight === null ) return null;
  11606. const maxMip = Math.log2( imageHeight ) - 2;
  11607. const texelHeight = 1.0 / imageHeight;
  11608. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  11609. return { texelWidth, texelHeight, maxMip };
  11610. }
  11611. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  11612. // TODO Send this event to Three.js DevTools
  11613. // console.log( 'WebGLProgram', cacheKey );
  11614. const gl = renderer.getContext();
  11615. const defines = parameters.defines;
  11616. let vertexShader = parameters.vertexShader;
  11617. let fragmentShader = parameters.fragmentShader;
  11618. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  11619. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  11620. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  11621. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  11622. const envMapCubeUVSize = generateCubeUVSize( parameters );
  11623. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  11624. const customDefines = generateDefines( defines );
  11625. const program = gl.createProgram();
  11626. let prefixVertex, prefixFragment;
  11627. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11628. if ( parameters.isRawShaderMaterial ) {
  11629. prefixVertex = [
  11630. '#define SHADER_TYPE ' + parameters.shaderType,
  11631. '#define SHADER_NAME ' + parameters.shaderName,
  11632. customDefines
  11633. ].filter( filterEmptyLine ).join( '\n' );
  11634. if ( prefixVertex.length > 0 ) {
  11635. prefixVertex += '\n';
  11636. }
  11637. prefixFragment = [
  11638. customExtensions,
  11639. '#define SHADER_TYPE ' + parameters.shaderType,
  11640. '#define SHADER_NAME ' + parameters.shaderName,
  11641. customDefines
  11642. ].filter( filterEmptyLine ).join( '\n' );
  11643. if ( prefixFragment.length > 0 ) {
  11644. prefixFragment += '\n';
  11645. }
  11646. } else {
  11647. prefixVertex = [
  11648. generatePrecision( parameters ),
  11649. '#define SHADER_TYPE ' + parameters.shaderType,
  11650. '#define SHADER_NAME ' + parameters.shaderName,
  11651. customDefines,
  11652. parameters.instancing ? '#define USE_INSTANCING' : '',
  11653. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  11654. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  11655. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  11656. parameters.map ? '#define USE_MAP' : '',
  11657. parameters.envMap ? '#define USE_ENVMAP' : '',
  11658. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11659. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11660. parameters.aoMap ? '#define USE_AOMAP' : '',
  11661. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11662. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11663. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  11664. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  11665. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  11666. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11667. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  11668. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11669. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11670. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11671. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11672. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11673. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11674. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  11675. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  11676. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11677. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11678. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11679. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  11680. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11681. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11682. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11683. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  11684. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  11685. //
  11686. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  11687. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  11688. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  11689. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  11690. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  11691. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  11692. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  11693. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  11694. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  11695. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  11696. parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '',
  11697. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  11698. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  11699. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  11700. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  11701. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  11702. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  11703. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  11704. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  11705. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  11706. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  11707. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  11708. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  11709. //
  11710. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  11711. parameters.vertexColors ? '#define USE_COLOR' : '',
  11712. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11713. parameters.vertexUv1s ? '#define USE_UV1' : '',
  11714. parameters.vertexUv2s ? '#define USE_UV2' : '',
  11715. parameters.vertexUv3s ? '#define USE_UV3' : '',
  11716. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  11717. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11718. parameters.skinning ? '#define USE_SKINNING' : '',
  11719. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  11720. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  11721. ( parameters.morphColors && parameters.isWebGL2 ) ? '#define USE_MORPHCOLORS' : '',
  11722. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE' : '',
  11723. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  11724. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  11725. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11726. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11727. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11728. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11729. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  11730. parameters.useLegacyLights ? '#define LEGACY_LIGHTS' : '',
  11731. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11732. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11733. 'uniform mat4 modelMatrix;',
  11734. 'uniform mat4 modelViewMatrix;',
  11735. 'uniform mat4 projectionMatrix;',
  11736. 'uniform mat4 viewMatrix;',
  11737. 'uniform mat3 normalMatrix;',
  11738. 'uniform vec3 cameraPosition;',
  11739. 'uniform bool isOrthographic;',
  11740. '#ifdef USE_INSTANCING',
  11741. ' attribute mat4 instanceMatrix;',
  11742. '#endif',
  11743. '#ifdef USE_INSTANCING_COLOR',
  11744. ' attribute vec3 instanceColor;',
  11745. '#endif',
  11746. 'attribute vec3 position;',
  11747. 'attribute vec3 normal;',
  11748. 'attribute vec2 uv;',
  11749. '#ifdef USE_UV1',
  11750. ' attribute vec2 uv1;',
  11751. '#endif',
  11752. '#ifdef USE_UV2',
  11753. ' attribute vec2 uv2;',
  11754. '#endif',
  11755. '#ifdef USE_UV3',
  11756. ' attribute vec2 uv3;',
  11757. '#endif',
  11758. '#ifdef USE_TANGENT',
  11759. ' attribute vec4 tangent;',
  11760. '#endif',
  11761. '#if defined( USE_COLOR_ALPHA )',
  11762. ' attribute vec4 color;',
  11763. '#elif defined( USE_COLOR )',
  11764. ' attribute vec3 color;',
  11765. '#endif',
  11766. '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )',
  11767. ' attribute vec3 morphTarget0;',
  11768. ' attribute vec3 morphTarget1;',
  11769. ' attribute vec3 morphTarget2;',
  11770. ' attribute vec3 morphTarget3;',
  11771. ' #ifdef USE_MORPHNORMALS',
  11772. ' attribute vec3 morphNormal0;',
  11773. ' attribute vec3 morphNormal1;',
  11774. ' attribute vec3 morphNormal2;',
  11775. ' attribute vec3 morphNormal3;',
  11776. ' #else',
  11777. ' attribute vec3 morphTarget4;',
  11778. ' attribute vec3 morphTarget5;',
  11779. ' attribute vec3 morphTarget6;',
  11780. ' attribute vec3 morphTarget7;',
  11781. ' #endif',
  11782. '#endif',
  11783. '#ifdef USE_SKINNING',
  11784. ' attribute vec4 skinIndex;',
  11785. ' attribute vec4 skinWeight;',
  11786. '#endif',
  11787. '\n'
  11788. ].filter( filterEmptyLine ).join( '\n' );
  11789. prefixFragment = [
  11790. customExtensions,
  11791. generatePrecision( parameters ),
  11792. '#define SHADER_TYPE ' + parameters.shaderType,
  11793. '#define SHADER_NAME ' + parameters.shaderName,
  11794. customDefines,
  11795. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  11796. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  11797. parameters.map ? '#define USE_MAP' : '',
  11798. parameters.matcap ? '#define USE_MATCAP' : '',
  11799. parameters.envMap ? '#define USE_ENVMAP' : '',
  11800. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  11801. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11802. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  11803. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  11804. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  11805. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  11806. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11807. parameters.aoMap ? '#define USE_AOMAP' : '',
  11808. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11809. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11810. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  11811. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  11812. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11813. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  11814. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  11815. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  11816. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11817. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11818. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11819. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  11820. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11821. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11822. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11823. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  11824. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  11825. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11826. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11827. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11828. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  11829. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  11830. parameters.sheen ? '#define USE_SHEEN' : '',
  11831. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  11832. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  11833. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11834. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11835. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11836. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  11837. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  11838. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11839. parameters.vertexUv1s ? '#define USE_UV1' : '',
  11840. parameters.vertexUv2s ? '#define USE_UV2' : '',
  11841. parameters.vertexUv3s ? '#define USE_UV3' : '',
  11842. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  11843. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  11844. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11845. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11846. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11847. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11848. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11849. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  11850. parameters.useLegacyLights ? '#define LEGACY_LIGHTS' : '',
  11851. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11852. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11853. 'uniform mat4 viewMatrix;',
  11854. 'uniform vec3 cameraPosition;',
  11855. 'uniform bool isOrthographic;',
  11856. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  11857. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  11858. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  11859. parameters.dithering ? '#define DITHERING' : '',
  11860. parameters.opaque ? '#define OPAQUE' : '',
  11861. ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  11862. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),
  11863. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  11864. '\n'
  11865. ].filter( filterEmptyLine ).join( '\n' );
  11866. }
  11867. vertexShader = resolveIncludes( vertexShader );
  11868. vertexShader = replaceLightNums( vertexShader, parameters );
  11869. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  11870. fragmentShader = resolveIncludes( fragmentShader );
  11871. fragmentShader = replaceLightNums( fragmentShader, parameters );
  11872. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  11873. vertexShader = unrollLoops( vertexShader );
  11874. fragmentShader = unrollLoops( fragmentShader );
  11875. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  11876. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11877. versionString = '#version 300 es\n';
  11878. prefixVertex = [
  11879. 'precision mediump sampler2DArray;',
  11880. '#define attribute in',
  11881. '#define varying out',
  11882. '#define texture2D texture'
  11883. ].join( '\n' ) + '\n' + prefixVertex;
  11884. prefixFragment = [
  11885. '#define varying in',
  11886. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  11887. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  11888. '#define gl_FragDepthEXT gl_FragDepth',
  11889. '#define texture2D texture',
  11890. '#define textureCube texture',
  11891. '#define texture2DProj textureProj',
  11892. '#define texture2DLodEXT textureLod',
  11893. '#define texture2DProjLodEXT textureProjLod',
  11894. '#define textureCubeLodEXT textureLod',
  11895. '#define texture2DGradEXT textureGrad',
  11896. '#define texture2DProjGradEXT textureProjGrad',
  11897. '#define textureCubeGradEXT textureGrad'
  11898. ].join( '\n' ) + '\n' + prefixFragment;
  11899. }
  11900. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11901. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  11902. // console.log( '*VERTEX*', vertexGlsl );
  11903. // console.log( '*FRAGMENT*', fragmentGlsl );
  11904. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  11905. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  11906. gl.attachShader( program, glVertexShader );
  11907. gl.attachShader( program, glFragmentShader );
  11908. // Force a particular attribute to index 0.
  11909. if ( parameters.index0AttributeName !== undefined ) {
  11910. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  11911. } else if ( parameters.morphTargets === true ) {
  11912. // programs with morphTargets displace position out of attribute 0
  11913. gl.bindAttribLocation( program, 0, 'position' );
  11914. }
  11915. gl.linkProgram( program );
  11916. // check for link errors
  11917. if ( renderer.debug.checkShaderErrors ) {
  11918. const programLog = gl.getProgramInfoLog( program ).trim();
  11919. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  11920. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  11921. let runnable = true;
  11922. let haveDiagnostics = true;
  11923. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  11924. runnable = false;
  11925. if ( typeof renderer.debug.onShaderError === 'function' ) {
  11926. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  11927. } else {
  11928. // default error reporting
  11929. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  11930. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  11931. console.error(
  11932. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  11933. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  11934. 'Program Info Log: ' + programLog + '\n' +
  11935. vertexErrors + '\n' +
  11936. fragmentErrors
  11937. );
  11938. }
  11939. } else if ( programLog !== '' ) {
  11940. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  11941. } else if ( vertexLog === '' || fragmentLog === '' ) {
  11942. haveDiagnostics = false;
  11943. }
  11944. if ( haveDiagnostics ) {
  11945. this.diagnostics = {
  11946. runnable: runnable,
  11947. programLog: programLog,
  11948. vertexShader: {
  11949. log: vertexLog,
  11950. prefix: prefixVertex
  11951. },
  11952. fragmentShader: {
  11953. log: fragmentLog,
  11954. prefix: prefixFragment
  11955. }
  11956. };
  11957. }
  11958. }
  11959. // Clean up
  11960. // Crashes in iOS9 and iOS10. #18402
  11961. // gl.detachShader( program, glVertexShader );
  11962. // gl.detachShader( program, glFragmentShader );
  11963. gl.deleteShader( glVertexShader );
  11964. gl.deleteShader( glFragmentShader );
  11965. // set up caching for uniform locations
  11966. let cachedUniforms;
  11967. this.getUniforms = function () {
  11968. if ( cachedUniforms === undefined ) {
  11969. cachedUniforms = new WebGLUniforms( gl, program );
  11970. }
  11971. return cachedUniforms;
  11972. };
  11973. // set up caching for attribute locations
  11974. let cachedAttributes;
  11975. this.getAttributes = function () {
  11976. if ( cachedAttributes === undefined ) {
  11977. cachedAttributes = fetchAttributeLocations( gl, program );
  11978. }
  11979. return cachedAttributes;
  11980. };
  11981. // free resource
  11982. this.destroy = function () {
  11983. bindingStates.releaseStatesOfProgram( this );
  11984. gl.deleteProgram( program );
  11985. this.program = undefined;
  11986. };
  11987. //
  11988. this.type = parameters.shaderType;
  11989. this.name = parameters.shaderName;
  11990. this.id = programIdCount ++;
  11991. this.cacheKey = cacheKey;
  11992. this.usedTimes = 1;
  11993. this.program = program;
  11994. this.vertexShader = glVertexShader;
  11995. this.fragmentShader = glFragmentShader;
  11996. return this;
  11997. }
  11998. let _id = 0;
  11999. class WebGLShaderCache {
  12000. constructor() {
  12001. this.shaderCache = new Map();
  12002. this.materialCache = new Map();
  12003. }
  12004. update( material ) {
  12005. const vertexShader = material.vertexShader;
  12006. const fragmentShader = material.fragmentShader;
  12007. const vertexShaderStage = this._getShaderStage( vertexShader );
  12008. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  12009. const materialShaders = this._getShaderCacheForMaterial( material );
  12010. if ( materialShaders.has( vertexShaderStage ) === false ) {
  12011. materialShaders.add( vertexShaderStage );
  12012. vertexShaderStage.usedTimes ++;
  12013. }
  12014. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  12015. materialShaders.add( fragmentShaderStage );
  12016. fragmentShaderStage.usedTimes ++;
  12017. }
  12018. return this;
  12019. }
  12020. remove( material ) {
  12021. const materialShaders = this.materialCache.get( material );
  12022. for ( const shaderStage of materialShaders ) {
  12023. shaderStage.usedTimes --;
  12024. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  12025. }
  12026. this.materialCache.delete( material );
  12027. return this;
  12028. }
  12029. getVertexShaderID( material ) {
  12030. return this._getShaderStage( material.vertexShader ).id;
  12031. }
  12032. getFragmentShaderID( material ) {
  12033. return this._getShaderStage( material.fragmentShader ).id;
  12034. }
  12035. dispose() {
  12036. this.shaderCache.clear();
  12037. this.materialCache.clear();
  12038. }
  12039. _getShaderCacheForMaterial( material ) {
  12040. const cache = this.materialCache;
  12041. let set = cache.get( material );
  12042. if ( set === undefined ) {
  12043. set = new Set();
  12044. cache.set( material, set );
  12045. }
  12046. return set;
  12047. }
  12048. _getShaderStage( code ) {
  12049. const cache = this.shaderCache;
  12050. let stage = cache.get( code );
  12051. if ( stage === undefined ) {
  12052. stage = new WebGLShaderStage( code );
  12053. cache.set( code, stage );
  12054. }
  12055. return stage;
  12056. }
  12057. }
  12058. class WebGLShaderStage {
  12059. constructor( code ) {
  12060. this.id = _id ++;
  12061. this.code = code;
  12062. this.usedTimes = 0;
  12063. }
  12064. }
  12065. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  12066. const _programLayers = new Layers();
  12067. const _customShaders = new WebGLShaderCache();
  12068. const programs = [];
  12069. const IS_WEBGL2 = capabilities.isWebGL2;
  12070. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  12071. const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures;
  12072. let precision = capabilities.precision;
  12073. const shaderIDs = {
  12074. MeshDepthMaterial: 'depth',
  12075. MeshDistanceMaterial: 'distanceRGBA',
  12076. MeshNormalMaterial: 'normal',
  12077. MeshBasicMaterial: 'basic',
  12078. MeshLambertMaterial: 'lambert',
  12079. MeshPhongMaterial: 'phong',
  12080. MeshToonMaterial: 'toon',
  12081. MeshStandardMaterial: 'physical',
  12082. MeshPhysicalMaterial: 'physical',
  12083. MeshMatcapMaterial: 'matcap',
  12084. LineBasicMaterial: 'basic',
  12085. LineDashedMaterial: 'dashed',
  12086. PointsMaterial: 'points',
  12087. ShadowMaterial: 'shadow',
  12088. SpriteMaterial: 'sprite'
  12089. };
  12090. function getChannel( value ) {
  12091. if ( value === 0 ) return 'uv';
  12092. return `uv${ value }`;
  12093. }
  12094. function getParameters( material, lights, shadows, scene, object ) {
  12095. const fog = scene.fog;
  12096. const geometry = object.geometry;
  12097. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  12098. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  12099. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  12100. const shaderID = shaderIDs[ material.type ];
  12101. // heuristics to create shader parameters according to lights in the scene
  12102. // (not to blow over maxLights budget)
  12103. if ( material.precision !== null ) {
  12104. precision = capabilities.getMaxPrecision( material.precision );
  12105. if ( precision !== material.precision ) {
  12106. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  12107. }
  12108. }
  12109. //
  12110. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12111. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12112. let morphTextureStride = 0;
  12113. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  12114. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  12115. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  12116. //
  12117. let vertexShader, fragmentShader;
  12118. let customVertexShaderID, customFragmentShaderID;
  12119. if ( shaderID ) {
  12120. const shader = ShaderLib[ shaderID ];
  12121. vertexShader = shader.vertexShader;
  12122. fragmentShader = shader.fragmentShader;
  12123. } else {
  12124. vertexShader = material.vertexShader;
  12125. fragmentShader = material.fragmentShader;
  12126. _customShaders.update( material );
  12127. customVertexShaderID = _customShaders.getVertexShaderID( material );
  12128. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  12129. }
  12130. const currentRenderTarget = renderer.getRenderTarget();
  12131. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  12132. const HAS_MAP = !! material.map;
  12133. const HAS_MATCAP = !! material.matcap;
  12134. const HAS_ENVMAP = !! envMap;
  12135. const HAS_AOMAP = !! material.aoMap;
  12136. const HAS_LIGHTMAP = !! material.lightMap;
  12137. const HAS_BUMPMAP = !! material.bumpMap;
  12138. const HAS_NORMALMAP = !! material.normalMap;
  12139. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  12140. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  12141. const HAS_METALNESSMAP = !! material.metalnessMap;
  12142. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  12143. const HAS_ANISOTROPY = material.anisotropy > 0;
  12144. const HAS_CLEARCOAT = material.clearcoat > 0;
  12145. const HAS_IRIDESCENCE = material.iridescence > 0;
  12146. const HAS_SHEEN = material.sheen > 0;
  12147. const HAS_TRANSMISSION = material.transmission > 0;
  12148. const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap;
  12149. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  12150. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  12151. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  12152. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  12153. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  12154. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  12155. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  12156. const HAS_SPECULARMAP = !! material.specularMap;
  12157. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  12158. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  12159. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  12160. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  12161. const HAS_GRADIENTMAP = !! material.gradientMap;
  12162. const HAS_ALPHAMAP = !! material.alphaMap;
  12163. const HAS_ALPHATEST = material.alphaTest > 0;
  12164. const HAS_ALPHAHASH = !! material.alphaHash;
  12165. const HAS_EXTENSIONS = !! material.extensions;
  12166. const HAS_ATTRIBUTE_UV1 = !! geometry.attributes.uv1;
  12167. const HAS_ATTRIBUTE_UV2 = !! geometry.attributes.uv2;
  12168. const HAS_ATTRIBUTE_UV3 = !! geometry.attributes.uv3;
  12169. const parameters = {
  12170. isWebGL2: IS_WEBGL2,
  12171. shaderID: shaderID,
  12172. shaderType: material.type,
  12173. shaderName: material.name,
  12174. vertexShader: vertexShader,
  12175. fragmentShader: fragmentShader,
  12176. defines: material.defines,
  12177. customVertexShaderID: customVertexShaderID,
  12178. customFragmentShaderID: customFragmentShaderID,
  12179. isRawShaderMaterial: material.isRawShaderMaterial === true,
  12180. glslVersion: material.glslVersion,
  12181. precision: precision,
  12182. instancing: IS_INSTANCEDMESH,
  12183. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  12184. supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES,
  12185. outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),
  12186. map: HAS_MAP,
  12187. matcap: HAS_MATCAP,
  12188. envMap: HAS_ENVMAP,
  12189. envMapMode: HAS_ENVMAP && envMap.mapping,
  12190. envMapCubeUVHeight: envMapCubeUVHeight,
  12191. aoMap: HAS_AOMAP,
  12192. lightMap: HAS_LIGHTMAP,
  12193. bumpMap: HAS_BUMPMAP,
  12194. normalMap: HAS_NORMALMAP,
  12195. displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP,
  12196. emissiveMap: HAS_EMISSIVEMAP,
  12197. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  12198. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  12199. metalnessMap: HAS_METALNESSMAP,
  12200. roughnessMap: HAS_ROUGHNESSMAP,
  12201. anisotropy: HAS_ANISOTROPY,
  12202. anisotropyMap: HAS_ANISOTROPYMAP,
  12203. clearcoat: HAS_CLEARCOAT,
  12204. clearcoatMap: HAS_CLEARCOATMAP,
  12205. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  12206. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  12207. iridescence: HAS_IRIDESCENCE,
  12208. iridescenceMap: HAS_IRIDESCENCEMAP,
  12209. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  12210. sheen: HAS_SHEEN,
  12211. sheenColorMap: HAS_SHEEN_COLORMAP,
  12212. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  12213. specularMap: HAS_SPECULARMAP,
  12214. specularColorMap: HAS_SPECULAR_COLORMAP,
  12215. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  12216. transmission: HAS_TRANSMISSION,
  12217. transmissionMap: HAS_TRANSMISSIONMAP,
  12218. thicknessMap: HAS_THICKNESSMAP,
  12219. gradientMap: HAS_GRADIENTMAP,
  12220. opaque: material.transparent === false && material.blending === NormalBlending,
  12221. alphaMap: HAS_ALPHAMAP,
  12222. alphaTest: HAS_ALPHATEST,
  12223. alphaHash: HAS_ALPHAHASH,
  12224. combine: material.combine,
  12225. //
  12226. mapUv: HAS_MAP && getChannel( material.map.channel ),
  12227. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  12228. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  12229. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  12230. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  12231. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  12232. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  12233. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  12234. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  12235. anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ),
  12236. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  12237. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  12238. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  12239. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  12240. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  12241. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  12242. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  12243. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  12244. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  12245. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  12246. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  12247. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  12248. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  12249. //
  12250. vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ),
  12251. vertexColors: material.vertexColors,
  12252. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  12253. vertexUv1s: HAS_ATTRIBUTE_UV1,
  12254. vertexUv2s: HAS_ATTRIBUTE_UV2,
  12255. vertexUv3s: HAS_ATTRIBUTE_UV3,
  12256. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  12257. fog: !! fog,
  12258. useFog: material.fog === true,
  12259. fogExp2: ( fog && fog.isFogExp2 ),
  12260. flatShading: material.flatShading === true,
  12261. sizeAttenuation: material.sizeAttenuation === true,
  12262. logarithmicDepthBuffer: logarithmicDepthBuffer,
  12263. skinning: object.isSkinnedMesh === true,
  12264. morphTargets: geometry.morphAttributes.position !== undefined,
  12265. morphNormals: geometry.morphAttributes.normal !== undefined,
  12266. morphColors: geometry.morphAttributes.color !== undefined,
  12267. morphTargetsCount: morphTargetsCount,
  12268. morphTextureStride: morphTextureStride,
  12269. numDirLights: lights.directional.length,
  12270. numPointLights: lights.point.length,
  12271. numSpotLights: lights.spot.length,
  12272. numSpotLightMaps: lights.spotLightMap.length,
  12273. numRectAreaLights: lights.rectArea.length,
  12274. numHemiLights: lights.hemi.length,
  12275. numDirLightShadows: lights.directionalShadowMap.length,
  12276. numPointLightShadows: lights.pointShadowMap.length,
  12277. numSpotLightShadows: lights.spotShadowMap.length,
  12278. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  12279. numClippingPlanes: clipping.numPlanes,
  12280. numClipIntersection: clipping.numIntersection,
  12281. dithering: material.dithering,
  12282. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  12283. shadowMapType: renderer.shadowMap.type,
  12284. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  12285. useLegacyLights: renderer.useLegacyLights,
  12286. premultipliedAlpha: material.premultipliedAlpha,
  12287. doubleSided: material.side === DoubleSide,
  12288. flipSided: material.side === BackSide,
  12289. useDepthPacking: material.depthPacking >= 0,
  12290. depthPacking: material.depthPacking || 0,
  12291. index0AttributeName: material.index0AttributeName,
  12292. extensionDerivatives: HAS_EXTENSIONS && material.extensions.derivatives === true,
  12293. extensionFragDepth: HAS_EXTENSIONS && material.extensions.fragDepth === true,
  12294. extensionDrawBuffers: HAS_EXTENSIONS && material.extensions.drawBuffers === true,
  12295. extensionShaderTextureLOD: HAS_EXTENSIONS && material.extensions.shaderTextureLOD === true,
  12296. rendererExtensionFragDepth: IS_WEBGL2 || extensions.has( 'EXT_frag_depth' ),
  12297. rendererExtensionDrawBuffers: IS_WEBGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  12298. rendererExtensionShaderTextureLod: IS_WEBGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  12299. customProgramCacheKey: material.customProgramCacheKey()
  12300. };
  12301. return parameters;
  12302. }
  12303. function getProgramCacheKey( parameters ) {
  12304. const array = [];
  12305. if ( parameters.shaderID ) {
  12306. array.push( parameters.shaderID );
  12307. } else {
  12308. array.push( parameters.customVertexShaderID );
  12309. array.push( parameters.customFragmentShaderID );
  12310. }
  12311. if ( parameters.defines !== undefined ) {
  12312. for ( const name in parameters.defines ) {
  12313. array.push( name );
  12314. array.push( parameters.defines[ name ] );
  12315. }
  12316. }
  12317. if ( parameters.isRawShaderMaterial === false ) {
  12318. getProgramCacheKeyParameters( array, parameters );
  12319. getProgramCacheKeyBooleans( array, parameters );
  12320. array.push( renderer.outputColorSpace );
  12321. }
  12322. array.push( parameters.customProgramCacheKey );
  12323. return array.join();
  12324. }
  12325. function getProgramCacheKeyParameters( array, parameters ) {
  12326. array.push( parameters.precision );
  12327. array.push( parameters.outputColorSpace );
  12328. array.push( parameters.envMapMode );
  12329. array.push( parameters.envMapCubeUVHeight );
  12330. array.push( parameters.mapUv );
  12331. array.push( parameters.alphaMapUv );
  12332. array.push( parameters.lightMapUv );
  12333. array.push( parameters.aoMapUv );
  12334. array.push( parameters.bumpMapUv );
  12335. array.push( parameters.normalMapUv );
  12336. array.push( parameters.displacementMapUv );
  12337. array.push( parameters.emissiveMapUv );
  12338. array.push( parameters.metalnessMapUv );
  12339. array.push( parameters.roughnessMapUv );
  12340. array.push( parameters.anisotropyMapUv );
  12341. array.push( parameters.clearcoatMapUv );
  12342. array.push( parameters.clearcoatNormalMapUv );
  12343. array.push( parameters.clearcoatRoughnessMapUv );
  12344. array.push( parameters.iridescenceMapUv );
  12345. array.push( parameters.iridescenceThicknessMapUv );
  12346. array.push( parameters.sheenColorMapUv );
  12347. array.push( parameters.sheenRoughnessMapUv );
  12348. array.push( parameters.specularMapUv );
  12349. array.push( parameters.specularColorMapUv );
  12350. array.push( parameters.specularIntensityMapUv );
  12351. array.push( parameters.transmissionMapUv );
  12352. array.push( parameters.thicknessMapUv );
  12353. array.push( parameters.combine );
  12354. array.push( parameters.fogExp2 );
  12355. array.push( parameters.sizeAttenuation );
  12356. array.push( parameters.morphTargetsCount );
  12357. array.push( parameters.morphAttributeCount );
  12358. array.push( parameters.numDirLights );
  12359. array.push( parameters.numPointLights );
  12360. array.push( parameters.numSpotLights );
  12361. array.push( parameters.numSpotLightMaps );
  12362. array.push( parameters.numHemiLights );
  12363. array.push( parameters.numRectAreaLights );
  12364. array.push( parameters.numDirLightShadows );
  12365. array.push( parameters.numPointLightShadows );
  12366. array.push( parameters.numSpotLightShadows );
  12367. array.push( parameters.numSpotLightShadowsWithMaps );
  12368. array.push( parameters.shadowMapType );
  12369. array.push( parameters.toneMapping );
  12370. array.push( parameters.numClippingPlanes );
  12371. array.push( parameters.numClipIntersection );
  12372. array.push( parameters.depthPacking );
  12373. }
  12374. function getProgramCacheKeyBooleans( array, parameters ) {
  12375. _programLayers.disableAll();
  12376. if ( parameters.isWebGL2 )
  12377. _programLayers.enable( 0 );
  12378. if ( parameters.supportsVertexTextures )
  12379. _programLayers.enable( 1 );
  12380. if ( parameters.instancing )
  12381. _programLayers.enable( 2 );
  12382. if ( parameters.instancingColor )
  12383. _programLayers.enable( 3 );
  12384. if ( parameters.matcap )
  12385. _programLayers.enable( 4 );
  12386. if ( parameters.envMap )
  12387. _programLayers.enable( 5 );
  12388. if ( parameters.normalMapObjectSpace )
  12389. _programLayers.enable( 6 );
  12390. if ( parameters.normalMapTangentSpace )
  12391. _programLayers.enable( 7 );
  12392. if ( parameters.clearcoat )
  12393. _programLayers.enable( 8 );
  12394. if ( parameters.iridescence )
  12395. _programLayers.enable( 9 );
  12396. if ( parameters.alphaTest )
  12397. _programLayers.enable( 10 );
  12398. if ( parameters.vertexColors )
  12399. _programLayers.enable( 11 );
  12400. if ( parameters.vertexAlphas )
  12401. _programLayers.enable( 12 );
  12402. if ( parameters.vertexUv1s )
  12403. _programLayers.enable( 13 );
  12404. if ( parameters.vertexUv2s )
  12405. _programLayers.enable( 14 );
  12406. if ( parameters.vertexUv3s )
  12407. _programLayers.enable( 15 );
  12408. if ( parameters.vertexTangents )
  12409. _programLayers.enable( 16 );
  12410. if ( parameters.anisotropy )
  12411. _programLayers.enable( 17 );
  12412. array.push( _programLayers.mask );
  12413. _programLayers.disableAll();
  12414. if ( parameters.fog )
  12415. _programLayers.enable( 0 );
  12416. if ( parameters.useFog )
  12417. _programLayers.enable( 1 );
  12418. if ( parameters.flatShading )
  12419. _programLayers.enable( 2 );
  12420. if ( parameters.logarithmicDepthBuffer )
  12421. _programLayers.enable( 3 );
  12422. if ( parameters.skinning )
  12423. _programLayers.enable( 4 );
  12424. if ( parameters.morphTargets )
  12425. _programLayers.enable( 5 );
  12426. if ( parameters.morphNormals )
  12427. _programLayers.enable( 6 );
  12428. if ( parameters.morphColors )
  12429. _programLayers.enable( 7 );
  12430. if ( parameters.premultipliedAlpha )
  12431. _programLayers.enable( 8 );
  12432. if ( parameters.shadowMapEnabled )
  12433. _programLayers.enable( 9 );
  12434. if ( parameters.useLegacyLights )
  12435. _programLayers.enable( 10 );
  12436. if ( parameters.doubleSided )
  12437. _programLayers.enable( 11 );
  12438. if ( parameters.flipSided )
  12439. _programLayers.enable( 12 );
  12440. if ( parameters.useDepthPacking )
  12441. _programLayers.enable( 13 );
  12442. if ( parameters.dithering )
  12443. _programLayers.enable( 14 );
  12444. if ( parameters.transmission )
  12445. _programLayers.enable( 15 );
  12446. if ( parameters.sheen )
  12447. _programLayers.enable( 16 );
  12448. if ( parameters.opaque )
  12449. _programLayers.enable( 17 );
  12450. if ( parameters.pointsUvs )
  12451. _programLayers.enable( 18 );
  12452. array.push( _programLayers.mask );
  12453. }
  12454. function getUniforms( material ) {
  12455. const shaderID = shaderIDs[ material.type ];
  12456. let uniforms;
  12457. if ( shaderID ) {
  12458. const shader = ShaderLib[ shaderID ];
  12459. uniforms = UniformsUtils.clone( shader.uniforms );
  12460. } else {
  12461. uniforms = material.uniforms;
  12462. }
  12463. return uniforms;
  12464. }
  12465. function acquireProgram( parameters, cacheKey ) {
  12466. let program;
  12467. // Check if code has been already compiled
  12468. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  12469. const preexistingProgram = programs[ p ];
  12470. if ( preexistingProgram.cacheKey === cacheKey ) {
  12471. program = preexistingProgram;
  12472. ++ program.usedTimes;
  12473. break;
  12474. }
  12475. }
  12476. if ( program === undefined ) {
  12477. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  12478. programs.push( program );
  12479. }
  12480. return program;
  12481. }
  12482. function releaseProgram( program ) {
  12483. if ( -- program.usedTimes === 0 ) {
  12484. // Remove from unordered set
  12485. const i = programs.indexOf( program );
  12486. programs[ i ] = programs[ programs.length - 1 ];
  12487. programs.pop();
  12488. // Free WebGL resources
  12489. program.destroy();
  12490. }
  12491. }
  12492. function releaseShaderCache( material ) {
  12493. _customShaders.remove( material );
  12494. }
  12495. function dispose() {
  12496. _customShaders.dispose();
  12497. }
  12498. return {
  12499. getParameters: getParameters,
  12500. getProgramCacheKey: getProgramCacheKey,
  12501. getUniforms: getUniforms,
  12502. acquireProgram: acquireProgram,
  12503. releaseProgram: releaseProgram,
  12504. releaseShaderCache: releaseShaderCache,
  12505. // Exposed for resource monitoring & error feedback via renderer.info:
  12506. programs: programs,
  12507. dispose: dispose
  12508. };
  12509. }
  12510. function WebGLProperties() {
  12511. let properties = new WeakMap();
  12512. function get( object ) {
  12513. let map = properties.get( object );
  12514. if ( map === undefined ) {
  12515. map = {};
  12516. properties.set( object, map );
  12517. }
  12518. return map;
  12519. }
  12520. function remove( object ) {
  12521. properties.delete( object );
  12522. }
  12523. function update( object, key, value ) {
  12524. properties.get( object )[ key ] = value;
  12525. }
  12526. function dispose() {
  12527. properties = new WeakMap();
  12528. }
  12529. return {
  12530. get: get,
  12531. remove: remove,
  12532. update: update,
  12533. dispose: dispose
  12534. };
  12535. }
  12536. function painterSortStable( a, b ) {
  12537. if ( a.groupOrder !== b.groupOrder ) {
  12538. return a.groupOrder - b.groupOrder;
  12539. } else if ( a.renderOrder !== b.renderOrder ) {
  12540. return a.renderOrder - b.renderOrder;
  12541. } else if ( a.material.id !== b.material.id ) {
  12542. return a.material.id - b.material.id;
  12543. } else if ( a.z !== b.z ) {
  12544. return a.z - b.z;
  12545. } else {
  12546. return a.id - b.id;
  12547. }
  12548. }
  12549. function reversePainterSortStable( a, b ) {
  12550. if ( a.groupOrder !== b.groupOrder ) {
  12551. return a.groupOrder - b.groupOrder;
  12552. } else if ( a.renderOrder !== b.renderOrder ) {
  12553. return a.renderOrder - b.renderOrder;
  12554. } else if ( a.z !== b.z ) {
  12555. return b.z - a.z;
  12556. } else {
  12557. return a.id - b.id;
  12558. }
  12559. }
  12560. function WebGLRenderList() {
  12561. const renderItems = [];
  12562. let renderItemsIndex = 0;
  12563. const opaque = [];
  12564. const transmissive = [];
  12565. const transparent = [];
  12566. function init() {
  12567. renderItemsIndex = 0;
  12568. opaque.length = 0;
  12569. transmissive.length = 0;
  12570. transparent.length = 0;
  12571. }
  12572. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  12573. let renderItem = renderItems[ renderItemsIndex ];
  12574. if ( renderItem === undefined ) {
  12575. renderItem = {
  12576. id: object.id,
  12577. object: object,
  12578. geometry: geometry,
  12579. material: material,
  12580. groupOrder: groupOrder,
  12581. renderOrder: object.renderOrder,
  12582. z: z,
  12583. group: group
  12584. };
  12585. renderItems[ renderItemsIndex ] = renderItem;
  12586. } else {
  12587. renderItem.id = object.id;
  12588. renderItem.object = object;
  12589. renderItem.geometry = geometry;
  12590. renderItem.material = material;
  12591. renderItem.groupOrder = groupOrder;
  12592. renderItem.renderOrder = object.renderOrder;
  12593. renderItem.z = z;
  12594. renderItem.group = group;
  12595. }
  12596. renderItemsIndex ++;
  12597. return renderItem;
  12598. }
  12599. function push( object, geometry, material, groupOrder, z, group ) {
  12600. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12601. if ( material.transmission > 0.0 ) {
  12602. transmissive.push( renderItem );
  12603. } else if ( material.transparent === true ) {
  12604. transparent.push( renderItem );
  12605. } else {
  12606. opaque.push( renderItem );
  12607. }
  12608. }
  12609. function unshift( object, geometry, material, groupOrder, z, group ) {
  12610. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12611. if ( material.transmission > 0.0 ) {
  12612. transmissive.unshift( renderItem );
  12613. } else if ( material.transparent === true ) {
  12614. transparent.unshift( renderItem );
  12615. } else {
  12616. opaque.unshift( renderItem );
  12617. }
  12618. }
  12619. function sort( customOpaqueSort, customTransparentSort ) {
  12620. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  12621. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  12622. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  12623. }
  12624. function finish() {
  12625. // Clear references from inactive renderItems in the list
  12626. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  12627. const renderItem = renderItems[ i ];
  12628. if ( renderItem.id === null ) break;
  12629. renderItem.id = null;
  12630. renderItem.object = null;
  12631. renderItem.geometry = null;
  12632. renderItem.material = null;
  12633. renderItem.group = null;
  12634. }
  12635. }
  12636. return {
  12637. opaque: opaque,
  12638. transmissive: transmissive,
  12639. transparent: transparent,
  12640. init: init,
  12641. push: push,
  12642. unshift: unshift,
  12643. finish: finish,
  12644. sort: sort
  12645. };
  12646. }
  12647. function WebGLRenderLists() {
  12648. let lists = new WeakMap();
  12649. function get( scene, renderCallDepth ) {
  12650. const listArray = lists.get( scene );
  12651. let list;
  12652. if ( listArray === undefined ) {
  12653. list = new WebGLRenderList();
  12654. lists.set( scene, [ list ] );
  12655. } else {
  12656. if ( renderCallDepth >= listArray.length ) {
  12657. list = new WebGLRenderList();
  12658. listArray.push( list );
  12659. } else {
  12660. list = listArray[ renderCallDepth ];
  12661. }
  12662. }
  12663. return list;
  12664. }
  12665. function dispose() {
  12666. lists = new WeakMap();
  12667. }
  12668. return {
  12669. get: get,
  12670. dispose: dispose
  12671. };
  12672. }
  12673. function UniformsCache() {
  12674. const lights = {};
  12675. return {
  12676. get: function ( light ) {
  12677. if ( lights[ light.id ] !== undefined ) {
  12678. return lights[ light.id ];
  12679. }
  12680. let uniforms;
  12681. switch ( light.type ) {
  12682. case 'DirectionalLight':
  12683. uniforms = {
  12684. direction: new Vector3(),
  12685. color: new Color()
  12686. };
  12687. break;
  12688. case 'SpotLight':
  12689. uniforms = {
  12690. position: new Vector3(),
  12691. direction: new Vector3(),
  12692. color: new Color(),
  12693. distance: 0,
  12694. coneCos: 0,
  12695. penumbraCos: 0,
  12696. decay: 0
  12697. };
  12698. break;
  12699. case 'PointLight':
  12700. uniforms = {
  12701. position: new Vector3(),
  12702. color: new Color(),
  12703. distance: 0,
  12704. decay: 0
  12705. };
  12706. break;
  12707. case 'HemisphereLight':
  12708. uniforms = {
  12709. direction: new Vector3(),
  12710. skyColor: new Color(),
  12711. groundColor: new Color()
  12712. };
  12713. break;
  12714. case 'RectAreaLight':
  12715. uniforms = {
  12716. color: new Color(),
  12717. position: new Vector3(),
  12718. halfWidth: new Vector3(),
  12719. halfHeight: new Vector3()
  12720. };
  12721. break;
  12722. }
  12723. lights[ light.id ] = uniforms;
  12724. return uniforms;
  12725. }
  12726. };
  12727. }
  12728. function ShadowUniformsCache() {
  12729. const lights = {};
  12730. return {
  12731. get: function ( light ) {
  12732. if ( lights[ light.id ] !== undefined ) {
  12733. return lights[ light.id ];
  12734. }
  12735. let uniforms;
  12736. switch ( light.type ) {
  12737. case 'DirectionalLight':
  12738. uniforms = {
  12739. shadowBias: 0,
  12740. shadowNormalBias: 0,
  12741. shadowRadius: 1,
  12742. shadowMapSize: new Vector2()
  12743. };
  12744. break;
  12745. case 'SpotLight':
  12746. uniforms = {
  12747. shadowBias: 0,
  12748. shadowNormalBias: 0,
  12749. shadowRadius: 1,
  12750. shadowMapSize: new Vector2()
  12751. };
  12752. break;
  12753. case 'PointLight':
  12754. uniforms = {
  12755. shadowBias: 0,
  12756. shadowNormalBias: 0,
  12757. shadowRadius: 1,
  12758. shadowMapSize: new Vector2(),
  12759. shadowCameraNear: 1,
  12760. shadowCameraFar: 1000
  12761. };
  12762. break;
  12763. // TODO (abelnation): set RectAreaLight shadow uniforms
  12764. }
  12765. lights[ light.id ] = uniforms;
  12766. return uniforms;
  12767. }
  12768. };
  12769. }
  12770. let nextVersion = 0;
  12771. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  12772. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  12773. }
  12774. function WebGLLights( extensions, capabilities ) {
  12775. const cache = new UniformsCache();
  12776. const shadowCache = ShadowUniformsCache();
  12777. const state = {
  12778. version: 0,
  12779. hash: {
  12780. directionalLength: - 1,
  12781. pointLength: - 1,
  12782. spotLength: - 1,
  12783. rectAreaLength: - 1,
  12784. hemiLength: - 1,
  12785. numDirectionalShadows: - 1,
  12786. numPointShadows: - 1,
  12787. numSpotShadows: - 1,
  12788. numSpotMaps: - 1
  12789. },
  12790. ambient: [ 0, 0, 0 ],
  12791. probe: [],
  12792. directional: [],
  12793. directionalShadow: [],
  12794. directionalShadowMap: [],
  12795. directionalShadowMatrix: [],
  12796. spot: [],
  12797. spotLightMap: [],
  12798. spotShadow: [],
  12799. spotShadowMap: [],
  12800. spotLightMatrix: [],
  12801. rectArea: [],
  12802. rectAreaLTC1: null,
  12803. rectAreaLTC2: null,
  12804. point: [],
  12805. pointShadow: [],
  12806. pointShadowMap: [],
  12807. pointShadowMatrix: [],
  12808. hemi: [],
  12809. numSpotLightShadowsWithMaps: 0
  12810. };
  12811. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  12812. const vector3 = new Vector3();
  12813. const matrix4 = new Matrix4();
  12814. const matrix42 = new Matrix4();
  12815. function setup( lights, useLegacyLights ) {
  12816. let r = 0, g = 0, b = 0;
  12817. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  12818. let directionalLength = 0;
  12819. let pointLength = 0;
  12820. let spotLength = 0;
  12821. let rectAreaLength = 0;
  12822. let hemiLength = 0;
  12823. let numDirectionalShadows = 0;
  12824. let numPointShadows = 0;
  12825. let numSpotShadows = 0;
  12826. let numSpotMaps = 0;
  12827. let numSpotShadowsWithMaps = 0;
  12828. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  12829. lights.sort( shadowCastingAndTexturingLightsFirst );
  12830. // artist-friendly light intensity scaling factor
  12831. const scaleFactor = ( useLegacyLights === true ) ? Math.PI : 1;
  12832. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12833. const light = lights[ i ];
  12834. const color = light.color;
  12835. const intensity = light.intensity;
  12836. const distance = light.distance;
  12837. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12838. if ( light.isAmbientLight ) {
  12839. r += color.r * intensity * scaleFactor;
  12840. g += color.g * intensity * scaleFactor;
  12841. b += color.b * intensity * scaleFactor;
  12842. } else if ( light.isLightProbe ) {
  12843. for ( let j = 0; j < 9; j ++ ) {
  12844. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  12845. }
  12846. } else if ( light.isDirectionalLight ) {
  12847. const uniforms = cache.get( light );
  12848. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12849. if ( light.castShadow ) {
  12850. const shadow = light.shadow;
  12851. const shadowUniforms = shadowCache.get( light );
  12852. shadowUniforms.shadowBias = shadow.bias;
  12853. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12854. shadowUniforms.shadowRadius = shadow.radius;
  12855. shadowUniforms.shadowMapSize = shadow.mapSize;
  12856. state.directionalShadow[ directionalLength ] = shadowUniforms;
  12857. state.directionalShadowMap[ directionalLength ] = shadowMap;
  12858. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  12859. numDirectionalShadows ++;
  12860. }
  12861. state.directional[ directionalLength ] = uniforms;
  12862. directionalLength ++;
  12863. } else if ( light.isSpotLight ) {
  12864. const uniforms = cache.get( light );
  12865. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12866. uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor );
  12867. uniforms.distance = distance;
  12868. uniforms.coneCos = Math.cos( light.angle );
  12869. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  12870. uniforms.decay = light.decay;
  12871. state.spot[ spotLength ] = uniforms;
  12872. const shadow = light.shadow;
  12873. if ( light.map ) {
  12874. state.spotLightMap[ numSpotMaps ] = light.map;
  12875. numSpotMaps ++;
  12876. // make sure the lightMatrix is up to date
  12877. // TODO : do it if required only
  12878. shadow.updateMatrices( light );
  12879. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  12880. }
  12881. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  12882. if ( light.castShadow ) {
  12883. const shadowUniforms = shadowCache.get( light );
  12884. shadowUniforms.shadowBias = shadow.bias;
  12885. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12886. shadowUniforms.shadowRadius = shadow.radius;
  12887. shadowUniforms.shadowMapSize = shadow.mapSize;
  12888. state.spotShadow[ spotLength ] = shadowUniforms;
  12889. state.spotShadowMap[ spotLength ] = shadowMap;
  12890. numSpotShadows ++;
  12891. }
  12892. spotLength ++;
  12893. } else if ( light.isRectAreaLight ) {
  12894. const uniforms = cache.get( light );
  12895. uniforms.color.copy( color ).multiplyScalar( intensity );
  12896. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12897. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12898. state.rectArea[ rectAreaLength ] = uniforms;
  12899. rectAreaLength ++;
  12900. } else if ( light.isPointLight ) {
  12901. const uniforms = cache.get( light );
  12902. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12903. uniforms.distance = light.distance;
  12904. uniforms.decay = light.decay;
  12905. if ( light.castShadow ) {
  12906. const shadow = light.shadow;
  12907. const shadowUniforms = shadowCache.get( light );
  12908. shadowUniforms.shadowBias = shadow.bias;
  12909. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12910. shadowUniforms.shadowRadius = shadow.radius;
  12911. shadowUniforms.shadowMapSize = shadow.mapSize;
  12912. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12913. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12914. state.pointShadow[ pointLength ] = shadowUniforms;
  12915. state.pointShadowMap[ pointLength ] = shadowMap;
  12916. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  12917. numPointShadows ++;
  12918. }
  12919. state.point[ pointLength ] = uniforms;
  12920. pointLength ++;
  12921. } else if ( light.isHemisphereLight ) {
  12922. const uniforms = cache.get( light );
  12923. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor );
  12924. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor );
  12925. state.hemi[ hemiLength ] = uniforms;
  12926. hemiLength ++;
  12927. }
  12928. }
  12929. if ( rectAreaLength > 0 ) {
  12930. if ( capabilities.isWebGL2 ) {
  12931. // WebGL 2
  12932. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12933. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12934. } else {
  12935. // WebGL 1
  12936. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  12937. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12938. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12939. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  12940. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12941. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12942. } else {
  12943. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  12944. }
  12945. }
  12946. }
  12947. state.ambient[ 0 ] = r;
  12948. state.ambient[ 1 ] = g;
  12949. state.ambient[ 2 ] = b;
  12950. const hash = state.hash;
  12951. if ( hash.directionalLength !== directionalLength ||
  12952. hash.pointLength !== pointLength ||
  12953. hash.spotLength !== spotLength ||
  12954. hash.rectAreaLength !== rectAreaLength ||
  12955. hash.hemiLength !== hemiLength ||
  12956. hash.numDirectionalShadows !== numDirectionalShadows ||
  12957. hash.numPointShadows !== numPointShadows ||
  12958. hash.numSpotShadows !== numSpotShadows ||
  12959. hash.numSpotMaps !== numSpotMaps ) {
  12960. state.directional.length = directionalLength;
  12961. state.spot.length = spotLength;
  12962. state.rectArea.length = rectAreaLength;
  12963. state.point.length = pointLength;
  12964. state.hemi.length = hemiLength;
  12965. state.directionalShadow.length = numDirectionalShadows;
  12966. state.directionalShadowMap.length = numDirectionalShadows;
  12967. state.pointShadow.length = numPointShadows;
  12968. state.pointShadowMap.length = numPointShadows;
  12969. state.spotShadow.length = numSpotShadows;
  12970. state.spotShadowMap.length = numSpotShadows;
  12971. state.directionalShadowMatrix.length = numDirectionalShadows;
  12972. state.pointShadowMatrix.length = numPointShadows;
  12973. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  12974. state.spotLightMap.length = numSpotMaps;
  12975. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  12976. hash.directionalLength = directionalLength;
  12977. hash.pointLength = pointLength;
  12978. hash.spotLength = spotLength;
  12979. hash.rectAreaLength = rectAreaLength;
  12980. hash.hemiLength = hemiLength;
  12981. hash.numDirectionalShadows = numDirectionalShadows;
  12982. hash.numPointShadows = numPointShadows;
  12983. hash.numSpotShadows = numSpotShadows;
  12984. hash.numSpotMaps = numSpotMaps;
  12985. state.version = nextVersion ++;
  12986. }
  12987. }
  12988. function setupView( lights, camera ) {
  12989. let directionalLength = 0;
  12990. let pointLength = 0;
  12991. let spotLength = 0;
  12992. let rectAreaLength = 0;
  12993. let hemiLength = 0;
  12994. const viewMatrix = camera.matrixWorldInverse;
  12995. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12996. const light = lights[ i ];
  12997. if ( light.isDirectionalLight ) {
  12998. const uniforms = state.directional[ directionalLength ];
  12999. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13000. vector3.setFromMatrixPosition( light.target.matrixWorld );
  13001. uniforms.direction.sub( vector3 );
  13002. uniforms.direction.transformDirection( viewMatrix );
  13003. directionalLength ++;
  13004. } else if ( light.isSpotLight ) {
  13005. const uniforms = state.spot[ spotLength ];
  13006. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13007. uniforms.position.applyMatrix4( viewMatrix );
  13008. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13009. vector3.setFromMatrixPosition( light.target.matrixWorld );
  13010. uniforms.direction.sub( vector3 );
  13011. uniforms.direction.transformDirection( viewMatrix );
  13012. spotLength ++;
  13013. } else if ( light.isRectAreaLight ) {
  13014. const uniforms = state.rectArea[ rectAreaLength ];
  13015. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13016. uniforms.position.applyMatrix4( viewMatrix );
  13017. // extract local rotation of light to derive width/height half vectors
  13018. matrix42.identity();
  13019. matrix4.copy( light.matrixWorld );
  13020. matrix4.premultiply( viewMatrix );
  13021. matrix42.extractRotation( matrix4 );
  13022. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  13023. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  13024. uniforms.halfWidth.applyMatrix4( matrix42 );
  13025. uniforms.halfHeight.applyMatrix4( matrix42 );
  13026. rectAreaLength ++;
  13027. } else if ( light.isPointLight ) {
  13028. const uniforms = state.point[ pointLength ];
  13029. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  13030. uniforms.position.applyMatrix4( viewMatrix );
  13031. pointLength ++;
  13032. } else if ( light.isHemisphereLight ) {
  13033. const uniforms = state.hemi[ hemiLength ];
  13034. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  13035. uniforms.direction.transformDirection( viewMatrix );
  13036. hemiLength ++;
  13037. }
  13038. }
  13039. }
  13040. return {
  13041. setup: setup,
  13042. setupView: setupView,
  13043. state: state
  13044. };
  13045. }
  13046. function WebGLRenderState( extensions, capabilities ) {
  13047. const lights = new WebGLLights( extensions, capabilities );
  13048. const lightsArray = [];
  13049. const shadowsArray = [];
  13050. function init() {
  13051. lightsArray.length = 0;
  13052. shadowsArray.length = 0;
  13053. }
  13054. function pushLight( light ) {
  13055. lightsArray.push( light );
  13056. }
  13057. function pushShadow( shadowLight ) {
  13058. shadowsArray.push( shadowLight );
  13059. }
  13060. function setupLights( useLegacyLights ) {
  13061. lights.setup( lightsArray, useLegacyLights );
  13062. }
  13063. function setupLightsView( camera ) {
  13064. lights.setupView( lightsArray, camera );
  13065. }
  13066. const state = {
  13067. lightsArray: lightsArray,
  13068. shadowsArray: shadowsArray,
  13069. lights: lights
  13070. };
  13071. return {
  13072. init: init,
  13073. state: state,
  13074. setupLights: setupLights,
  13075. setupLightsView: setupLightsView,
  13076. pushLight: pushLight,
  13077. pushShadow: pushShadow
  13078. };
  13079. }
  13080. function WebGLRenderStates( extensions, capabilities ) {
  13081. let renderStates = new WeakMap();
  13082. function get( scene, renderCallDepth = 0 ) {
  13083. const renderStateArray = renderStates.get( scene );
  13084. let renderState;
  13085. if ( renderStateArray === undefined ) {
  13086. renderState = new WebGLRenderState( extensions, capabilities );
  13087. renderStates.set( scene, [ renderState ] );
  13088. } else {
  13089. if ( renderCallDepth >= renderStateArray.length ) {
  13090. renderState = new WebGLRenderState( extensions, capabilities );
  13091. renderStateArray.push( renderState );
  13092. } else {
  13093. renderState = renderStateArray[ renderCallDepth ];
  13094. }
  13095. }
  13096. return renderState;
  13097. }
  13098. function dispose() {
  13099. renderStates = new WeakMap();
  13100. }
  13101. return {
  13102. get: get,
  13103. dispose: dispose
  13104. };
  13105. }
  13106. class MeshDepthMaterial extends Material {
  13107. constructor( parameters ) {
  13108. super();
  13109. this.isMeshDepthMaterial = true;
  13110. this.type = 'MeshDepthMaterial';
  13111. this.depthPacking = BasicDepthPacking;
  13112. this.map = null;
  13113. this.alphaMap = null;
  13114. this.displacementMap = null;
  13115. this.displacementScale = 1;
  13116. this.displacementBias = 0;
  13117. this.wireframe = false;
  13118. this.wireframeLinewidth = 1;
  13119. this.setValues( parameters );
  13120. }
  13121. copy( source ) {
  13122. super.copy( source );
  13123. this.depthPacking = source.depthPacking;
  13124. this.map = source.map;
  13125. this.alphaMap = source.alphaMap;
  13126. this.displacementMap = source.displacementMap;
  13127. this.displacementScale = source.displacementScale;
  13128. this.displacementBias = source.displacementBias;
  13129. this.wireframe = source.wireframe;
  13130. this.wireframeLinewidth = source.wireframeLinewidth;
  13131. return this;
  13132. }
  13133. }
  13134. class MeshDistanceMaterial extends Material {
  13135. constructor( parameters ) {
  13136. super();
  13137. this.isMeshDistanceMaterial = true;
  13138. this.type = 'MeshDistanceMaterial';
  13139. this.map = null;
  13140. this.alphaMap = null;
  13141. this.displacementMap = null;
  13142. this.displacementScale = 1;
  13143. this.displacementBias = 0;
  13144. this.setValues( parameters );
  13145. }
  13146. copy( source ) {
  13147. super.copy( source );
  13148. this.map = source.map;
  13149. this.alphaMap = source.alphaMap;
  13150. this.displacementMap = source.displacementMap;
  13151. this.displacementScale = source.displacementScale;
  13152. this.displacementBias = source.displacementBias;
  13153. return this;
  13154. }
  13155. }
  13156. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  13157. 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}";
  13158. function WebGLShadowMap( _renderer, _objects, _capabilities ) {
  13159. let _frustum = new Frustum();
  13160. const _shadowMapSize = new Vector2(),
  13161. _viewportSize = new Vector2(),
  13162. _viewport = new Vector4(),
  13163. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  13164. _distanceMaterial = new MeshDistanceMaterial(),
  13165. _materialCache = {},
  13166. _maxTextureSize = _capabilities.maxTextureSize;
  13167. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  13168. const shadowMaterialVertical = new ShaderMaterial( {
  13169. defines: {
  13170. VSM_SAMPLES: 8
  13171. },
  13172. uniforms: {
  13173. shadow_pass: { value: null },
  13174. resolution: { value: new Vector2() },
  13175. radius: { value: 4.0 }
  13176. },
  13177. vertexShader: vertex,
  13178. fragmentShader: fragment
  13179. } );
  13180. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  13181. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  13182. const fullScreenTri = new BufferGeometry();
  13183. fullScreenTri.setAttribute(
  13184. 'position',
  13185. new BufferAttribute(
  13186. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  13187. 3
  13188. )
  13189. );
  13190. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  13191. const scope = this;
  13192. this.enabled = false;
  13193. this.autoUpdate = true;
  13194. this.needsUpdate = false;
  13195. this.type = PCFShadowMap;
  13196. let _previousType = this.type;
  13197. this.render = function ( lights, scene, camera ) {
  13198. if ( scope.enabled === false ) return;
  13199. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  13200. if ( lights.length === 0 ) return;
  13201. const currentRenderTarget = _renderer.getRenderTarget();
  13202. const activeCubeFace = _renderer.getActiveCubeFace();
  13203. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  13204. const _state = _renderer.state;
  13205. // Set GL state for depth map.
  13206. _state.setBlending( NoBlending );
  13207. _state.buffers.color.setClear( 1, 1, 1, 1 );
  13208. _state.buffers.depth.setTest( true );
  13209. _state.setScissorTest( false );
  13210. // check for shadow map type changes
  13211. const toVSM = ( _previousType !== VSMShadowMap && this.type === VSMShadowMap );
  13212. const fromVSM = ( _previousType === VSMShadowMap && this.type !== VSMShadowMap );
  13213. // render depth map
  13214. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  13215. const light = lights[ i ];
  13216. const shadow = light.shadow;
  13217. if ( shadow === undefined ) {
  13218. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  13219. continue;
  13220. }
  13221. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  13222. _shadowMapSize.copy( shadow.mapSize );
  13223. const shadowFrameExtents = shadow.getFrameExtents();
  13224. _shadowMapSize.multiply( shadowFrameExtents );
  13225. _viewportSize.copy( shadow.mapSize );
  13226. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  13227. if ( _shadowMapSize.x > _maxTextureSize ) {
  13228. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  13229. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  13230. shadow.mapSize.x = _viewportSize.x;
  13231. }
  13232. if ( _shadowMapSize.y > _maxTextureSize ) {
  13233. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  13234. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  13235. shadow.mapSize.y = _viewportSize.y;
  13236. }
  13237. }
  13238. if ( shadow.map === null || toVSM === true || fromVSM === true ) {
  13239. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  13240. if ( shadow.map !== null ) {
  13241. shadow.map.dispose();
  13242. }
  13243. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  13244. shadow.map.texture.name = light.name + '.shadowMap';
  13245. shadow.camera.updateProjectionMatrix();
  13246. }
  13247. _renderer.setRenderTarget( shadow.map );
  13248. _renderer.clear();
  13249. const viewportCount = shadow.getViewportCount();
  13250. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  13251. const viewport = shadow.getViewport( vp );
  13252. _viewport.set(
  13253. _viewportSize.x * viewport.x,
  13254. _viewportSize.y * viewport.y,
  13255. _viewportSize.x * viewport.z,
  13256. _viewportSize.y * viewport.w
  13257. );
  13258. _state.viewport( _viewport );
  13259. shadow.updateMatrices( light, vp );
  13260. _frustum = shadow.getFrustum();
  13261. renderObject( scene, camera, shadow.camera, light, this.type );
  13262. }
  13263. // do blur pass for VSM
  13264. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  13265. VSMPass( shadow, camera );
  13266. }
  13267. shadow.needsUpdate = false;
  13268. }
  13269. _previousType = this.type;
  13270. scope.needsUpdate = false;
  13271. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  13272. };
  13273. function VSMPass( shadow, camera ) {
  13274. const geometry = _objects.update( fullScreenMesh );
  13275. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  13276. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  13277. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  13278. shadowMaterialVertical.needsUpdate = true;
  13279. shadowMaterialHorizontal.needsUpdate = true;
  13280. }
  13281. if ( shadow.mapPass === null ) {
  13282. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  13283. }
  13284. // vertical pass
  13285. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  13286. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  13287. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  13288. _renderer.setRenderTarget( shadow.mapPass );
  13289. _renderer.clear();
  13290. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  13291. // horizontal pass
  13292. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  13293. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  13294. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  13295. _renderer.setRenderTarget( shadow.map );
  13296. _renderer.clear();
  13297. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  13298. }
  13299. function getDepthMaterial( object, material, light, type ) {
  13300. let result = null;
  13301. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  13302. if ( customMaterial !== undefined ) {
  13303. result = customMaterial;
  13304. } else {
  13305. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  13306. if ( ( _renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  13307. ( material.displacementMap && material.displacementScale !== 0 ) ||
  13308. ( material.alphaMap && material.alphaTest > 0 ) ||
  13309. ( material.map && material.alphaTest > 0 ) ) {
  13310. // in this case we need a unique material instance reflecting the
  13311. // appropriate state
  13312. const keyA = result.uuid, keyB = material.uuid;
  13313. let materialsForVariant = _materialCache[ keyA ];
  13314. if ( materialsForVariant === undefined ) {
  13315. materialsForVariant = {};
  13316. _materialCache[ keyA ] = materialsForVariant;
  13317. }
  13318. let cachedMaterial = materialsForVariant[ keyB ];
  13319. if ( cachedMaterial === undefined ) {
  13320. cachedMaterial = result.clone();
  13321. materialsForVariant[ keyB ] = cachedMaterial;
  13322. }
  13323. result = cachedMaterial;
  13324. }
  13325. }
  13326. result.visible = material.visible;
  13327. result.wireframe = material.wireframe;
  13328. if ( type === VSMShadowMap ) {
  13329. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  13330. } else {
  13331. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  13332. }
  13333. result.alphaMap = material.alphaMap;
  13334. result.alphaTest = material.alphaTest;
  13335. result.map = material.map;
  13336. result.clipShadows = material.clipShadows;
  13337. result.clippingPlanes = material.clippingPlanes;
  13338. result.clipIntersection = material.clipIntersection;
  13339. result.displacementMap = material.displacementMap;
  13340. result.displacementScale = material.displacementScale;
  13341. result.displacementBias = material.displacementBias;
  13342. result.wireframeLinewidth = material.wireframeLinewidth;
  13343. result.linewidth = material.linewidth;
  13344. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  13345. const materialProperties = _renderer.properties.get( result );
  13346. materialProperties.light = light;
  13347. }
  13348. return result;
  13349. }
  13350. function renderObject( object, camera, shadowCamera, light, type ) {
  13351. if ( object.visible === false ) return;
  13352. const visible = object.layers.test( camera.layers );
  13353. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  13354. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  13355. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  13356. const geometry = _objects.update( object );
  13357. const material = object.material;
  13358. if ( Array.isArray( material ) ) {
  13359. const groups = geometry.groups;
  13360. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  13361. const group = groups[ k ];
  13362. const groupMaterial = material[ group.materialIndex ];
  13363. if ( groupMaterial && groupMaterial.visible ) {
  13364. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  13365. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  13366. }
  13367. }
  13368. } else if ( material.visible ) {
  13369. const depthMaterial = getDepthMaterial( object, material, light, type );
  13370. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  13371. }
  13372. }
  13373. }
  13374. const children = object.children;
  13375. for ( let i = 0, l = children.length; i < l; i ++ ) {
  13376. renderObject( children[ i ], camera, shadowCamera, light, type );
  13377. }
  13378. }
  13379. }
  13380. function WebGLState( gl, extensions, capabilities ) {
  13381. const isWebGL2 = capabilities.isWebGL2;
  13382. function ColorBuffer() {
  13383. let locked = false;
  13384. const color = new Vector4();
  13385. let currentColorMask = null;
  13386. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  13387. return {
  13388. setMask: function ( colorMask ) {
  13389. if ( currentColorMask !== colorMask && ! locked ) {
  13390. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  13391. currentColorMask = colorMask;
  13392. }
  13393. },
  13394. setLocked: function ( lock ) {
  13395. locked = lock;
  13396. },
  13397. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  13398. if ( premultipliedAlpha === true ) {
  13399. r *= a; g *= a; b *= a;
  13400. }
  13401. color.set( r, g, b, a );
  13402. if ( currentColorClear.equals( color ) === false ) {
  13403. gl.clearColor( r, g, b, a );
  13404. currentColorClear.copy( color );
  13405. }
  13406. },
  13407. reset: function () {
  13408. locked = false;
  13409. currentColorMask = null;
  13410. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  13411. }
  13412. };
  13413. }
  13414. function DepthBuffer() {
  13415. let locked = false;
  13416. let currentDepthMask = null;
  13417. let currentDepthFunc = null;
  13418. let currentDepthClear = null;
  13419. return {
  13420. setTest: function ( depthTest ) {
  13421. if ( depthTest ) {
  13422. enable( gl.DEPTH_TEST );
  13423. } else {
  13424. disable( gl.DEPTH_TEST );
  13425. }
  13426. },
  13427. setMask: function ( depthMask ) {
  13428. if ( currentDepthMask !== depthMask && ! locked ) {
  13429. gl.depthMask( depthMask );
  13430. currentDepthMask = depthMask;
  13431. }
  13432. },
  13433. setFunc: function ( depthFunc ) {
  13434. if ( currentDepthFunc !== depthFunc ) {
  13435. switch ( depthFunc ) {
  13436. case NeverDepth:
  13437. gl.depthFunc( gl.NEVER );
  13438. break;
  13439. case AlwaysDepth:
  13440. gl.depthFunc( gl.ALWAYS );
  13441. break;
  13442. case LessDepth:
  13443. gl.depthFunc( gl.LESS );
  13444. break;
  13445. case LessEqualDepth:
  13446. gl.depthFunc( gl.LEQUAL );
  13447. break;
  13448. case EqualDepth:
  13449. gl.depthFunc( gl.EQUAL );
  13450. break;
  13451. case GreaterEqualDepth:
  13452. gl.depthFunc( gl.GEQUAL );
  13453. break;
  13454. case GreaterDepth:
  13455. gl.depthFunc( gl.GREATER );
  13456. break;
  13457. case NotEqualDepth:
  13458. gl.depthFunc( gl.NOTEQUAL );
  13459. break;
  13460. default:
  13461. gl.depthFunc( gl.LEQUAL );
  13462. }
  13463. currentDepthFunc = depthFunc;
  13464. }
  13465. },
  13466. setLocked: function ( lock ) {
  13467. locked = lock;
  13468. },
  13469. setClear: function ( depth ) {
  13470. if ( currentDepthClear !== depth ) {
  13471. gl.clearDepth( depth );
  13472. currentDepthClear = depth;
  13473. }
  13474. },
  13475. reset: function () {
  13476. locked = false;
  13477. currentDepthMask = null;
  13478. currentDepthFunc = null;
  13479. currentDepthClear = null;
  13480. }
  13481. };
  13482. }
  13483. function StencilBuffer() {
  13484. let locked = false;
  13485. let currentStencilMask = null;
  13486. let currentStencilFunc = null;
  13487. let currentStencilRef = null;
  13488. let currentStencilFuncMask = null;
  13489. let currentStencilFail = null;
  13490. let currentStencilZFail = null;
  13491. let currentStencilZPass = null;
  13492. let currentStencilClear = null;
  13493. return {
  13494. setTest: function ( stencilTest ) {
  13495. if ( ! locked ) {
  13496. if ( stencilTest ) {
  13497. enable( gl.STENCIL_TEST );
  13498. } else {
  13499. disable( gl.STENCIL_TEST );
  13500. }
  13501. }
  13502. },
  13503. setMask: function ( stencilMask ) {
  13504. if ( currentStencilMask !== stencilMask && ! locked ) {
  13505. gl.stencilMask( stencilMask );
  13506. currentStencilMask = stencilMask;
  13507. }
  13508. },
  13509. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  13510. if ( currentStencilFunc !== stencilFunc ||
  13511. currentStencilRef !== stencilRef ||
  13512. currentStencilFuncMask !== stencilMask ) {
  13513. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  13514. currentStencilFunc = stencilFunc;
  13515. currentStencilRef = stencilRef;
  13516. currentStencilFuncMask = stencilMask;
  13517. }
  13518. },
  13519. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  13520. if ( currentStencilFail !== stencilFail ||
  13521. currentStencilZFail !== stencilZFail ||
  13522. currentStencilZPass !== stencilZPass ) {
  13523. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  13524. currentStencilFail = stencilFail;
  13525. currentStencilZFail = stencilZFail;
  13526. currentStencilZPass = stencilZPass;
  13527. }
  13528. },
  13529. setLocked: function ( lock ) {
  13530. locked = lock;
  13531. },
  13532. setClear: function ( stencil ) {
  13533. if ( currentStencilClear !== stencil ) {
  13534. gl.clearStencil( stencil );
  13535. currentStencilClear = stencil;
  13536. }
  13537. },
  13538. reset: function () {
  13539. locked = false;
  13540. currentStencilMask = null;
  13541. currentStencilFunc = null;
  13542. currentStencilRef = null;
  13543. currentStencilFuncMask = null;
  13544. currentStencilFail = null;
  13545. currentStencilZFail = null;
  13546. currentStencilZPass = null;
  13547. currentStencilClear = null;
  13548. }
  13549. };
  13550. }
  13551. //
  13552. const colorBuffer = new ColorBuffer();
  13553. const depthBuffer = new DepthBuffer();
  13554. const stencilBuffer = new StencilBuffer();
  13555. const uboBindings = new WeakMap();
  13556. const uboProgramMap = new WeakMap();
  13557. let enabledCapabilities = {};
  13558. let currentBoundFramebuffers = {};
  13559. let currentDrawbuffers = new WeakMap();
  13560. let defaultDrawbuffers = [];
  13561. let currentProgram = null;
  13562. let currentBlendingEnabled = false;
  13563. let currentBlending = null;
  13564. let currentBlendEquation = null;
  13565. let currentBlendSrc = null;
  13566. let currentBlendDst = null;
  13567. let currentBlendEquationAlpha = null;
  13568. let currentBlendSrcAlpha = null;
  13569. let currentBlendDstAlpha = null;
  13570. let currentPremultipledAlpha = false;
  13571. let currentFlipSided = null;
  13572. let currentCullFace = null;
  13573. let currentLineWidth = null;
  13574. let currentPolygonOffsetFactor = null;
  13575. let currentPolygonOffsetUnits = null;
  13576. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  13577. let lineWidthAvailable = false;
  13578. let version = 0;
  13579. const glVersion = gl.getParameter( gl.VERSION );
  13580. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  13581. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  13582. lineWidthAvailable = ( version >= 1.0 );
  13583. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  13584. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  13585. lineWidthAvailable = ( version >= 2.0 );
  13586. }
  13587. let currentTextureSlot = null;
  13588. let currentBoundTextures = {};
  13589. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  13590. const viewportParam = gl.getParameter( gl.VIEWPORT );
  13591. const currentScissor = new Vector4().fromArray( scissorParam );
  13592. const currentViewport = new Vector4().fromArray( viewportParam );
  13593. function createTexture( type, target, count, dimensions ) {
  13594. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  13595. const texture = gl.createTexture();
  13596. gl.bindTexture( type, texture );
  13597. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  13598. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  13599. for ( let i = 0; i < count; i ++ ) {
  13600. if ( isWebGL2 && ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) ) {
  13601. gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  13602. } else {
  13603. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  13604. }
  13605. }
  13606. return texture;
  13607. }
  13608. const emptyTextures = {};
  13609. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  13610. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  13611. if ( isWebGL2 ) {
  13612. emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );
  13613. emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );
  13614. }
  13615. // init
  13616. colorBuffer.setClear( 0, 0, 0, 1 );
  13617. depthBuffer.setClear( 1 );
  13618. stencilBuffer.setClear( 0 );
  13619. enable( gl.DEPTH_TEST );
  13620. depthBuffer.setFunc( LessEqualDepth );
  13621. setFlipSided( false );
  13622. setCullFace( CullFaceBack );
  13623. enable( gl.CULL_FACE );
  13624. setBlending( NoBlending );
  13625. //
  13626. function enable( id ) {
  13627. if ( enabledCapabilities[ id ] !== true ) {
  13628. gl.enable( id );
  13629. enabledCapabilities[ id ] = true;
  13630. }
  13631. }
  13632. function disable( id ) {
  13633. if ( enabledCapabilities[ id ] !== false ) {
  13634. gl.disable( id );
  13635. enabledCapabilities[ id ] = false;
  13636. }
  13637. }
  13638. function bindFramebuffer( target, framebuffer ) {
  13639. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  13640. gl.bindFramebuffer( target, framebuffer );
  13641. currentBoundFramebuffers[ target ] = framebuffer;
  13642. if ( isWebGL2 ) {
  13643. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  13644. if ( target === gl.DRAW_FRAMEBUFFER ) {
  13645. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  13646. }
  13647. if ( target === gl.FRAMEBUFFER ) {
  13648. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  13649. }
  13650. }
  13651. return true;
  13652. }
  13653. return false;
  13654. }
  13655. function drawBuffers( renderTarget, framebuffer ) {
  13656. let drawBuffers = defaultDrawbuffers;
  13657. let needsUpdate = false;
  13658. if ( renderTarget ) {
  13659. drawBuffers = currentDrawbuffers.get( framebuffer );
  13660. if ( drawBuffers === undefined ) {
  13661. drawBuffers = [];
  13662. currentDrawbuffers.set( framebuffer, drawBuffers );
  13663. }
  13664. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13665. const textures = renderTarget.texture;
  13666. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  13667. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13668. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  13669. }
  13670. drawBuffers.length = textures.length;
  13671. needsUpdate = true;
  13672. }
  13673. } else {
  13674. if ( drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  13675. drawBuffers[ 0 ] = gl.COLOR_ATTACHMENT0;
  13676. needsUpdate = true;
  13677. }
  13678. }
  13679. } else {
  13680. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  13681. drawBuffers[ 0 ] = gl.BACK;
  13682. needsUpdate = true;
  13683. }
  13684. }
  13685. if ( needsUpdate ) {
  13686. if ( capabilities.isWebGL2 ) {
  13687. gl.drawBuffers( drawBuffers );
  13688. } else {
  13689. extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers );
  13690. }
  13691. }
  13692. }
  13693. function useProgram( program ) {
  13694. if ( currentProgram !== program ) {
  13695. gl.useProgram( program );
  13696. currentProgram = program;
  13697. return true;
  13698. }
  13699. return false;
  13700. }
  13701. const equationToGL = {
  13702. [ AddEquation ]: gl.FUNC_ADD,
  13703. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  13704. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  13705. };
  13706. if ( isWebGL2 ) {
  13707. equationToGL[ MinEquation ] = gl.MIN;
  13708. equationToGL[ MaxEquation ] = gl.MAX;
  13709. } else {
  13710. const extension = extensions.get( 'EXT_blend_minmax' );
  13711. if ( extension !== null ) {
  13712. equationToGL[ MinEquation ] = extension.MIN_EXT;
  13713. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  13714. }
  13715. }
  13716. const factorToGL = {
  13717. [ ZeroFactor ]: gl.ZERO,
  13718. [ OneFactor ]: gl.ONE,
  13719. [ SrcColorFactor ]: gl.SRC_COLOR,
  13720. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  13721. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  13722. [ DstColorFactor ]: gl.DST_COLOR,
  13723. [ DstAlphaFactor ]: gl.DST_ALPHA,
  13724. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  13725. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  13726. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  13727. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  13728. };
  13729. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  13730. if ( blending === NoBlending ) {
  13731. if ( currentBlendingEnabled === true ) {
  13732. disable( gl.BLEND );
  13733. currentBlendingEnabled = false;
  13734. }
  13735. return;
  13736. }
  13737. if ( currentBlendingEnabled === false ) {
  13738. enable( gl.BLEND );
  13739. currentBlendingEnabled = true;
  13740. }
  13741. if ( blending !== CustomBlending ) {
  13742. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  13743. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  13744. gl.blendEquation( gl.FUNC_ADD );
  13745. currentBlendEquation = AddEquation;
  13746. currentBlendEquationAlpha = AddEquation;
  13747. }
  13748. if ( premultipliedAlpha ) {
  13749. switch ( blending ) {
  13750. case NormalBlending:
  13751. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  13752. break;
  13753. case AdditiveBlending:
  13754. gl.blendFunc( gl.ONE, gl.ONE );
  13755. break;
  13756. case SubtractiveBlending:
  13757. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  13758. break;
  13759. case MultiplyBlending:
  13760. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  13761. break;
  13762. default:
  13763. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13764. break;
  13765. }
  13766. } else {
  13767. switch ( blending ) {
  13768. case NormalBlending:
  13769. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  13770. break;
  13771. case AdditiveBlending:
  13772. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  13773. break;
  13774. case SubtractiveBlending:
  13775. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  13776. break;
  13777. case MultiplyBlending:
  13778. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  13779. break;
  13780. default:
  13781. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13782. break;
  13783. }
  13784. }
  13785. currentBlendSrc = null;
  13786. currentBlendDst = null;
  13787. currentBlendSrcAlpha = null;
  13788. currentBlendDstAlpha = null;
  13789. currentBlending = blending;
  13790. currentPremultipledAlpha = premultipliedAlpha;
  13791. }
  13792. return;
  13793. }
  13794. // custom blending
  13795. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13796. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13797. blendDstAlpha = blendDstAlpha || blendDst;
  13798. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  13799. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  13800. currentBlendEquation = blendEquation;
  13801. currentBlendEquationAlpha = blendEquationAlpha;
  13802. }
  13803. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  13804. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  13805. currentBlendSrc = blendSrc;
  13806. currentBlendDst = blendDst;
  13807. currentBlendSrcAlpha = blendSrcAlpha;
  13808. currentBlendDstAlpha = blendDstAlpha;
  13809. }
  13810. currentBlending = blending;
  13811. currentPremultipledAlpha = false;
  13812. }
  13813. function setMaterial( material, frontFaceCW ) {
  13814. material.side === DoubleSide
  13815. ? disable( gl.CULL_FACE )
  13816. : enable( gl.CULL_FACE );
  13817. let flipSided = ( material.side === BackSide );
  13818. if ( frontFaceCW ) flipSided = ! flipSided;
  13819. setFlipSided( flipSided );
  13820. ( material.blending === NormalBlending && material.transparent === false )
  13821. ? setBlending( NoBlending )
  13822. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  13823. depthBuffer.setFunc( material.depthFunc );
  13824. depthBuffer.setTest( material.depthTest );
  13825. depthBuffer.setMask( material.depthWrite );
  13826. colorBuffer.setMask( material.colorWrite );
  13827. const stencilWrite = material.stencilWrite;
  13828. stencilBuffer.setTest( stencilWrite );
  13829. if ( stencilWrite ) {
  13830. stencilBuffer.setMask( material.stencilWriteMask );
  13831. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  13832. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  13833. }
  13834. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13835. material.alphaToCoverage === true
  13836. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  13837. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  13838. }
  13839. //
  13840. function setFlipSided( flipSided ) {
  13841. if ( currentFlipSided !== flipSided ) {
  13842. if ( flipSided ) {
  13843. gl.frontFace( gl.CW );
  13844. } else {
  13845. gl.frontFace( gl.CCW );
  13846. }
  13847. currentFlipSided = flipSided;
  13848. }
  13849. }
  13850. function setCullFace( cullFace ) {
  13851. if ( cullFace !== CullFaceNone ) {
  13852. enable( gl.CULL_FACE );
  13853. if ( cullFace !== currentCullFace ) {
  13854. if ( cullFace === CullFaceBack ) {
  13855. gl.cullFace( gl.BACK );
  13856. } else if ( cullFace === CullFaceFront ) {
  13857. gl.cullFace( gl.FRONT );
  13858. } else {
  13859. gl.cullFace( gl.FRONT_AND_BACK );
  13860. }
  13861. }
  13862. } else {
  13863. disable( gl.CULL_FACE );
  13864. }
  13865. currentCullFace = cullFace;
  13866. }
  13867. function setLineWidth( width ) {
  13868. if ( width !== currentLineWidth ) {
  13869. if ( lineWidthAvailable ) gl.lineWidth( width );
  13870. currentLineWidth = width;
  13871. }
  13872. }
  13873. function setPolygonOffset( polygonOffset, factor, units ) {
  13874. if ( polygonOffset ) {
  13875. enable( gl.POLYGON_OFFSET_FILL );
  13876. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  13877. gl.polygonOffset( factor, units );
  13878. currentPolygonOffsetFactor = factor;
  13879. currentPolygonOffsetUnits = units;
  13880. }
  13881. } else {
  13882. disable( gl.POLYGON_OFFSET_FILL );
  13883. }
  13884. }
  13885. function setScissorTest( scissorTest ) {
  13886. if ( scissorTest ) {
  13887. enable( gl.SCISSOR_TEST );
  13888. } else {
  13889. disable( gl.SCISSOR_TEST );
  13890. }
  13891. }
  13892. // texture
  13893. function activeTexture( webglSlot ) {
  13894. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13895. if ( currentTextureSlot !== webglSlot ) {
  13896. gl.activeTexture( webglSlot );
  13897. currentTextureSlot = webglSlot;
  13898. }
  13899. }
  13900. function bindTexture( webglType, webglTexture, webglSlot ) {
  13901. if ( webglSlot === undefined ) {
  13902. if ( currentTextureSlot === null ) {
  13903. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  13904. } else {
  13905. webglSlot = currentTextureSlot;
  13906. }
  13907. }
  13908. let boundTexture = currentBoundTextures[ webglSlot ];
  13909. if ( boundTexture === undefined ) {
  13910. boundTexture = { type: undefined, texture: undefined };
  13911. currentBoundTextures[ webglSlot ] = boundTexture;
  13912. }
  13913. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  13914. if ( currentTextureSlot !== webglSlot ) {
  13915. gl.activeTexture( webglSlot );
  13916. currentTextureSlot = webglSlot;
  13917. }
  13918. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  13919. boundTexture.type = webglType;
  13920. boundTexture.texture = webglTexture;
  13921. }
  13922. }
  13923. function unbindTexture() {
  13924. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  13925. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  13926. gl.bindTexture( boundTexture.type, null );
  13927. boundTexture.type = undefined;
  13928. boundTexture.texture = undefined;
  13929. }
  13930. }
  13931. function compressedTexImage2D() {
  13932. try {
  13933. gl.compressedTexImage2D.apply( gl, arguments );
  13934. } catch ( error ) {
  13935. console.error( 'THREE.WebGLState:', error );
  13936. }
  13937. }
  13938. function compressedTexImage3D() {
  13939. try {
  13940. gl.compressedTexImage3D.apply( gl, arguments );
  13941. } catch ( error ) {
  13942. console.error( 'THREE.WebGLState:', error );
  13943. }
  13944. }
  13945. function texSubImage2D() {
  13946. try {
  13947. gl.texSubImage2D.apply( gl, arguments );
  13948. } catch ( error ) {
  13949. console.error( 'THREE.WebGLState:', error );
  13950. }
  13951. }
  13952. function texSubImage3D() {
  13953. try {
  13954. gl.texSubImage3D.apply( gl, arguments );
  13955. } catch ( error ) {
  13956. console.error( 'THREE.WebGLState:', error );
  13957. }
  13958. }
  13959. function compressedTexSubImage2D() {
  13960. try {
  13961. gl.compressedTexSubImage2D.apply( gl, arguments );
  13962. } catch ( error ) {
  13963. console.error( 'THREE.WebGLState:', error );
  13964. }
  13965. }
  13966. function compressedTexSubImage3D() {
  13967. try {
  13968. gl.compressedTexSubImage3D.apply( gl, arguments );
  13969. } catch ( error ) {
  13970. console.error( 'THREE.WebGLState:', error );
  13971. }
  13972. }
  13973. function texStorage2D() {
  13974. try {
  13975. gl.texStorage2D.apply( gl, arguments );
  13976. } catch ( error ) {
  13977. console.error( 'THREE.WebGLState:', error );
  13978. }
  13979. }
  13980. function texStorage3D() {
  13981. try {
  13982. gl.texStorage3D.apply( gl, arguments );
  13983. } catch ( error ) {
  13984. console.error( 'THREE.WebGLState:', error );
  13985. }
  13986. }
  13987. function texImage2D() {
  13988. try {
  13989. gl.texImage2D.apply( gl, arguments );
  13990. } catch ( error ) {
  13991. console.error( 'THREE.WebGLState:', error );
  13992. }
  13993. }
  13994. function texImage3D() {
  13995. try {
  13996. gl.texImage3D.apply( gl, arguments );
  13997. } catch ( error ) {
  13998. console.error( 'THREE.WebGLState:', error );
  13999. }
  14000. }
  14001. //
  14002. function scissor( scissor ) {
  14003. if ( currentScissor.equals( scissor ) === false ) {
  14004. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  14005. currentScissor.copy( scissor );
  14006. }
  14007. }
  14008. function viewport( viewport ) {
  14009. if ( currentViewport.equals( viewport ) === false ) {
  14010. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  14011. currentViewport.copy( viewport );
  14012. }
  14013. }
  14014. function updateUBOMapping( uniformsGroup, program ) {
  14015. let mapping = uboProgramMap.get( program );
  14016. if ( mapping === undefined ) {
  14017. mapping = new WeakMap();
  14018. uboProgramMap.set( program, mapping );
  14019. }
  14020. let blockIndex = mapping.get( uniformsGroup );
  14021. if ( blockIndex === undefined ) {
  14022. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  14023. mapping.set( uniformsGroup, blockIndex );
  14024. }
  14025. }
  14026. function uniformBlockBinding( uniformsGroup, program ) {
  14027. const mapping = uboProgramMap.get( program );
  14028. const blockIndex = mapping.get( uniformsGroup );
  14029. if ( uboBindings.get( program ) !== blockIndex ) {
  14030. // bind shader specific block index to global block point
  14031. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  14032. uboBindings.set( program, blockIndex );
  14033. }
  14034. }
  14035. //
  14036. function reset() {
  14037. // reset state
  14038. gl.disable( gl.BLEND );
  14039. gl.disable( gl.CULL_FACE );
  14040. gl.disable( gl.DEPTH_TEST );
  14041. gl.disable( gl.POLYGON_OFFSET_FILL );
  14042. gl.disable( gl.SCISSOR_TEST );
  14043. gl.disable( gl.STENCIL_TEST );
  14044. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  14045. gl.blendEquation( gl.FUNC_ADD );
  14046. gl.blendFunc( gl.ONE, gl.ZERO );
  14047. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  14048. gl.colorMask( true, true, true, true );
  14049. gl.clearColor( 0, 0, 0, 0 );
  14050. gl.depthMask( true );
  14051. gl.depthFunc( gl.LESS );
  14052. gl.clearDepth( 1 );
  14053. gl.stencilMask( 0xffffffff );
  14054. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  14055. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  14056. gl.clearStencil( 0 );
  14057. gl.cullFace( gl.BACK );
  14058. gl.frontFace( gl.CCW );
  14059. gl.polygonOffset( 0, 0 );
  14060. gl.activeTexture( gl.TEXTURE0 );
  14061. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  14062. if ( isWebGL2 === true ) {
  14063. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  14064. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  14065. }
  14066. gl.useProgram( null );
  14067. gl.lineWidth( 1 );
  14068. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  14069. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  14070. // reset internals
  14071. enabledCapabilities = {};
  14072. currentTextureSlot = null;
  14073. currentBoundTextures = {};
  14074. currentBoundFramebuffers = {};
  14075. currentDrawbuffers = new WeakMap();
  14076. defaultDrawbuffers = [];
  14077. currentProgram = null;
  14078. currentBlendingEnabled = false;
  14079. currentBlending = null;
  14080. currentBlendEquation = null;
  14081. currentBlendSrc = null;
  14082. currentBlendDst = null;
  14083. currentBlendEquationAlpha = null;
  14084. currentBlendSrcAlpha = null;
  14085. currentBlendDstAlpha = null;
  14086. currentPremultipledAlpha = false;
  14087. currentFlipSided = null;
  14088. currentCullFace = null;
  14089. currentLineWidth = null;
  14090. currentPolygonOffsetFactor = null;
  14091. currentPolygonOffsetUnits = null;
  14092. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  14093. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  14094. colorBuffer.reset();
  14095. depthBuffer.reset();
  14096. stencilBuffer.reset();
  14097. }
  14098. return {
  14099. buffers: {
  14100. color: colorBuffer,
  14101. depth: depthBuffer,
  14102. stencil: stencilBuffer
  14103. },
  14104. enable: enable,
  14105. disable: disable,
  14106. bindFramebuffer: bindFramebuffer,
  14107. drawBuffers: drawBuffers,
  14108. useProgram: useProgram,
  14109. setBlending: setBlending,
  14110. setMaterial: setMaterial,
  14111. setFlipSided: setFlipSided,
  14112. setCullFace: setCullFace,
  14113. setLineWidth: setLineWidth,
  14114. setPolygonOffset: setPolygonOffset,
  14115. setScissorTest: setScissorTest,
  14116. activeTexture: activeTexture,
  14117. bindTexture: bindTexture,
  14118. unbindTexture: unbindTexture,
  14119. compressedTexImage2D: compressedTexImage2D,
  14120. compressedTexImage3D: compressedTexImage3D,
  14121. texImage2D: texImage2D,
  14122. texImage3D: texImage3D,
  14123. updateUBOMapping: updateUBOMapping,
  14124. uniformBlockBinding: uniformBlockBinding,
  14125. texStorage2D: texStorage2D,
  14126. texStorage3D: texStorage3D,
  14127. texSubImage2D: texSubImage2D,
  14128. texSubImage3D: texSubImage3D,
  14129. compressedTexSubImage2D: compressedTexSubImage2D,
  14130. compressedTexSubImage3D: compressedTexSubImage3D,
  14131. scissor: scissor,
  14132. viewport: viewport,
  14133. reset: reset
  14134. };
  14135. }
  14136. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  14137. const isWebGL2 = capabilities.isWebGL2;
  14138. const maxTextures = capabilities.maxTextures;
  14139. const maxCubemapSize = capabilities.maxCubemapSize;
  14140. const maxTextureSize = capabilities.maxTextureSize;
  14141. const maxSamples = capabilities.maxSamples;
  14142. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  14143. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  14144. const _videoTextures = new WeakMap();
  14145. let _canvas;
  14146. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  14147. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  14148. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  14149. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  14150. let useOffscreenCanvas = false;
  14151. try {
  14152. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  14153. // eslint-disable-next-line compat/compat
  14154. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  14155. } catch ( err ) {
  14156. // Ignore any errors
  14157. }
  14158. function createCanvas( width, height ) {
  14159. // Use OffscreenCanvas when available. Specially needed in web workers
  14160. return useOffscreenCanvas ?
  14161. // eslint-disable-next-line compat/compat
  14162. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  14163. }
  14164. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  14165. let scale = 1;
  14166. // handle case if texture exceeds max size
  14167. if ( image.width > maxSize || image.height > maxSize ) {
  14168. scale = maxSize / Math.max( image.width, image.height );
  14169. }
  14170. // only perform resize if necessary
  14171. if ( scale < 1 || needsPowerOfTwo === true ) {
  14172. // only perform resize for certain image types
  14173. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  14174. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  14175. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  14176. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  14177. const width = floor( scale * image.width );
  14178. const height = floor( scale * image.height );
  14179. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  14180. // cube textures can't reuse the same canvas
  14181. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  14182. canvas.width = width;
  14183. canvas.height = height;
  14184. const context = canvas.getContext( '2d' );
  14185. context.drawImage( image, 0, 0, width, height );
  14186. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  14187. return canvas;
  14188. } else {
  14189. if ( 'data' in image ) {
  14190. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  14191. }
  14192. return image;
  14193. }
  14194. }
  14195. return image;
  14196. }
  14197. function isPowerOfTwo$1( image ) {
  14198. return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height );
  14199. }
  14200. function textureNeedsPowerOfTwo( texture ) {
  14201. if ( isWebGL2 ) return false;
  14202. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  14203. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  14204. }
  14205. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  14206. return texture.generateMipmaps && supportsMips &&
  14207. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  14208. }
  14209. function generateMipmap( target ) {
  14210. _gl.generateMipmap( target );
  14211. }
  14212. function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  14213. if ( isWebGL2 === false ) return glFormat;
  14214. if ( internalFormatName !== null ) {
  14215. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  14216. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  14217. }
  14218. let internalFormat = glFormat;
  14219. if ( glFormat === _gl.RED ) {
  14220. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  14221. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  14222. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  14223. }
  14224. if ( glFormat === _gl.RG ) {
  14225. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  14226. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  14227. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  14228. }
  14229. if ( glFormat === _gl.RGBA ) {
  14230. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  14231. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  14232. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  14233. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  14234. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  14235. }
  14236. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  14237. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  14238. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  14239. extensions.get( 'EXT_color_buffer_float' );
  14240. }
  14241. return internalFormat;
  14242. }
  14243. function getMipLevels( texture, image, supportsMips ) {
  14244. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  14245. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  14246. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  14247. // user-defined mipmaps
  14248. return texture.mipmaps.length;
  14249. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  14250. return image.mipmaps.length;
  14251. } else {
  14252. // texture without mipmaps (only base level)
  14253. return 1;
  14254. }
  14255. }
  14256. // Fallback filters for non-power-of-2 textures
  14257. function filterFallback( f ) {
  14258. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  14259. return _gl.NEAREST;
  14260. }
  14261. return _gl.LINEAR;
  14262. }
  14263. //
  14264. function onTextureDispose( event ) {
  14265. const texture = event.target;
  14266. texture.removeEventListener( 'dispose', onTextureDispose );
  14267. deallocateTexture( texture );
  14268. if ( texture.isVideoTexture ) {
  14269. _videoTextures.delete( texture );
  14270. }
  14271. }
  14272. function onRenderTargetDispose( event ) {
  14273. const renderTarget = event.target;
  14274. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  14275. deallocateRenderTarget( renderTarget );
  14276. }
  14277. //
  14278. function deallocateTexture( texture ) {
  14279. const textureProperties = properties.get( texture );
  14280. if ( textureProperties.__webglInit === undefined ) return;
  14281. // check if it's necessary to remove the WebGLTexture object
  14282. const source = texture.source;
  14283. const webglTextures = _sources.get( source );
  14284. if ( webglTextures ) {
  14285. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  14286. webglTexture.usedTimes --;
  14287. // the WebGLTexture object is not used anymore, remove it
  14288. if ( webglTexture.usedTimes === 0 ) {
  14289. deleteTexture( texture );
  14290. }
  14291. // remove the weak map entry if no WebGLTexture uses the source anymore
  14292. if ( Object.keys( webglTextures ).length === 0 ) {
  14293. _sources.delete( source );
  14294. }
  14295. }
  14296. properties.remove( texture );
  14297. }
  14298. function deleteTexture( texture ) {
  14299. const textureProperties = properties.get( texture );
  14300. _gl.deleteTexture( textureProperties.__webglTexture );
  14301. const source = texture.source;
  14302. const webglTextures = _sources.get( source );
  14303. delete webglTextures[ textureProperties.__cacheKey ];
  14304. info.memory.textures --;
  14305. }
  14306. function deallocateRenderTarget( renderTarget ) {
  14307. const texture = renderTarget.texture;
  14308. const renderTargetProperties = properties.get( renderTarget );
  14309. const textureProperties = properties.get( texture );
  14310. if ( textureProperties.__webglTexture !== undefined ) {
  14311. _gl.deleteTexture( textureProperties.__webglTexture );
  14312. info.memory.textures --;
  14313. }
  14314. if ( renderTarget.depthTexture ) {
  14315. renderTarget.depthTexture.dispose();
  14316. }
  14317. if ( renderTarget.isWebGLCubeRenderTarget ) {
  14318. for ( let i = 0; i < 6; i ++ ) {
  14319. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  14320. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  14321. }
  14322. } else {
  14323. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  14324. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  14325. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  14326. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  14327. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  14328. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14329. }
  14330. }
  14331. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  14332. }
  14333. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  14334. for ( let i = 0, il = texture.length; i < il; i ++ ) {
  14335. const attachmentProperties = properties.get( texture[ i ] );
  14336. if ( attachmentProperties.__webglTexture ) {
  14337. _gl.deleteTexture( attachmentProperties.__webglTexture );
  14338. info.memory.textures --;
  14339. }
  14340. properties.remove( texture[ i ] );
  14341. }
  14342. }
  14343. properties.remove( texture );
  14344. properties.remove( renderTarget );
  14345. }
  14346. //
  14347. let textureUnits = 0;
  14348. function resetTextureUnits() {
  14349. textureUnits = 0;
  14350. }
  14351. function allocateTextureUnit() {
  14352. const textureUnit = textureUnits;
  14353. if ( textureUnit >= maxTextures ) {
  14354. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  14355. }
  14356. textureUnits += 1;
  14357. return textureUnit;
  14358. }
  14359. function getTextureCacheKey( texture ) {
  14360. const array = [];
  14361. array.push( texture.wrapS );
  14362. array.push( texture.wrapT );
  14363. array.push( texture.wrapR || 0 );
  14364. array.push( texture.magFilter );
  14365. array.push( texture.minFilter );
  14366. array.push( texture.anisotropy );
  14367. array.push( texture.internalFormat );
  14368. array.push( texture.format );
  14369. array.push( texture.type );
  14370. array.push( texture.generateMipmaps );
  14371. array.push( texture.premultiplyAlpha );
  14372. array.push( texture.flipY );
  14373. array.push( texture.unpackAlignment );
  14374. array.push( texture.colorSpace );
  14375. return array.join();
  14376. }
  14377. //
  14378. function setTexture2D( texture, slot ) {
  14379. const textureProperties = properties.get( texture );
  14380. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  14381. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  14382. const image = texture.image;
  14383. if ( image === null ) {
  14384. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  14385. } else if ( image.complete === false ) {
  14386. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  14387. } else {
  14388. uploadTexture( textureProperties, texture, slot );
  14389. return;
  14390. }
  14391. }
  14392. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14393. }
  14394. function setTexture2DArray( texture, slot ) {
  14395. const textureProperties = properties.get( texture );
  14396. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14397. uploadTexture( textureProperties, texture, slot );
  14398. return;
  14399. }
  14400. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14401. }
  14402. function setTexture3D( texture, slot ) {
  14403. const textureProperties = properties.get( texture );
  14404. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14405. uploadTexture( textureProperties, texture, slot );
  14406. return;
  14407. }
  14408. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14409. }
  14410. function setTextureCube( texture, slot ) {
  14411. const textureProperties = properties.get( texture );
  14412. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14413. uploadCubeTexture( textureProperties, texture, slot );
  14414. return;
  14415. }
  14416. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14417. }
  14418. const wrappingToGL = {
  14419. [ RepeatWrapping ]: _gl.REPEAT,
  14420. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  14421. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  14422. };
  14423. const filterToGL = {
  14424. [ NearestFilter ]: _gl.NEAREST,
  14425. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  14426. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  14427. [ LinearFilter ]: _gl.LINEAR,
  14428. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  14429. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  14430. };
  14431. const compareToGL = {
  14432. [ NeverCompare ]: _gl.NEVER,
  14433. [ AlwaysCompare ]: _gl.ALWAYS,
  14434. [ LessCompare ]: _gl.LESS,
  14435. [ LessEqualCompare ]: _gl.LEQUAL,
  14436. [ EqualCompare ]: _gl.EQUAL,
  14437. [ GreaterEqualCompare ]: _gl.GEQUAL,
  14438. [ GreaterCompare ]: _gl.GREATER,
  14439. [ NotEqualCompare ]: _gl.NOTEQUAL
  14440. };
  14441. function setTextureParameters( textureType, texture, supportsMips ) {
  14442. if ( supportsMips ) {
  14443. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  14444. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  14445. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  14446. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  14447. }
  14448. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  14449. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  14450. } else {
  14451. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14452. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14453. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  14454. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, _gl.CLAMP_TO_EDGE );
  14455. }
  14456. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  14457. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  14458. }
  14459. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14460. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14461. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  14462. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  14463. }
  14464. }
  14465. if ( texture.compareFunction ) {
  14466. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE );
  14467. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  14468. }
  14469. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  14470. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  14471. if ( texture.magFilter === NearestFilter ) return;
  14472. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  14473. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  14474. if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only
  14475. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  14476. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  14477. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  14478. }
  14479. }
  14480. }
  14481. function initTexture( textureProperties, texture ) {
  14482. let forceUpload = false;
  14483. if ( textureProperties.__webglInit === undefined ) {
  14484. textureProperties.__webglInit = true;
  14485. texture.addEventListener( 'dispose', onTextureDispose );
  14486. }
  14487. // create Source <-> WebGLTextures mapping if necessary
  14488. const source = texture.source;
  14489. let webglTextures = _sources.get( source );
  14490. if ( webglTextures === undefined ) {
  14491. webglTextures = {};
  14492. _sources.set( source, webglTextures );
  14493. }
  14494. // check if there is already a WebGLTexture object for the given texture parameters
  14495. const textureCacheKey = getTextureCacheKey( texture );
  14496. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  14497. // if not, create a new instance of WebGLTexture
  14498. if ( webglTextures[ textureCacheKey ] === undefined ) {
  14499. // create new entry
  14500. webglTextures[ textureCacheKey ] = {
  14501. texture: _gl.createTexture(),
  14502. usedTimes: 0
  14503. };
  14504. info.memory.textures ++;
  14505. // when a new instance of WebGLTexture was created, a texture upload is required
  14506. // even if the image contents are identical
  14507. forceUpload = true;
  14508. }
  14509. webglTextures[ textureCacheKey ].usedTimes ++;
  14510. // every time the texture cache key changes, it's necessary to check if an instance of
  14511. // WebGLTexture can be deleted in order to avoid a memory leak.
  14512. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  14513. if ( webglTexture !== undefined ) {
  14514. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  14515. if ( webglTexture.usedTimes === 0 ) {
  14516. deleteTexture( texture );
  14517. }
  14518. }
  14519. // store references to cache key and WebGLTexture object
  14520. textureProperties.__cacheKey = textureCacheKey;
  14521. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  14522. }
  14523. return forceUpload;
  14524. }
  14525. function uploadTexture( textureProperties, texture, slot ) {
  14526. let textureType = _gl.TEXTURE_2D;
  14527. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  14528. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  14529. const forceUpload = initTexture( textureProperties, texture );
  14530. const source = texture.source;
  14531. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14532. const sourceProperties = properties.get( source );
  14533. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14534. state.activeTexture( _gl.TEXTURE0 + slot );
  14535. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14536. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14537. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14538. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE );
  14539. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false;
  14540. let image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  14541. image = verifyColorSpace( texture, image );
  14542. const supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14543. glFormat = utils.convert( texture.format, texture.colorSpace );
  14544. let glType = utils.convert( texture.type ),
  14545. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  14546. setTextureParameters( textureType, texture, supportsMips );
  14547. let mipmap;
  14548. const mipmaps = texture.mipmaps;
  14549. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  14550. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14551. const levels = getMipLevels( texture, image, supportsMips );
  14552. if ( texture.isDepthTexture ) {
  14553. // populate depth texture with dummy data
  14554. glInternalFormat = _gl.DEPTH_COMPONENT;
  14555. if ( isWebGL2 ) {
  14556. if ( texture.type === FloatType ) {
  14557. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14558. } else if ( texture.type === UnsignedIntType ) {
  14559. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14560. } else if ( texture.type === UnsignedInt248Type ) {
  14561. glInternalFormat = _gl.DEPTH24_STENCIL8;
  14562. } else {
  14563. glInternalFormat = _gl.DEPTH_COMPONENT16; // WebGL2 requires sized internalformat for glTexImage2D
  14564. }
  14565. } else {
  14566. if ( texture.type === FloatType ) {
  14567. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  14568. }
  14569. }
  14570. // validation checks for WebGL 1
  14571. if ( texture.format === DepthFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) {
  14572. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14573. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  14574. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14575. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  14576. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  14577. texture.type = UnsignedIntType;
  14578. glType = utils.convert( texture.type );
  14579. }
  14580. }
  14581. if ( texture.format === DepthStencilFormat && glInternalFormat === _gl.DEPTH_COMPONENT ) {
  14582. // Depth stencil textures need the DEPTH_STENCIL internal format
  14583. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14584. glInternalFormat = _gl.DEPTH_STENCIL;
  14585. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14586. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  14587. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14588. if ( texture.type !== UnsignedInt248Type ) {
  14589. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  14590. texture.type = UnsignedInt248Type;
  14591. glType = utils.convert( texture.type );
  14592. }
  14593. }
  14594. //
  14595. if ( allocateMemory ) {
  14596. if ( useTexStorage ) {
  14597. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  14598. } else {
  14599. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  14600. }
  14601. }
  14602. } else if ( texture.isDataTexture ) {
  14603. // use manually created mipmaps if available
  14604. // if there are no manual mipmaps
  14605. // set 0 level mipmap and then use GL to generate other mipmap levels
  14606. if ( mipmaps.length > 0 && supportsMips ) {
  14607. if ( useTexStorage && allocateMemory ) {
  14608. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14609. }
  14610. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14611. mipmap = mipmaps[ i ];
  14612. if ( useTexStorage ) {
  14613. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14614. } else {
  14615. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14616. }
  14617. }
  14618. texture.generateMipmaps = false;
  14619. } else {
  14620. if ( useTexStorage ) {
  14621. if ( allocateMemory ) {
  14622. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14623. }
  14624. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  14625. } else {
  14626. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14627. }
  14628. }
  14629. } else if ( texture.isCompressedTexture ) {
  14630. if ( texture.isCompressedArrayTexture ) {
  14631. if ( useTexStorage && allocateMemory ) {
  14632. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  14633. }
  14634. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14635. mipmap = mipmaps[ i ];
  14636. if ( texture.format !== RGBAFormat ) {
  14637. if ( glFormat !== null ) {
  14638. if ( useTexStorage ) {
  14639. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  14640. } else {
  14641. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  14642. }
  14643. } else {
  14644. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14645. }
  14646. } else {
  14647. if ( useTexStorage ) {
  14648. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  14649. } else {
  14650. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  14651. }
  14652. }
  14653. }
  14654. } else {
  14655. if ( useTexStorage && allocateMemory ) {
  14656. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14657. }
  14658. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14659. mipmap = mipmaps[ i ];
  14660. if ( texture.format !== RGBAFormat ) {
  14661. if ( glFormat !== null ) {
  14662. if ( useTexStorage ) {
  14663. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14664. } else {
  14665. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14666. }
  14667. } else {
  14668. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14669. }
  14670. } else {
  14671. if ( useTexStorage ) {
  14672. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14673. } else {
  14674. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14675. }
  14676. }
  14677. }
  14678. }
  14679. } else if ( texture.isDataArrayTexture ) {
  14680. if ( useTexStorage ) {
  14681. if ( allocateMemory ) {
  14682. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  14683. }
  14684. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14685. } else {
  14686. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14687. }
  14688. } else if ( texture.isData3DTexture ) {
  14689. if ( useTexStorage ) {
  14690. if ( allocateMemory ) {
  14691. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  14692. }
  14693. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14694. } else {
  14695. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14696. }
  14697. } else if ( texture.isFramebufferTexture ) {
  14698. if ( allocateMemory ) {
  14699. if ( useTexStorage ) {
  14700. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14701. } else {
  14702. let width = image.width, height = image.height;
  14703. for ( let i = 0; i < levels; i ++ ) {
  14704. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  14705. width >>= 1;
  14706. height >>= 1;
  14707. }
  14708. }
  14709. }
  14710. } else {
  14711. // regular Texture (image, video, canvas)
  14712. // use manually created mipmaps if available
  14713. // if there are no manual mipmaps
  14714. // set 0 level mipmap and then use GL to generate other mipmap levels
  14715. if ( mipmaps.length > 0 && supportsMips ) {
  14716. if ( useTexStorage && allocateMemory ) {
  14717. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14718. }
  14719. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14720. mipmap = mipmaps[ i ];
  14721. if ( useTexStorage ) {
  14722. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  14723. } else {
  14724. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  14725. }
  14726. }
  14727. texture.generateMipmaps = false;
  14728. } else {
  14729. if ( useTexStorage ) {
  14730. if ( allocateMemory ) {
  14731. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  14732. }
  14733. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  14734. } else {
  14735. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  14736. }
  14737. }
  14738. }
  14739. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14740. generateMipmap( textureType );
  14741. }
  14742. sourceProperties.__version = source.version;
  14743. if ( texture.onUpdate ) texture.onUpdate( texture );
  14744. }
  14745. textureProperties.__version = texture.version;
  14746. }
  14747. function uploadCubeTexture( textureProperties, texture, slot ) {
  14748. if ( texture.image.length !== 6 ) return;
  14749. const forceUpload = initTexture( textureProperties, texture );
  14750. const source = texture.source;
  14751. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  14752. const sourceProperties = properties.get( source );
  14753. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14754. state.activeTexture( _gl.TEXTURE0 + slot );
  14755. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14756. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14757. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14758. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, _gl.NONE );
  14759. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  14760. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  14761. const cubeImage = [];
  14762. for ( let i = 0; i < 6; i ++ ) {
  14763. if ( ! isCompressed && ! isDataTexture ) {
  14764. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  14765. } else {
  14766. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  14767. }
  14768. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  14769. }
  14770. const image = cubeImage[ 0 ],
  14771. supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14772. glFormat = utils.convert( texture.format, texture.colorSpace ),
  14773. glType = utils.convert( texture.type ),
  14774. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  14775. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  14776. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14777. let levels = getMipLevels( texture, image, supportsMips );
  14778. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips );
  14779. let mipmaps;
  14780. if ( isCompressed ) {
  14781. if ( useTexStorage && allocateMemory ) {
  14782. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  14783. }
  14784. for ( let i = 0; i < 6; i ++ ) {
  14785. mipmaps = cubeImage[ i ].mipmaps;
  14786. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14787. const mipmap = mipmaps[ j ];
  14788. if ( texture.format !== RGBAFormat ) {
  14789. if ( glFormat !== null ) {
  14790. if ( useTexStorage ) {
  14791. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14792. } else {
  14793. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14794. }
  14795. } else {
  14796. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  14797. }
  14798. } else {
  14799. if ( useTexStorage ) {
  14800. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14801. } else {
  14802. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14803. }
  14804. }
  14805. }
  14806. }
  14807. } else {
  14808. mipmaps = texture.mipmaps;
  14809. if ( useTexStorage && allocateMemory ) {
  14810. // TODO: Uniformly handle mipmap definitions
  14811. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  14812. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  14813. if ( mipmaps.length > 0 ) levels ++;
  14814. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height );
  14815. }
  14816. for ( let i = 0; i < 6; i ++ ) {
  14817. if ( isDataTexture ) {
  14818. if ( useTexStorage ) {
  14819. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  14820. } else {
  14821. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  14822. }
  14823. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14824. const mipmap = mipmaps[ j ];
  14825. const mipmapImage = mipmap.image[ i ].image;
  14826. if ( useTexStorage ) {
  14827. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  14828. } else {
  14829. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  14830. }
  14831. }
  14832. } else {
  14833. if ( useTexStorage ) {
  14834. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  14835. } else {
  14836. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  14837. }
  14838. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14839. const mipmap = mipmaps[ j ];
  14840. if ( useTexStorage ) {
  14841. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  14842. } else {
  14843. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  14844. }
  14845. }
  14846. }
  14847. }
  14848. }
  14849. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14850. // We assume images for cube map have the same size.
  14851. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14852. }
  14853. sourceProperties.__version = source.version;
  14854. if ( texture.onUpdate ) texture.onUpdate( texture );
  14855. }
  14856. textureProperties.__version = texture.version;
  14857. }
  14858. // Render targets
  14859. // Setup storage for target texture and bind it to correct framebuffer
  14860. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) {
  14861. const glFormat = utils.convert( texture.format, texture.colorSpace );
  14862. const glType = utils.convert( texture.type );
  14863. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  14864. const renderTargetProperties = properties.get( renderTarget );
  14865. if ( ! renderTargetProperties.__hasExternalTextures ) {
  14866. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  14867. state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null );
  14868. } else {
  14869. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14870. }
  14871. }
  14872. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14873. if ( useMultisampledRTT( renderTarget ) ) {
  14874. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  14875. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  14876. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 );
  14877. }
  14878. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14879. }
  14880. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14881. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  14882. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  14883. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14884. let glInternalFormat = _gl.DEPTH_COMPONENT16;
  14885. if ( isMultisample || useMultisampledRTT( renderTarget ) ) {
  14886. const depthTexture = renderTarget.depthTexture;
  14887. if ( depthTexture && depthTexture.isDepthTexture ) {
  14888. if ( depthTexture.type === FloatType ) {
  14889. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  14890. } else if ( depthTexture.type === UnsignedIntType ) {
  14891. glInternalFormat = _gl.DEPTH_COMPONENT24;
  14892. }
  14893. }
  14894. const samples = getRenderTargetSamples( renderTarget );
  14895. if ( useMultisampledRTT( renderTarget ) ) {
  14896. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14897. } else {
  14898. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14899. }
  14900. } else {
  14901. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  14902. }
  14903. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14904. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14905. const samples = getRenderTargetSamples( renderTarget );
  14906. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14907. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height );
  14908. } else if ( useMultisampledRTT( renderTarget ) ) {
  14909. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, _gl.DEPTH24_STENCIL8, renderTarget.width, renderTarget.height );
  14910. } else {
  14911. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  14912. }
  14913. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14914. } else {
  14915. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14916. for ( let i = 0; i < textures.length; i ++ ) {
  14917. const texture = textures[ i ];
  14918. const glFormat = utils.convert( texture.format, texture.colorSpace );
  14919. const glType = utils.convert( texture.type );
  14920. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  14921. const samples = getRenderTargetSamples( renderTarget );
  14922. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14923. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14924. } else if ( useMultisampledRTT( renderTarget ) ) {
  14925. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14926. } else {
  14927. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  14928. }
  14929. }
  14930. }
  14931. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  14932. }
  14933. // Setup resources for a Depth Texture for a FBO (needs an extension)
  14934. function setupDepthTexture( framebuffer, renderTarget ) {
  14935. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  14936. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  14937. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14938. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  14939. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  14940. }
  14941. // upload an empty depth texture with framebuffer size
  14942. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  14943. renderTarget.depthTexture.image.width !== renderTarget.width ||
  14944. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  14945. renderTarget.depthTexture.image.width = renderTarget.width;
  14946. renderTarget.depthTexture.image.height = renderTarget.height;
  14947. renderTarget.depthTexture.needsUpdate = true;
  14948. }
  14949. setTexture2D( renderTarget.depthTexture, 0 );
  14950. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  14951. const samples = getRenderTargetSamples( renderTarget );
  14952. if ( renderTarget.depthTexture.format === DepthFormat ) {
  14953. if ( useMultisampledRTT( renderTarget ) ) {
  14954. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  14955. } else {
  14956. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  14957. }
  14958. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  14959. if ( useMultisampledRTT( renderTarget ) ) {
  14960. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0, samples );
  14961. } else {
  14962. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  14963. }
  14964. } else {
  14965. throw new Error( 'Unknown depthTexture format' );
  14966. }
  14967. }
  14968. // Setup GL resources for a non-texture depth buffer
  14969. function setupDepthRenderbuffer( renderTarget ) {
  14970. const renderTargetProperties = properties.get( renderTarget );
  14971. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14972. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  14973. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  14974. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  14975. } else {
  14976. if ( isCube ) {
  14977. renderTargetProperties.__webglDepthbuffer = [];
  14978. for ( let i = 0; i < 6; i ++ ) {
  14979. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  14980. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  14981. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  14982. }
  14983. } else {
  14984. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  14985. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14986. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  14987. }
  14988. }
  14989. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14990. }
  14991. // rebind framebuffer with external textures
  14992. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  14993. const renderTargetProperties = properties.get( renderTarget );
  14994. if ( colorTexture !== undefined ) {
  14995. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  14996. }
  14997. if ( depthTexture !== undefined ) {
  14998. setupDepthRenderbuffer( renderTarget );
  14999. }
  15000. }
  15001. // Set up GL resources for the render target
  15002. function setupRenderTarget( renderTarget ) {
  15003. const texture = renderTarget.texture;
  15004. const renderTargetProperties = properties.get( renderTarget );
  15005. const textureProperties = properties.get( texture );
  15006. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15007. if ( renderTarget.isWebGLMultipleRenderTargets !== true ) {
  15008. if ( textureProperties.__webglTexture === undefined ) {
  15009. textureProperties.__webglTexture = _gl.createTexture();
  15010. }
  15011. textureProperties.__version = texture.version;
  15012. info.memory.textures ++;
  15013. }
  15014. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  15015. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  15016. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  15017. // Setup framebuffer
  15018. if ( isCube ) {
  15019. renderTargetProperties.__webglFramebuffer = [];
  15020. for ( let i = 0; i < 6; i ++ ) {
  15021. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15022. }
  15023. } else {
  15024. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  15025. if ( isMultipleRenderTargets ) {
  15026. if ( capabilities.drawBuffers ) {
  15027. const textures = renderTarget.texture;
  15028. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15029. const attachmentProperties = properties.get( textures[ i ] );
  15030. if ( attachmentProperties.__webglTexture === undefined ) {
  15031. attachmentProperties.__webglTexture = _gl.createTexture();
  15032. info.memory.textures ++;
  15033. }
  15034. }
  15035. } else {
  15036. console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' );
  15037. }
  15038. }
  15039. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  15040. const textures = isMultipleRenderTargets ? texture : [ texture ];
  15041. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  15042. renderTargetProperties.__webglColorRenderbuffer = [];
  15043. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15044. for ( let i = 0; i < textures.length; i ++ ) {
  15045. const texture = textures[ i ];
  15046. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  15047. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15048. const glFormat = utils.convert( texture.format, texture.colorSpace );
  15049. const glType = utils.convert( texture.type );
  15050. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );
  15051. const samples = getRenderTargetSamples( renderTarget );
  15052. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  15053. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15054. }
  15055. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15056. if ( renderTarget.depthBuffer ) {
  15057. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  15058. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  15059. }
  15060. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15061. }
  15062. }
  15063. // Setup color buffer
  15064. if ( isCube ) {
  15065. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  15066. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, supportsMips );
  15067. for ( let i = 0; i < 6; i ++ ) {
  15068. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15069. }
  15070. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  15071. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15072. }
  15073. state.unbindTexture();
  15074. } else if ( isMultipleRenderTargets ) {
  15075. const textures = renderTarget.texture;
  15076. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15077. const attachment = textures[ i ];
  15078. const attachmentProperties = properties.get( attachment );
  15079. state.bindTexture( _gl.TEXTURE_2D, attachmentProperties.__webglTexture );
  15080. setTextureParameters( _gl.TEXTURE_2D, attachment, supportsMips );
  15081. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D );
  15082. if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) {
  15083. generateMipmap( _gl.TEXTURE_2D );
  15084. }
  15085. }
  15086. state.unbindTexture();
  15087. } else {
  15088. let glTextureType = _gl.TEXTURE_2D;
  15089. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  15090. if ( isWebGL2 ) {
  15091. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  15092. } else {
  15093. console.error( 'THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.' );
  15094. }
  15095. }
  15096. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  15097. setTextureParameters( glTextureType, texture, supportsMips );
  15098. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType );
  15099. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  15100. generateMipmap( glTextureType );
  15101. }
  15102. state.unbindTexture();
  15103. }
  15104. // Setup depth and stencil buffers
  15105. if ( renderTarget.depthBuffer ) {
  15106. setupDepthRenderbuffer( renderTarget );
  15107. }
  15108. }
  15109. function updateRenderTargetMipmap( renderTarget ) {
  15110. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  15111. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  15112. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  15113. const texture = textures[ i ];
  15114. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  15115. const target = renderTarget.isWebGLCubeRenderTarget ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  15116. const webglTexture = properties.get( texture ).__webglTexture;
  15117. state.bindTexture( target, webglTexture );
  15118. generateMipmap( target );
  15119. state.unbindTexture();
  15120. }
  15121. }
  15122. }
  15123. function updateMultisampleRenderTarget( renderTarget ) {
  15124. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  15125. const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [ renderTarget.texture ];
  15126. const width = renderTarget.width;
  15127. const height = renderTarget.height;
  15128. let mask = _gl.COLOR_BUFFER_BIT;
  15129. const invalidationArray = [];
  15130. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  15131. const renderTargetProperties = properties.get( renderTarget );
  15132. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  15133. // If MRT we need to remove FBO attachments
  15134. if ( isMultipleRenderTargets ) {
  15135. for ( let i = 0; i < textures.length; i ++ ) {
  15136. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15137. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  15138. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15139. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  15140. }
  15141. }
  15142. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15143. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15144. for ( let i = 0; i < textures.length; i ++ ) {
  15145. invalidationArray.push( _gl.COLOR_ATTACHMENT0 + i );
  15146. if ( renderTarget.depthBuffer ) {
  15147. invalidationArray.push( depthStyle );
  15148. }
  15149. const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false;
  15150. if ( ignoreDepthValues === false ) {
  15151. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  15152. if ( renderTarget.stencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  15153. }
  15154. if ( isMultipleRenderTargets ) {
  15155. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15156. }
  15157. if ( ignoreDepthValues === true ) {
  15158. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, [ depthStyle ] );
  15159. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  15160. }
  15161. if ( isMultipleRenderTargets ) {
  15162. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  15163. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  15164. }
  15165. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  15166. if ( supportsInvalidateFramebuffer ) {
  15167. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArray );
  15168. }
  15169. }
  15170. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  15171. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  15172. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  15173. if ( isMultipleRenderTargets ) {
  15174. for ( let i = 0; i < textures.length; i ++ ) {
  15175. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15176. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  15177. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  15178. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15179. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  15180. }
  15181. }
  15182. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  15183. }
  15184. }
  15185. function getRenderTargetSamples( renderTarget ) {
  15186. return Math.min( maxSamples, renderTarget.samples );
  15187. }
  15188. function useMultisampledRTT( renderTarget ) {
  15189. const renderTargetProperties = properties.get( renderTarget );
  15190. return isWebGL2 && renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  15191. }
  15192. function updateVideoTexture( texture ) {
  15193. const frame = info.render.frame;
  15194. // Check the last frame we updated the VideoTexture
  15195. if ( _videoTextures.get( texture ) !== frame ) {
  15196. _videoTextures.set( texture, frame );
  15197. texture.update();
  15198. }
  15199. }
  15200. function verifyColorSpace( texture, image ) {
  15201. const colorSpace = texture.colorSpace;
  15202. const format = texture.format;
  15203. const type = texture.type;
  15204. if ( texture.isCompressedTexture === true || texture.format === _SRGBAFormat ) return image;
  15205. if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {
  15206. // sRGB
  15207. if ( colorSpace === SRGBColorSpace ) {
  15208. if ( isWebGL2 === false ) {
  15209. // in WebGL 1, try to use EXT_sRGB extension and unsized formats
  15210. if ( extensions.has( 'EXT_sRGB' ) === true && format === RGBAFormat ) {
  15211. texture.format = _SRGBAFormat;
  15212. // it's not possible to generate mips in WebGL 1 with this extension
  15213. texture.minFilter = LinearFilter;
  15214. texture.generateMipmaps = false;
  15215. } else {
  15216. // slow fallback (CPU decode)
  15217. image = ImageUtils.sRGBToLinear( image );
  15218. }
  15219. } else {
  15220. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  15221. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  15222. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  15223. }
  15224. }
  15225. } else {
  15226. console.error( 'THREE.WebGLTextures: Unsupported texture color space:', colorSpace );
  15227. }
  15228. }
  15229. return image;
  15230. }
  15231. //
  15232. this.allocateTextureUnit = allocateTextureUnit;
  15233. this.resetTextureUnits = resetTextureUnits;
  15234. this.setTexture2D = setTexture2D;
  15235. this.setTexture2DArray = setTexture2DArray;
  15236. this.setTexture3D = setTexture3D;
  15237. this.setTextureCube = setTextureCube;
  15238. this.rebindTextures = rebindTextures;
  15239. this.setupRenderTarget = setupRenderTarget;
  15240. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  15241. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  15242. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  15243. this.setupFrameBufferTexture = setupFrameBufferTexture;
  15244. this.useMultisampledRTT = useMultisampledRTT;
  15245. }
  15246. function WebGLUtils( gl, extensions, capabilities ) {
  15247. const isWebGL2 = capabilities.isWebGL2;
  15248. function convert( p, colorSpace = NoColorSpace ) {
  15249. let extension;
  15250. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  15251. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  15252. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  15253. if ( p === ByteType ) return gl.BYTE;
  15254. if ( p === ShortType ) return gl.SHORT;
  15255. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  15256. if ( p === IntType ) return gl.INT;
  15257. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  15258. if ( p === FloatType ) return gl.FLOAT;
  15259. if ( p === HalfFloatType ) {
  15260. if ( isWebGL2 ) return gl.HALF_FLOAT;
  15261. extension = extensions.get( 'OES_texture_half_float' );
  15262. if ( extension !== null ) {
  15263. return extension.HALF_FLOAT_OES;
  15264. } else {
  15265. return null;
  15266. }
  15267. }
  15268. if ( p === AlphaFormat ) return gl.ALPHA;
  15269. if ( p === RGBAFormat ) return gl.RGBA;
  15270. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  15271. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  15272. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  15273. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  15274. // WebGL 1 sRGB fallback
  15275. if ( p === _SRGBAFormat ) {
  15276. extension = extensions.get( 'EXT_sRGB' );
  15277. if ( extension !== null ) {
  15278. return extension.SRGB_ALPHA_EXT;
  15279. } else {
  15280. return null;
  15281. }
  15282. }
  15283. // WebGL2 formats.
  15284. if ( p === RedFormat ) return gl.RED;
  15285. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  15286. if ( p === RGFormat ) return gl.RG;
  15287. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  15288. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  15289. // S3TC
  15290. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  15291. if ( colorSpace === SRGBColorSpace ) {
  15292. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  15293. if ( extension !== null ) {
  15294. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  15295. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  15296. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  15297. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  15298. } else {
  15299. return null;
  15300. }
  15301. } else {
  15302. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  15303. if ( extension !== null ) {
  15304. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15305. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15306. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15307. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15308. } else {
  15309. return null;
  15310. }
  15311. }
  15312. }
  15313. // PVRTC
  15314. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  15315. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  15316. if ( extension !== null ) {
  15317. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  15318. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  15319. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  15320. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  15321. } else {
  15322. return null;
  15323. }
  15324. }
  15325. // ETC1
  15326. if ( p === RGB_ETC1_Format ) {
  15327. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  15328. if ( extension !== null ) {
  15329. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  15330. } else {
  15331. return null;
  15332. }
  15333. }
  15334. // ETC2
  15335. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  15336. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  15337. if ( extension !== null ) {
  15338. if ( p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  15339. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  15340. } else {
  15341. return null;
  15342. }
  15343. }
  15344. // ASTC
  15345. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  15346. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  15347. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  15348. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  15349. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  15350. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  15351. if ( extension !== null ) {
  15352. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  15353. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  15354. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  15355. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  15356. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  15357. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  15358. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  15359. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  15360. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  15361. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  15362. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  15363. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  15364. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  15365. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  15366. } else {
  15367. return null;
  15368. }
  15369. }
  15370. // BPTC
  15371. if ( p === RGBA_BPTC_Format ) {
  15372. extension = extensions.get( 'EXT_texture_compression_bptc' );
  15373. if ( extension !== null ) {
  15374. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  15375. } else {
  15376. return null;
  15377. }
  15378. }
  15379. // RGTC
  15380. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  15381. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  15382. if ( extension !== null ) {
  15383. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  15384. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  15385. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  15386. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  15387. } else {
  15388. return null;
  15389. }
  15390. }
  15391. //
  15392. if ( p === UnsignedInt248Type ) {
  15393. if ( isWebGL2 ) return gl.UNSIGNED_INT_24_8;
  15394. extension = extensions.get( 'WEBGL_depth_texture' );
  15395. if ( extension !== null ) {
  15396. return extension.UNSIGNED_INT_24_8_WEBGL;
  15397. } else {
  15398. return null;
  15399. }
  15400. }
  15401. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  15402. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  15403. }
  15404. return { convert: convert };
  15405. }
  15406. class ArrayCamera extends PerspectiveCamera {
  15407. constructor( array = [] ) {
  15408. super();
  15409. this.isArrayCamera = true;
  15410. this.cameras = array;
  15411. }
  15412. }
  15413. class Group extends Object3D {
  15414. constructor() {
  15415. super();
  15416. this.isGroup = true;
  15417. this.type = 'Group';
  15418. }
  15419. }
  15420. const _moveEvent = { type: 'move' };
  15421. class WebXRController {
  15422. constructor() {
  15423. this._targetRay = null;
  15424. this._grip = null;
  15425. this._hand = null;
  15426. }
  15427. getHandSpace() {
  15428. if ( this._hand === null ) {
  15429. this._hand = new Group();
  15430. this._hand.matrixAutoUpdate = false;
  15431. this._hand.visible = false;
  15432. this._hand.joints = {};
  15433. this._hand.inputState = { pinching: false };
  15434. }
  15435. return this._hand;
  15436. }
  15437. getTargetRaySpace() {
  15438. if ( this._targetRay === null ) {
  15439. this._targetRay = new Group();
  15440. this._targetRay.matrixAutoUpdate = false;
  15441. this._targetRay.visible = false;
  15442. this._targetRay.hasLinearVelocity = false;
  15443. this._targetRay.linearVelocity = new Vector3();
  15444. this._targetRay.hasAngularVelocity = false;
  15445. this._targetRay.angularVelocity = new Vector3();
  15446. }
  15447. return this._targetRay;
  15448. }
  15449. getGripSpace() {
  15450. if ( this._grip === null ) {
  15451. this._grip = new Group();
  15452. this._grip.matrixAutoUpdate = false;
  15453. this._grip.visible = false;
  15454. this._grip.hasLinearVelocity = false;
  15455. this._grip.linearVelocity = new Vector3();
  15456. this._grip.hasAngularVelocity = false;
  15457. this._grip.angularVelocity = new Vector3();
  15458. }
  15459. return this._grip;
  15460. }
  15461. dispatchEvent( event ) {
  15462. if ( this._targetRay !== null ) {
  15463. this._targetRay.dispatchEvent( event );
  15464. }
  15465. if ( this._grip !== null ) {
  15466. this._grip.dispatchEvent( event );
  15467. }
  15468. if ( this._hand !== null ) {
  15469. this._hand.dispatchEvent( event );
  15470. }
  15471. return this;
  15472. }
  15473. connect( inputSource ) {
  15474. if ( inputSource && inputSource.hand ) {
  15475. const hand = this._hand;
  15476. if ( hand ) {
  15477. for ( const inputjoint of inputSource.hand.values() ) {
  15478. // Initialize hand with joints when connected
  15479. this._getHandJoint( hand, inputjoint );
  15480. }
  15481. }
  15482. }
  15483. this.dispatchEvent( { type: 'connected', data: inputSource } );
  15484. return this;
  15485. }
  15486. disconnect( inputSource ) {
  15487. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  15488. if ( this._targetRay !== null ) {
  15489. this._targetRay.visible = false;
  15490. }
  15491. if ( this._grip !== null ) {
  15492. this._grip.visible = false;
  15493. }
  15494. if ( this._hand !== null ) {
  15495. this._hand.visible = false;
  15496. }
  15497. return this;
  15498. }
  15499. update( inputSource, frame, referenceSpace ) {
  15500. let inputPose = null;
  15501. let gripPose = null;
  15502. let handPose = null;
  15503. const targetRay = this._targetRay;
  15504. const grip = this._grip;
  15505. const hand = this._hand;
  15506. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  15507. if ( hand && inputSource.hand ) {
  15508. handPose = true;
  15509. for ( const inputjoint of inputSource.hand.values() ) {
  15510. // Update the joints groups with the XRJoint poses
  15511. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  15512. // The transform of this joint will be updated with the joint pose on each frame
  15513. const joint = this._getHandJoint( hand, inputjoint );
  15514. if ( jointPose !== null ) {
  15515. joint.matrix.fromArray( jointPose.transform.matrix );
  15516. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  15517. joint.matrixWorldNeedsUpdate = true;
  15518. joint.jointRadius = jointPose.radius;
  15519. }
  15520. joint.visible = jointPose !== null;
  15521. }
  15522. // Custom events
  15523. // Check pinchz
  15524. const indexTip = hand.joints[ 'index-finger-tip' ];
  15525. const thumbTip = hand.joints[ 'thumb-tip' ];
  15526. const distance = indexTip.position.distanceTo( thumbTip.position );
  15527. const distanceToPinch = 0.02;
  15528. const threshold = 0.005;
  15529. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  15530. hand.inputState.pinching = false;
  15531. this.dispatchEvent( {
  15532. type: 'pinchend',
  15533. handedness: inputSource.handedness,
  15534. target: this
  15535. } );
  15536. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  15537. hand.inputState.pinching = true;
  15538. this.dispatchEvent( {
  15539. type: 'pinchstart',
  15540. handedness: inputSource.handedness,
  15541. target: this
  15542. } );
  15543. }
  15544. } else {
  15545. if ( grip !== null && inputSource.gripSpace ) {
  15546. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  15547. if ( gripPose !== null ) {
  15548. grip.matrix.fromArray( gripPose.transform.matrix );
  15549. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  15550. grip.matrixWorldNeedsUpdate = true;
  15551. if ( gripPose.linearVelocity ) {
  15552. grip.hasLinearVelocity = true;
  15553. grip.linearVelocity.copy( gripPose.linearVelocity );
  15554. } else {
  15555. grip.hasLinearVelocity = false;
  15556. }
  15557. if ( gripPose.angularVelocity ) {
  15558. grip.hasAngularVelocity = true;
  15559. grip.angularVelocity.copy( gripPose.angularVelocity );
  15560. } else {
  15561. grip.hasAngularVelocity = false;
  15562. }
  15563. }
  15564. }
  15565. }
  15566. if ( targetRay !== null ) {
  15567. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  15568. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  15569. if ( inputPose === null && gripPose !== null ) {
  15570. inputPose = gripPose;
  15571. }
  15572. if ( inputPose !== null ) {
  15573. targetRay.matrix.fromArray( inputPose.transform.matrix );
  15574. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  15575. targetRay.matrixWorldNeedsUpdate = true;
  15576. if ( inputPose.linearVelocity ) {
  15577. targetRay.hasLinearVelocity = true;
  15578. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  15579. } else {
  15580. targetRay.hasLinearVelocity = false;
  15581. }
  15582. if ( inputPose.angularVelocity ) {
  15583. targetRay.hasAngularVelocity = true;
  15584. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  15585. } else {
  15586. targetRay.hasAngularVelocity = false;
  15587. }
  15588. this.dispatchEvent( _moveEvent );
  15589. }
  15590. }
  15591. }
  15592. if ( targetRay !== null ) {
  15593. targetRay.visible = ( inputPose !== null );
  15594. }
  15595. if ( grip !== null ) {
  15596. grip.visible = ( gripPose !== null );
  15597. }
  15598. if ( hand !== null ) {
  15599. hand.visible = ( handPose !== null );
  15600. }
  15601. return this;
  15602. }
  15603. // private method
  15604. _getHandJoint( hand, inputjoint ) {
  15605. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  15606. const joint = new Group();
  15607. joint.matrixAutoUpdate = false;
  15608. joint.visible = false;
  15609. hand.joints[ inputjoint.jointName ] = joint;
  15610. hand.add( joint );
  15611. }
  15612. return hand.joints[ inputjoint.jointName ];
  15613. }
  15614. }
  15615. class DepthTexture extends Texture {
  15616. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  15617. format = format !== undefined ? format : DepthFormat;
  15618. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  15619. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  15620. }
  15621. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  15622. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  15623. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  15624. this.isDepthTexture = true;
  15625. this.image = { width: width, height: height };
  15626. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  15627. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  15628. this.flipY = false;
  15629. this.generateMipmaps = false;
  15630. this.compareFunction = null;
  15631. }
  15632. copy( source ) {
  15633. super.copy( source );
  15634. this.compareFunction = source.compareFunction;
  15635. return this;
  15636. }
  15637. toJSON( meta ) {
  15638. const data = super.toJSON( meta );
  15639. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  15640. return data;
  15641. }
  15642. }
  15643. class WebXRManager extends EventDispatcher {
  15644. constructor( renderer, gl ) {
  15645. super();
  15646. const scope = this;
  15647. let session = null;
  15648. let framebufferScaleFactor = 1.0;
  15649. let referenceSpace = null;
  15650. let referenceSpaceType = 'local-floor';
  15651. // Set default foveation to maximum.
  15652. let foveation = 1.0;
  15653. let customReferenceSpace = null;
  15654. let pose = null;
  15655. let glBinding = null;
  15656. let glProjLayer = null;
  15657. let glBaseLayer = null;
  15658. let xrFrame = null;
  15659. const attributes = gl.getContextAttributes();
  15660. let initialRenderTarget = null;
  15661. let newRenderTarget = null;
  15662. const controllers = [];
  15663. const controllerInputSources = [];
  15664. //
  15665. const cameraL = new PerspectiveCamera();
  15666. cameraL.layers.enable( 1 );
  15667. cameraL.viewport = new Vector4();
  15668. const cameraR = new PerspectiveCamera();
  15669. cameraR.layers.enable( 2 );
  15670. cameraR.viewport = new Vector4();
  15671. const cameras = [ cameraL, cameraR ];
  15672. const cameraXR = new ArrayCamera();
  15673. cameraXR.layers.enable( 1 );
  15674. cameraXR.layers.enable( 2 );
  15675. let _currentDepthNear = null;
  15676. let _currentDepthFar = null;
  15677. //
  15678. this.cameraAutoUpdate = true;
  15679. this.enabled = false;
  15680. this.isPresenting = false;
  15681. this.getController = function ( index ) {
  15682. let controller = controllers[ index ];
  15683. if ( controller === undefined ) {
  15684. controller = new WebXRController();
  15685. controllers[ index ] = controller;
  15686. }
  15687. return controller.getTargetRaySpace();
  15688. };
  15689. this.getControllerGrip = function ( index ) {
  15690. let controller = controllers[ index ];
  15691. if ( controller === undefined ) {
  15692. controller = new WebXRController();
  15693. controllers[ index ] = controller;
  15694. }
  15695. return controller.getGripSpace();
  15696. };
  15697. this.getHand = function ( index ) {
  15698. let controller = controllers[ index ];
  15699. if ( controller === undefined ) {
  15700. controller = new WebXRController();
  15701. controllers[ index ] = controller;
  15702. }
  15703. return controller.getHandSpace();
  15704. };
  15705. //
  15706. function onSessionEvent( event ) {
  15707. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  15708. if ( controllerIndex === - 1 ) {
  15709. return;
  15710. }
  15711. const controller = controllers[ controllerIndex ];
  15712. if ( controller !== undefined ) {
  15713. controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );
  15714. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  15715. }
  15716. }
  15717. function onSessionEnd() {
  15718. session.removeEventListener( 'select', onSessionEvent );
  15719. session.removeEventListener( 'selectstart', onSessionEvent );
  15720. session.removeEventListener( 'selectend', onSessionEvent );
  15721. session.removeEventListener( 'squeeze', onSessionEvent );
  15722. session.removeEventListener( 'squeezestart', onSessionEvent );
  15723. session.removeEventListener( 'squeezeend', onSessionEvent );
  15724. session.removeEventListener( 'end', onSessionEnd );
  15725. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  15726. for ( let i = 0; i < controllers.length; i ++ ) {
  15727. const inputSource = controllerInputSources[ i ];
  15728. if ( inputSource === null ) continue;
  15729. controllerInputSources[ i ] = null;
  15730. controllers[ i ].disconnect( inputSource );
  15731. }
  15732. _currentDepthNear = null;
  15733. _currentDepthFar = null;
  15734. // restore framebuffer/rendering state
  15735. renderer.setRenderTarget( initialRenderTarget );
  15736. glBaseLayer = null;
  15737. glProjLayer = null;
  15738. glBinding = null;
  15739. session = null;
  15740. newRenderTarget = null;
  15741. //
  15742. animation.stop();
  15743. scope.isPresenting = false;
  15744. scope.dispatchEvent( { type: 'sessionend' } );
  15745. }
  15746. this.setFramebufferScaleFactor = function ( value ) {
  15747. framebufferScaleFactor = value;
  15748. if ( scope.isPresenting === true ) {
  15749. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  15750. }
  15751. };
  15752. this.setReferenceSpaceType = function ( value ) {
  15753. referenceSpaceType = value;
  15754. if ( scope.isPresenting === true ) {
  15755. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  15756. }
  15757. };
  15758. this.getReferenceSpace = function () {
  15759. return customReferenceSpace || referenceSpace;
  15760. };
  15761. this.setReferenceSpace = function ( space ) {
  15762. customReferenceSpace = space;
  15763. };
  15764. this.getBaseLayer = function () {
  15765. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  15766. };
  15767. this.getBinding = function () {
  15768. return glBinding;
  15769. };
  15770. this.getFrame = function () {
  15771. return xrFrame;
  15772. };
  15773. this.getSession = function () {
  15774. return session;
  15775. };
  15776. this.setSession = async function ( value ) {
  15777. session = value;
  15778. if ( session !== null ) {
  15779. initialRenderTarget = renderer.getRenderTarget();
  15780. session.addEventListener( 'select', onSessionEvent );
  15781. session.addEventListener( 'selectstart', onSessionEvent );
  15782. session.addEventListener( 'selectend', onSessionEvent );
  15783. session.addEventListener( 'squeeze', onSessionEvent );
  15784. session.addEventListener( 'squeezestart', onSessionEvent );
  15785. session.addEventListener( 'squeezeend', onSessionEvent );
  15786. session.addEventListener( 'end', onSessionEnd );
  15787. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  15788. if ( attributes.xrCompatible !== true ) {
  15789. await gl.makeXRCompatible();
  15790. }
  15791. if ( ( session.renderState.layers === undefined ) || ( renderer.capabilities.isWebGL2 === false ) ) {
  15792. const layerInit = {
  15793. antialias: ( session.renderState.layers === undefined ) ? attributes.antialias : true,
  15794. alpha: true,
  15795. depth: attributes.depth,
  15796. stencil: attributes.stencil,
  15797. framebufferScaleFactor: framebufferScaleFactor
  15798. };
  15799. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  15800. session.updateRenderState( { baseLayer: glBaseLayer } );
  15801. newRenderTarget = new WebGLRenderTarget(
  15802. glBaseLayer.framebufferWidth,
  15803. glBaseLayer.framebufferHeight,
  15804. {
  15805. format: RGBAFormat,
  15806. type: UnsignedByteType,
  15807. colorSpace: renderer.outputColorSpace,
  15808. stencilBuffer: attributes.stencil
  15809. }
  15810. );
  15811. } else {
  15812. let depthFormat = null;
  15813. let depthType = null;
  15814. let glDepthFormat = null;
  15815. if ( attributes.depth ) {
  15816. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  15817. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  15818. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  15819. }
  15820. const projectionlayerInit = {
  15821. colorFormat: gl.RGBA8,
  15822. depthFormat: glDepthFormat,
  15823. scaleFactor: framebufferScaleFactor
  15824. };
  15825. glBinding = new XRWebGLBinding( session, gl );
  15826. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  15827. session.updateRenderState( { layers: [ glProjLayer ] } );
  15828. newRenderTarget = new WebGLRenderTarget(
  15829. glProjLayer.textureWidth,
  15830. glProjLayer.textureHeight,
  15831. {
  15832. format: RGBAFormat,
  15833. type: UnsignedByteType,
  15834. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  15835. stencilBuffer: attributes.stencil,
  15836. colorSpace: renderer.outputColorSpace,
  15837. samples: attributes.antialias ? 4 : 0
  15838. } );
  15839. const renderTargetProperties = renderer.properties.get( newRenderTarget );
  15840. renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues;
  15841. }
  15842. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  15843. this.setFoveation( foveation );
  15844. customReferenceSpace = null;
  15845. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  15846. animation.setContext( session );
  15847. animation.start();
  15848. scope.isPresenting = true;
  15849. scope.dispatchEvent( { type: 'sessionstart' } );
  15850. }
  15851. };
  15852. this.getEnvironmentBlendMode = function () {
  15853. if ( session !== null ) {
  15854. return session.environmentBlendMode;
  15855. }
  15856. };
  15857. function onInputSourcesChange( event ) {
  15858. // Notify disconnected
  15859. for ( let i = 0; i < event.removed.length; i ++ ) {
  15860. const inputSource = event.removed[ i ];
  15861. const index = controllerInputSources.indexOf( inputSource );
  15862. if ( index >= 0 ) {
  15863. controllerInputSources[ index ] = null;
  15864. controllers[ index ].disconnect( inputSource );
  15865. }
  15866. }
  15867. // Notify connected
  15868. for ( let i = 0; i < event.added.length; i ++ ) {
  15869. const inputSource = event.added[ i ];
  15870. let controllerIndex = controllerInputSources.indexOf( inputSource );
  15871. if ( controllerIndex === - 1 ) {
  15872. // Assign input source a controller that currently has no input source
  15873. for ( let i = 0; i < controllers.length; i ++ ) {
  15874. if ( i >= controllerInputSources.length ) {
  15875. controllerInputSources.push( inputSource );
  15876. controllerIndex = i;
  15877. break;
  15878. } else if ( controllerInputSources[ i ] === null ) {
  15879. controllerInputSources[ i ] = inputSource;
  15880. controllerIndex = i;
  15881. break;
  15882. }
  15883. }
  15884. // If all controllers do currently receive input we ignore new ones
  15885. if ( controllerIndex === - 1 ) break;
  15886. }
  15887. const controller = controllers[ controllerIndex ];
  15888. if ( controller ) {
  15889. controller.connect( inputSource );
  15890. }
  15891. }
  15892. }
  15893. //
  15894. const cameraLPos = new Vector3();
  15895. const cameraRPos = new Vector3();
  15896. /**
  15897. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15898. * the cameras' projection and world matrices have already been set.
  15899. * And that near and far planes are identical for both cameras.
  15900. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15901. */
  15902. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  15903. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  15904. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  15905. const ipd = cameraLPos.distanceTo( cameraRPos );
  15906. const projL = cameraL.projectionMatrix.elements;
  15907. const projR = cameraR.projectionMatrix.elements;
  15908. // VR systems will have identical far and near planes, and
  15909. // most likely identical top and bottom frustum extents.
  15910. // Use the left camera for these values.
  15911. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  15912. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  15913. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  15914. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  15915. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  15916. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  15917. const left = near * leftFov;
  15918. const right = near * rightFov;
  15919. // Calculate the new camera's position offset from the
  15920. // left camera. xOffset should be roughly half `ipd`.
  15921. const zOffset = ipd / ( - leftFov + rightFov );
  15922. const xOffset = zOffset * - leftFov;
  15923. // TODO: Better way to apply this offset?
  15924. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  15925. camera.translateX( xOffset );
  15926. camera.translateZ( zOffset );
  15927. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  15928. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15929. // Find the union of the frustum values of the cameras and scale
  15930. // the values so that the near plane's position does not change in world space,
  15931. // although must now be relative to the new union camera.
  15932. const near2 = near + zOffset;
  15933. const far2 = far + zOffset;
  15934. const left2 = left - xOffset;
  15935. const right2 = right + ( ipd - xOffset );
  15936. const top2 = topFov * far / far2 * near2;
  15937. const bottom2 = bottomFov * far / far2 * near2;
  15938. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  15939. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  15940. }
  15941. function updateCamera( camera, parent ) {
  15942. if ( parent === null ) {
  15943. camera.matrixWorld.copy( camera.matrix );
  15944. } else {
  15945. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  15946. }
  15947. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15948. }
  15949. this.updateCamera = function ( camera ) {
  15950. if ( session === null ) return;
  15951. cameraXR.near = cameraR.near = cameraL.near = camera.near;
  15952. cameraXR.far = cameraR.far = cameraL.far = camera.far;
  15953. if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) {
  15954. // Note that the new renderState won't apply until the next frame. See #18320
  15955. session.updateRenderState( {
  15956. depthNear: cameraXR.near,
  15957. depthFar: cameraXR.far
  15958. } );
  15959. _currentDepthNear = cameraXR.near;
  15960. _currentDepthFar = cameraXR.far;
  15961. }
  15962. const parent = camera.parent;
  15963. const cameras = cameraXR.cameras;
  15964. updateCamera( cameraXR, parent );
  15965. for ( let i = 0; i < cameras.length; i ++ ) {
  15966. updateCamera( cameras[ i ], parent );
  15967. }
  15968. // update projection matrix for proper view frustum culling
  15969. if ( cameras.length === 2 ) {
  15970. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  15971. } else {
  15972. // assume single camera setup (AR)
  15973. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  15974. }
  15975. // update user camera and its children
  15976. updateUserCamera( camera, cameraXR, parent );
  15977. };
  15978. function updateUserCamera( camera, cameraXR, parent ) {
  15979. if ( parent === null ) {
  15980. camera.matrix.copy( cameraXR.matrixWorld );
  15981. } else {
  15982. camera.matrix.copy( parent.matrixWorld );
  15983. camera.matrix.invert();
  15984. camera.matrix.multiply( cameraXR.matrixWorld );
  15985. }
  15986. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  15987. camera.updateMatrixWorld( true );
  15988. const children = camera.children;
  15989. for ( let i = 0, l = children.length; i < l; i ++ ) {
  15990. children[ i ].updateMatrixWorld( true );
  15991. }
  15992. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  15993. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  15994. if ( camera.isPerspectiveCamera ) {
  15995. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  15996. camera.zoom = 1;
  15997. }
  15998. }
  15999. this.getCamera = function () {
  16000. return cameraXR;
  16001. };
  16002. this.getFoveation = function () {
  16003. if ( glProjLayer === null && glBaseLayer === null ) {
  16004. return undefined;
  16005. }
  16006. return foveation;
  16007. };
  16008. this.setFoveation = function ( value ) {
  16009. // 0 = no foveation = full resolution
  16010. // 1 = maximum foveation = the edges render at lower resolution
  16011. foveation = value;
  16012. if ( glProjLayer !== null ) {
  16013. glProjLayer.fixedFoveation = value;
  16014. }
  16015. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  16016. glBaseLayer.fixedFoveation = value;
  16017. }
  16018. };
  16019. // Animation Loop
  16020. let onAnimationFrameCallback = null;
  16021. function onAnimationFrame( time, frame ) {
  16022. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  16023. xrFrame = frame;
  16024. if ( pose !== null ) {
  16025. const views = pose.views;
  16026. if ( glBaseLayer !== null ) {
  16027. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  16028. renderer.setRenderTarget( newRenderTarget );
  16029. }
  16030. let cameraXRNeedsUpdate = false;
  16031. // check if it's necessary to rebuild cameraXR's camera list
  16032. if ( views.length !== cameraXR.cameras.length ) {
  16033. cameraXR.cameras.length = 0;
  16034. cameraXRNeedsUpdate = true;
  16035. }
  16036. for ( let i = 0; i < views.length; i ++ ) {
  16037. const view = views[ i ];
  16038. let viewport = null;
  16039. if ( glBaseLayer !== null ) {
  16040. viewport = glBaseLayer.getViewport( view );
  16041. } else {
  16042. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  16043. viewport = glSubImage.viewport;
  16044. // For side-by-side projection, we only produce a single texture for both eyes.
  16045. if ( i === 0 ) {
  16046. renderer.setRenderTargetTextures(
  16047. newRenderTarget,
  16048. glSubImage.colorTexture,
  16049. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  16050. renderer.setRenderTarget( newRenderTarget );
  16051. }
  16052. }
  16053. let camera = cameras[ i ];
  16054. if ( camera === undefined ) {
  16055. camera = new PerspectiveCamera();
  16056. camera.layers.enable( i );
  16057. camera.viewport = new Vector4();
  16058. cameras[ i ] = camera;
  16059. }
  16060. camera.matrix.fromArray( view.transform.matrix );
  16061. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  16062. camera.projectionMatrix.fromArray( view.projectionMatrix );
  16063. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  16064. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  16065. if ( i === 0 ) {
  16066. cameraXR.matrix.copy( camera.matrix );
  16067. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  16068. }
  16069. if ( cameraXRNeedsUpdate === true ) {
  16070. cameraXR.cameras.push( camera );
  16071. }
  16072. }
  16073. }
  16074. //
  16075. for ( let i = 0; i < controllers.length; i ++ ) {
  16076. const inputSource = controllerInputSources[ i ];
  16077. const controller = controllers[ i ];
  16078. if ( inputSource !== null && controller !== undefined ) {
  16079. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  16080. }
  16081. }
  16082. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  16083. if ( frame.detectedPlanes ) {
  16084. scope.dispatchEvent( { type: 'planesdetected', data: frame } );
  16085. }
  16086. xrFrame = null;
  16087. }
  16088. const animation = new WebGLAnimation();
  16089. animation.setAnimationLoop( onAnimationFrame );
  16090. this.setAnimationLoop = function ( callback ) {
  16091. onAnimationFrameCallback = callback;
  16092. };
  16093. this.dispose = function () {};
  16094. }
  16095. }
  16096. function WebGLMaterials( renderer, properties ) {
  16097. function refreshTransformUniform( map, uniform ) {
  16098. if ( map.matrixAutoUpdate === true ) {
  16099. map.updateMatrix();
  16100. }
  16101. uniform.value.copy( map.matrix );
  16102. }
  16103. function refreshFogUniforms( uniforms, fog ) {
  16104. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  16105. if ( fog.isFog ) {
  16106. uniforms.fogNear.value = fog.near;
  16107. uniforms.fogFar.value = fog.far;
  16108. } else if ( fog.isFogExp2 ) {
  16109. uniforms.fogDensity.value = fog.density;
  16110. }
  16111. }
  16112. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  16113. if ( material.isMeshBasicMaterial ) {
  16114. refreshUniformsCommon( uniforms, material );
  16115. } else if ( material.isMeshLambertMaterial ) {
  16116. refreshUniformsCommon( uniforms, material );
  16117. } else if ( material.isMeshToonMaterial ) {
  16118. refreshUniformsCommon( uniforms, material );
  16119. refreshUniformsToon( uniforms, material );
  16120. } else if ( material.isMeshPhongMaterial ) {
  16121. refreshUniformsCommon( uniforms, material );
  16122. refreshUniformsPhong( uniforms, material );
  16123. } else if ( material.isMeshStandardMaterial ) {
  16124. refreshUniformsCommon( uniforms, material );
  16125. refreshUniformsStandard( uniforms, material );
  16126. if ( material.isMeshPhysicalMaterial ) {
  16127. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  16128. }
  16129. } else if ( material.isMeshMatcapMaterial ) {
  16130. refreshUniformsCommon( uniforms, material );
  16131. refreshUniformsMatcap( uniforms, material );
  16132. } else if ( material.isMeshDepthMaterial ) {
  16133. refreshUniformsCommon( uniforms, material );
  16134. } else if ( material.isMeshDistanceMaterial ) {
  16135. refreshUniformsCommon( uniforms, material );
  16136. refreshUniformsDistance( uniforms, material );
  16137. } else if ( material.isMeshNormalMaterial ) {
  16138. refreshUniformsCommon( uniforms, material );
  16139. } else if ( material.isLineBasicMaterial ) {
  16140. refreshUniformsLine( uniforms, material );
  16141. if ( material.isLineDashedMaterial ) {
  16142. refreshUniformsDash( uniforms, material );
  16143. }
  16144. } else if ( material.isPointsMaterial ) {
  16145. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  16146. } else if ( material.isSpriteMaterial ) {
  16147. refreshUniformsSprites( uniforms, material );
  16148. } else if ( material.isShadowMaterial ) {
  16149. uniforms.color.value.copy( material.color );
  16150. uniforms.opacity.value = material.opacity;
  16151. } else if ( material.isShaderMaterial ) {
  16152. material.uniformsNeedUpdate = false; // #15581
  16153. }
  16154. }
  16155. function refreshUniformsCommon( uniforms, material ) {
  16156. uniforms.opacity.value = material.opacity;
  16157. if ( material.color ) {
  16158. uniforms.diffuse.value.copy( material.color );
  16159. }
  16160. if ( material.emissive ) {
  16161. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  16162. }
  16163. if ( material.map ) {
  16164. uniforms.map.value = material.map;
  16165. refreshTransformUniform( material.map, uniforms.mapTransform );
  16166. }
  16167. if ( material.alphaMap ) {
  16168. uniforms.alphaMap.value = material.alphaMap;
  16169. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16170. }
  16171. if ( material.bumpMap ) {
  16172. uniforms.bumpMap.value = material.bumpMap;
  16173. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  16174. uniforms.bumpScale.value = material.bumpScale;
  16175. if ( material.side === BackSide ) {
  16176. uniforms.bumpScale.value *= - 1;
  16177. }
  16178. }
  16179. if ( material.normalMap ) {
  16180. uniforms.normalMap.value = material.normalMap;
  16181. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  16182. uniforms.normalScale.value.copy( material.normalScale );
  16183. if ( material.side === BackSide ) {
  16184. uniforms.normalScale.value.negate();
  16185. }
  16186. }
  16187. if ( material.displacementMap ) {
  16188. uniforms.displacementMap.value = material.displacementMap;
  16189. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  16190. uniforms.displacementScale.value = material.displacementScale;
  16191. uniforms.displacementBias.value = material.displacementBias;
  16192. }
  16193. if ( material.emissiveMap ) {
  16194. uniforms.emissiveMap.value = material.emissiveMap;
  16195. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  16196. }
  16197. if ( material.specularMap ) {
  16198. uniforms.specularMap.value = material.specularMap;
  16199. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  16200. }
  16201. if ( material.alphaTest > 0 ) {
  16202. uniforms.alphaTest.value = material.alphaTest;
  16203. }
  16204. const envMap = properties.get( material ).envMap;
  16205. if ( envMap ) {
  16206. uniforms.envMap.value = envMap;
  16207. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  16208. uniforms.reflectivity.value = material.reflectivity;
  16209. uniforms.ior.value = material.ior;
  16210. uniforms.refractionRatio.value = material.refractionRatio;
  16211. }
  16212. if ( material.lightMap ) {
  16213. uniforms.lightMap.value = material.lightMap;
  16214. // artist-friendly light intensity scaling factor
  16215. const scaleFactor = ( renderer.useLegacyLights === true ) ? Math.PI : 1;
  16216. uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor;
  16217. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  16218. }
  16219. if ( material.aoMap ) {
  16220. uniforms.aoMap.value = material.aoMap;
  16221. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  16222. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  16223. }
  16224. }
  16225. function refreshUniformsLine( uniforms, material ) {
  16226. uniforms.diffuse.value.copy( material.color );
  16227. uniforms.opacity.value = material.opacity;
  16228. if ( material.map ) {
  16229. uniforms.map.value = material.map;
  16230. refreshTransformUniform( material.map, uniforms.mapTransform );
  16231. }
  16232. }
  16233. function refreshUniformsDash( uniforms, material ) {
  16234. uniforms.dashSize.value = material.dashSize;
  16235. uniforms.totalSize.value = material.dashSize + material.gapSize;
  16236. uniforms.scale.value = material.scale;
  16237. }
  16238. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  16239. uniforms.diffuse.value.copy( material.color );
  16240. uniforms.opacity.value = material.opacity;
  16241. uniforms.size.value = material.size * pixelRatio;
  16242. uniforms.scale.value = height * 0.5;
  16243. if ( material.map ) {
  16244. uniforms.map.value = material.map;
  16245. refreshTransformUniform( material.map, uniforms.uvTransform );
  16246. }
  16247. if ( material.alphaMap ) {
  16248. uniforms.alphaMap.value = material.alphaMap;
  16249. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16250. }
  16251. if ( material.alphaTest > 0 ) {
  16252. uniforms.alphaTest.value = material.alphaTest;
  16253. }
  16254. }
  16255. function refreshUniformsSprites( uniforms, material ) {
  16256. uniforms.diffuse.value.copy( material.color );
  16257. uniforms.opacity.value = material.opacity;
  16258. uniforms.rotation.value = material.rotation;
  16259. if ( material.map ) {
  16260. uniforms.map.value = material.map;
  16261. refreshTransformUniform( material.map, uniforms.mapTransform );
  16262. }
  16263. if ( material.alphaMap ) {
  16264. uniforms.alphaMap.value = material.alphaMap;
  16265. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  16266. }
  16267. if ( material.alphaTest > 0 ) {
  16268. uniforms.alphaTest.value = material.alphaTest;
  16269. }
  16270. }
  16271. function refreshUniformsPhong( uniforms, material ) {
  16272. uniforms.specular.value.copy( material.specular );
  16273. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  16274. }
  16275. function refreshUniformsToon( uniforms, material ) {
  16276. if ( material.gradientMap ) {
  16277. uniforms.gradientMap.value = material.gradientMap;
  16278. }
  16279. }
  16280. function refreshUniformsStandard( uniforms, material ) {
  16281. uniforms.metalness.value = material.metalness;
  16282. if ( material.metalnessMap ) {
  16283. uniforms.metalnessMap.value = material.metalnessMap;
  16284. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  16285. }
  16286. uniforms.roughness.value = material.roughness;
  16287. if ( material.roughnessMap ) {
  16288. uniforms.roughnessMap.value = material.roughnessMap;
  16289. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  16290. }
  16291. const envMap = properties.get( material ).envMap;
  16292. if ( envMap ) {
  16293. //uniforms.envMap.value = material.envMap; // part of uniforms common
  16294. uniforms.envMapIntensity.value = material.envMapIntensity;
  16295. }
  16296. }
  16297. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  16298. uniforms.ior.value = material.ior; // also part of uniforms common
  16299. if ( material.sheen > 0 ) {
  16300. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  16301. uniforms.sheenRoughness.value = material.sheenRoughness;
  16302. if ( material.sheenColorMap ) {
  16303. uniforms.sheenColorMap.value = material.sheenColorMap;
  16304. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  16305. }
  16306. if ( material.sheenRoughnessMap ) {
  16307. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  16308. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  16309. }
  16310. }
  16311. if ( material.clearcoat > 0 ) {
  16312. uniforms.clearcoat.value = material.clearcoat;
  16313. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  16314. if ( material.clearcoatMap ) {
  16315. uniforms.clearcoatMap.value = material.clearcoatMap;
  16316. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  16317. }
  16318. if ( material.clearcoatRoughnessMap ) {
  16319. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  16320. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  16321. }
  16322. if ( material.clearcoatNormalMap ) {
  16323. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  16324. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  16325. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  16326. if ( material.side === BackSide ) {
  16327. uniforms.clearcoatNormalScale.value.negate();
  16328. }
  16329. }
  16330. }
  16331. if ( material.iridescence > 0 ) {
  16332. uniforms.iridescence.value = material.iridescence;
  16333. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  16334. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  16335. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  16336. if ( material.iridescenceMap ) {
  16337. uniforms.iridescenceMap.value = material.iridescenceMap;
  16338. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  16339. }
  16340. if ( material.iridescenceThicknessMap ) {
  16341. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  16342. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  16343. }
  16344. }
  16345. if ( material.transmission > 0 ) {
  16346. uniforms.transmission.value = material.transmission;
  16347. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  16348. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  16349. if ( material.transmissionMap ) {
  16350. uniforms.transmissionMap.value = material.transmissionMap;
  16351. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  16352. }
  16353. uniforms.thickness.value = material.thickness;
  16354. if ( material.thicknessMap ) {
  16355. uniforms.thicknessMap.value = material.thicknessMap;
  16356. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  16357. }
  16358. uniforms.attenuationDistance.value = material.attenuationDistance;
  16359. uniforms.attenuationColor.value.copy( material.attenuationColor );
  16360. }
  16361. if ( material.anisotropy > 0 ) {
  16362. uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  16363. if ( material.anisotropyMap ) {
  16364. uniforms.anisotropyMap.value = material.anisotropyMap;
  16365. refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform );
  16366. }
  16367. }
  16368. uniforms.specularIntensity.value = material.specularIntensity;
  16369. uniforms.specularColor.value.copy( material.specularColor );
  16370. if ( material.specularColorMap ) {
  16371. uniforms.specularColorMap.value = material.specularColorMap;
  16372. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  16373. }
  16374. if ( material.specularIntensityMap ) {
  16375. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  16376. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  16377. }
  16378. }
  16379. function refreshUniformsMatcap( uniforms, material ) {
  16380. if ( material.matcap ) {
  16381. uniforms.matcap.value = material.matcap;
  16382. }
  16383. }
  16384. function refreshUniformsDistance( uniforms, material ) {
  16385. const light = properties.get( material ).light;
  16386. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  16387. uniforms.nearDistance.value = light.shadow.camera.near;
  16388. uniforms.farDistance.value = light.shadow.camera.far;
  16389. }
  16390. return {
  16391. refreshFogUniforms: refreshFogUniforms,
  16392. refreshMaterialUniforms: refreshMaterialUniforms
  16393. };
  16394. }
  16395. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  16396. let buffers = {};
  16397. let updateList = {};
  16398. let allocatedBindingPoints = [];
  16399. const maxBindingPoints = ( capabilities.isWebGL2 ) ? gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ) : 0; // binding points are global whereas block indices are per shader program
  16400. function bind( uniformsGroup, program ) {
  16401. const webglProgram = program.program;
  16402. state.uniformBlockBinding( uniformsGroup, webglProgram );
  16403. }
  16404. function update( uniformsGroup, program ) {
  16405. let buffer = buffers[ uniformsGroup.id ];
  16406. if ( buffer === undefined ) {
  16407. prepareUniformsGroup( uniformsGroup );
  16408. buffer = createBuffer( uniformsGroup );
  16409. buffers[ uniformsGroup.id ] = buffer;
  16410. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  16411. }
  16412. // ensure to update the binding points/block indices mapping for this program
  16413. const webglProgram = program.program;
  16414. state.updateUBOMapping( uniformsGroup, webglProgram );
  16415. // update UBO once per frame
  16416. const frame = info.render.frame;
  16417. if ( updateList[ uniformsGroup.id ] !== frame ) {
  16418. updateBufferData( uniformsGroup );
  16419. updateList[ uniformsGroup.id ] = frame;
  16420. }
  16421. }
  16422. function createBuffer( uniformsGroup ) {
  16423. // the setup of an UBO is independent of a particular shader program but global
  16424. const bindingPointIndex = allocateBindingPointIndex();
  16425. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  16426. const buffer = gl.createBuffer();
  16427. const size = uniformsGroup.__size;
  16428. const usage = uniformsGroup.usage;
  16429. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  16430. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  16431. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  16432. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  16433. return buffer;
  16434. }
  16435. function allocateBindingPointIndex() {
  16436. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  16437. if ( allocatedBindingPoints.indexOf( i ) === - 1 ) {
  16438. allocatedBindingPoints.push( i );
  16439. return i;
  16440. }
  16441. }
  16442. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  16443. return 0;
  16444. }
  16445. function updateBufferData( uniformsGroup ) {
  16446. const buffer = buffers[ uniformsGroup.id ];
  16447. const uniforms = uniformsGroup.uniforms;
  16448. const cache = uniformsGroup.__cache;
  16449. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  16450. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  16451. const uniform = uniforms[ i ];
  16452. // partly update the buffer if necessary
  16453. if ( hasUniformChanged( uniform, i, cache ) === true ) {
  16454. const offset = uniform.__offset;
  16455. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16456. let arrayOffset = 0;
  16457. for ( let i = 0; i < values.length; i ++ ) {
  16458. const value = values[ i ];
  16459. const info = getUniformSize( value );
  16460. if ( typeof value === 'number' ) {
  16461. uniform.__data[ 0 ] = value;
  16462. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  16463. } else if ( value.isMatrix3 ) {
  16464. // manually converting 3x3 to 3x4
  16465. uniform.__data[ 0 ] = value.elements[ 0 ];
  16466. uniform.__data[ 1 ] = value.elements[ 1 ];
  16467. uniform.__data[ 2 ] = value.elements[ 2 ];
  16468. uniform.__data[ 3 ] = value.elements[ 0 ];
  16469. uniform.__data[ 4 ] = value.elements[ 3 ];
  16470. uniform.__data[ 5 ] = value.elements[ 4 ];
  16471. uniform.__data[ 6 ] = value.elements[ 5 ];
  16472. uniform.__data[ 7 ] = value.elements[ 0 ];
  16473. uniform.__data[ 8 ] = value.elements[ 6 ];
  16474. uniform.__data[ 9 ] = value.elements[ 7 ];
  16475. uniform.__data[ 10 ] = value.elements[ 8 ];
  16476. uniform.__data[ 11 ] = value.elements[ 0 ];
  16477. } else {
  16478. value.toArray( uniform.__data, arrayOffset );
  16479. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  16480. }
  16481. }
  16482. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  16483. }
  16484. }
  16485. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  16486. }
  16487. function hasUniformChanged( uniform, index, cache ) {
  16488. const value = uniform.value;
  16489. if ( cache[ index ] === undefined ) {
  16490. // cache entry does not exist so far
  16491. if ( typeof value === 'number' ) {
  16492. cache[ index ] = value;
  16493. } else {
  16494. const values = Array.isArray( value ) ? value : [ value ];
  16495. const tempValues = [];
  16496. for ( let i = 0; i < values.length; i ++ ) {
  16497. tempValues.push( values[ i ].clone() );
  16498. }
  16499. cache[ index ] = tempValues;
  16500. }
  16501. return true;
  16502. } else {
  16503. // compare current value with cached entry
  16504. if ( typeof value === 'number' ) {
  16505. if ( cache[ index ] !== value ) {
  16506. cache[ index ] = value;
  16507. return true;
  16508. }
  16509. } else {
  16510. const cachedObjects = Array.isArray( cache[ index ] ) ? cache[ index ] : [ cache[ index ] ];
  16511. const values = Array.isArray( value ) ? value : [ value ];
  16512. for ( let i = 0; i < cachedObjects.length; i ++ ) {
  16513. const cachedObject = cachedObjects[ i ];
  16514. if ( cachedObject.equals( values[ i ] ) === false ) {
  16515. cachedObject.copy( values[ i ] );
  16516. return true;
  16517. }
  16518. }
  16519. }
  16520. }
  16521. return false;
  16522. }
  16523. function prepareUniformsGroup( uniformsGroup ) {
  16524. // determine total buffer size according to the STD140 layout
  16525. // Hint: STD140 is the only supported layout in WebGL 2
  16526. const uniforms = uniformsGroup.uniforms;
  16527. let offset = 0; // global buffer offset in bytes
  16528. const chunkSize = 16; // size of a chunk in bytes
  16529. let chunkOffset = 0; // offset within a single chunk in bytes
  16530. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  16531. const uniform = uniforms[ i ];
  16532. const infos = {
  16533. boundary: 0, // bytes
  16534. storage: 0 // bytes
  16535. };
  16536. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16537. for ( let j = 0, jl = values.length; j < jl; j ++ ) {
  16538. const value = values[ j ];
  16539. const info = getUniformSize( value );
  16540. infos.boundary += info.boundary;
  16541. infos.storage += info.storage;
  16542. }
  16543. // the following two properties will be used for partial buffer updates
  16544. uniform.__data = new Float32Array( infos.storage / Float32Array.BYTES_PER_ELEMENT );
  16545. uniform.__offset = offset;
  16546. //
  16547. if ( i > 0 ) {
  16548. chunkOffset = offset % chunkSize;
  16549. const remainingSizeInChunk = chunkSize - chunkOffset;
  16550. // check for chunk overflow
  16551. if ( chunkOffset !== 0 && ( remainingSizeInChunk - infos.boundary ) < 0 ) {
  16552. // add padding and adjust offset
  16553. offset += ( chunkSize - chunkOffset );
  16554. uniform.__offset = offset;
  16555. }
  16556. }
  16557. offset += infos.storage;
  16558. }
  16559. // ensure correct final padding
  16560. chunkOffset = offset % chunkSize;
  16561. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  16562. //
  16563. uniformsGroup.__size = offset;
  16564. uniformsGroup.__cache = {};
  16565. return this;
  16566. }
  16567. function getUniformSize( value ) {
  16568. const info = {
  16569. boundary: 0, // bytes
  16570. storage: 0 // bytes
  16571. };
  16572. // determine sizes according to STD140
  16573. if ( typeof value === 'number' ) {
  16574. // float/int
  16575. info.boundary = 4;
  16576. info.storage = 4;
  16577. } else if ( value.isVector2 ) {
  16578. // vec2
  16579. info.boundary = 8;
  16580. info.storage = 8;
  16581. } else if ( value.isVector3 || value.isColor ) {
  16582. // vec3
  16583. info.boundary = 16;
  16584. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  16585. } else if ( value.isVector4 ) {
  16586. // vec4
  16587. info.boundary = 16;
  16588. info.storage = 16;
  16589. } else if ( value.isMatrix3 ) {
  16590. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  16591. info.boundary = 48;
  16592. info.storage = 48;
  16593. } else if ( value.isMatrix4 ) {
  16594. // mat4
  16595. info.boundary = 64;
  16596. info.storage = 64;
  16597. } else if ( value.isTexture ) {
  16598. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  16599. } else {
  16600. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  16601. }
  16602. return info;
  16603. }
  16604. function onUniformsGroupsDispose( event ) {
  16605. const uniformsGroup = event.target;
  16606. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  16607. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  16608. allocatedBindingPoints.splice( index, 1 );
  16609. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  16610. delete buffers[ uniformsGroup.id ];
  16611. delete updateList[ uniformsGroup.id ];
  16612. }
  16613. function dispose() {
  16614. for ( const id in buffers ) {
  16615. gl.deleteBuffer( buffers[ id ] );
  16616. }
  16617. allocatedBindingPoints = [];
  16618. buffers = {};
  16619. updateList = {};
  16620. }
  16621. return {
  16622. bind: bind,
  16623. update: update,
  16624. dispose: dispose
  16625. };
  16626. }
  16627. function createCanvasElement() {
  16628. const canvas = createElementNS( 'canvas' );
  16629. canvas.style.display = 'block';
  16630. return canvas;
  16631. }
  16632. class WebGLRenderer {
  16633. constructor( parameters = {} ) {
  16634. const {
  16635. canvas = createCanvasElement(),
  16636. context = null,
  16637. depth = true,
  16638. stencil = true,
  16639. alpha = false,
  16640. antialias = false,
  16641. premultipliedAlpha = true,
  16642. preserveDrawingBuffer = false,
  16643. powerPreference = 'default',
  16644. failIfMajorPerformanceCaveat = false,
  16645. } = parameters;
  16646. this.isWebGLRenderer = true;
  16647. let _alpha;
  16648. if ( context !== null ) {
  16649. _alpha = context.getContextAttributes().alpha;
  16650. } else {
  16651. _alpha = alpha;
  16652. }
  16653. const uintClearColor = new Uint32Array( 4 );
  16654. const intClearColor = new Int32Array( 4 );
  16655. let currentRenderList = null;
  16656. let currentRenderState = null;
  16657. // render() can be called from within a callback triggered by another render.
  16658. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  16659. const renderListStack = [];
  16660. const renderStateStack = [];
  16661. // public properties
  16662. this.domElement = canvas;
  16663. // Debug configuration container
  16664. this.debug = {
  16665. /**
  16666. * Enables error checking and reporting when shader programs are being compiled
  16667. * @type {boolean}
  16668. */
  16669. checkShaderErrors: true,
  16670. /**
  16671. * Callback for custom error reporting.
  16672. * @type {?Function}
  16673. */
  16674. onShaderError: null
  16675. };
  16676. // clearing
  16677. this.autoClear = true;
  16678. this.autoClearColor = true;
  16679. this.autoClearDepth = true;
  16680. this.autoClearStencil = true;
  16681. // scene graph
  16682. this.sortObjects = true;
  16683. // user-defined clipping
  16684. this.clippingPlanes = [];
  16685. this.localClippingEnabled = false;
  16686. // physically based shading
  16687. this.outputColorSpace = SRGBColorSpace;
  16688. // physical lights
  16689. this.useLegacyLights = true;
  16690. // tone mapping
  16691. this.toneMapping = NoToneMapping;
  16692. this.toneMappingExposure = 1.0;
  16693. // internal properties
  16694. const _this = this;
  16695. let _isContextLost = false;
  16696. // internal state cache
  16697. let _currentActiveCubeFace = 0;
  16698. let _currentActiveMipmapLevel = 0;
  16699. let _currentRenderTarget = null;
  16700. let _currentMaterialId = - 1;
  16701. let _currentCamera = null;
  16702. const _currentViewport = new Vector4();
  16703. const _currentScissor = new Vector4();
  16704. let _currentScissorTest = null;
  16705. const _currentClearColor = new Color( 0x000000 );
  16706. let _currentClearAlpha = 0;
  16707. //
  16708. let _width = canvas.width;
  16709. let _height = canvas.height;
  16710. let _pixelRatio = 1;
  16711. let _opaqueSort = null;
  16712. let _transparentSort = null;
  16713. const _viewport = new Vector4( 0, 0, _width, _height );
  16714. const _scissor = new Vector4( 0, 0, _width, _height );
  16715. let _scissorTest = false;
  16716. // frustum
  16717. const _frustum = new Frustum();
  16718. // clipping
  16719. let _clippingEnabled = false;
  16720. let _localClippingEnabled = false;
  16721. // transmission
  16722. let _transmissionRenderTarget = null;
  16723. // camera matrices cache
  16724. const _projScreenMatrix = new Matrix4();
  16725. const _vector2 = new Vector2();
  16726. const _vector3 = new Vector3();
  16727. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  16728. function getTargetPixelRatio() {
  16729. return _currentRenderTarget === null ? _pixelRatio : 1;
  16730. }
  16731. // initialize
  16732. let _gl = context;
  16733. function getContext( contextNames, contextAttributes ) {
  16734. for ( let i = 0; i < contextNames.length; i ++ ) {
  16735. const contextName = contextNames[ i ];
  16736. const context = canvas.getContext( contextName, contextAttributes );
  16737. if ( context !== null ) return context;
  16738. }
  16739. return null;
  16740. }
  16741. try {
  16742. const contextAttributes = {
  16743. alpha: true,
  16744. depth,
  16745. stencil,
  16746. antialias,
  16747. premultipliedAlpha,
  16748. preserveDrawingBuffer,
  16749. powerPreference,
  16750. failIfMajorPerformanceCaveat,
  16751. };
  16752. // OffscreenCanvas does not have setAttribute, see #22811
  16753. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  16754. // event listeners must be registered before WebGL context is created, see #12753
  16755. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  16756. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  16757. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16758. if ( _gl === null ) {
  16759. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  16760. if ( _this.isWebGL1Renderer === true ) {
  16761. contextNames.shift();
  16762. }
  16763. _gl = getContext( contextNames, contextAttributes );
  16764. if ( _gl === null ) {
  16765. if ( getContext( contextNames ) ) {
  16766. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  16767. } else {
  16768. throw new Error( 'Error creating WebGL context.' );
  16769. }
  16770. }
  16771. }
  16772. if ( typeof WebGLRenderingContext !== 'undefined' && _gl instanceof WebGLRenderingContext ) { // @deprecated, r153
  16773. console.warn( 'THREE.WebGLRenderer: WebGL 1 support was deprecated in r153 and will be removed in r163.' );
  16774. }
  16775. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  16776. if ( _gl.getShaderPrecisionFormat === undefined ) {
  16777. _gl.getShaderPrecisionFormat = function () {
  16778. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  16779. };
  16780. }
  16781. } catch ( error ) {
  16782. console.error( 'THREE.WebGLRenderer: ' + error.message );
  16783. throw error;
  16784. }
  16785. let extensions, capabilities, state, info;
  16786. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  16787. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  16788. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  16789. let utils, bindingStates, uniformsGroups;
  16790. function initGLContext() {
  16791. extensions = new WebGLExtensions( _gl );
  16792. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  16793. extensions.init( capabilities );
  16794. utils = new WebGLUtils( _gl, extensions, capabilities );
  16795. state = new WebGLState( _gl, extensions, capabilities );
  16796. info = new WebGLInfo( _gl );
  16797. properties = new WebGLProperties();
  16798. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  16799. cubemaps = new WebGLCubeMaps( _this );
  16800. cubeuvmaps = new WebGLCubeUVMaps( _this );
  16801. attributes = new WebGLAttributes( _gl, capabilities );
  16802. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  16803. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  16804. objects = new WebGLObjects( _gl, geometries, attributes, info );
  16805. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  16806. clipping = new WebGLClipping( properties );
  16807. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  16808. materials = new WebGLMaterials( _this, properties );
  16809. renderLists = new WebGLRenderLists();
  16810. renderStates = new WebGLRenderStates( extensions, capabilities );
  16811. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  16812. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  16813. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  16814. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  16815. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  16816. info.programs = programCache.programs;
  16817. _this.capabilities = capabilities;
  16818. _this.extensions = extensions;
  16819. _this.properties = properties;
  16820. _this.renderLists = renderLists;
  16821. _this.shadowMap = shadowMap;
  16822. _this.state = state;
  16823. _this.info = info;
  16824. }
  16825. initGLContext();
  16826. // xr
  16827. const xr = new WebXRManager( _this, _gl );
  16828. this.xr = xr;
  16829. // API
  16830. this.getContext = function () {
  16831. return _gl;
  16832. };
  16833. this.getContextAttributes = function () {
  16834. return _gl.getContextAttributes();
  16835. };
  16836. this.forceContextLoss = function () {
  16837. const extension = extensions.get( 'WEBGL_lose_context' );
  16838. if ( extension ) extension.loseContext();
  16839. };
  16840. this.forceContextRestore = function () {
  16841. const extension = extensions.get( 'WEBGL_lose_context' );
  16842. if ( extension ) extension.restoreContext();
  16843. };
  16844. this.getPixelRatio = function () {
  16845. return _pixelRatio;
  16846. };
  16847. this.setPixelRatio = function ( value ) {
  16848. if ( value === undefined ) return;
  16849. _pixelRatio = value;
  16850. this.setSize( _width, _height, false );
  16851. };
  16852. this.getSize = function ( target ) {
  16853. return target.set( _width, _height );
  16854. };
  16855. this.setSize = function ( width, height, updateStyle = true ) {
  16856. if ( xr.isPresenting ) {
  16857. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  16858. return;
  16859. }
  16860. _width = width;
  16861. _height = height;
  16862. canvas.width = Math.floor( width * _pixelRatio );
  16863. canvas.height = Math.floor( height * _pixelRatio );
  16864. if ( updateStyle === true ) {
  16865. canvas.style.width = width + 'px';
  16866. canvas.style.height = height + 'px';
  16867. }
  16868. this.setViewport( 0, 0, width, height );
  16869. };
  16870. this.getDrawingBufferSize = function ( target ) {
  16871. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  16872. };
  16873. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  16874. _width = width;
  16875. _height = height;
  16876. _pixelRatio = pixelRatio;
  16877. canvas.width = Math.floor( width * pixelRatio );
  16878. canvas.height = Math.floor( height * pixelRatio );
  16879. this.setViewport( 0, 0, width, height );
  16880. };
  16881. this.getCurrentViewport = function ( target ) {
  16882. return target.copy( _currentViewport );
  16883. };
  16884. this.getViewport = function ( target ) {
  16885. return target.copy( _viewport );
  16886. };
  16887. this.setViewport = function ( x, y, width, height ) {
  16888. if ( x.isVector4 ) {
  16889. _viewport.set( x.x, x.y, x.z, x.w );
  16890. } else {
  16891. _viewport.set( x, y, width, height );
  16892. }
  16893. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  16894. };
  16895. this.getScissor = function ( target ) {
  16896. return target.copy( _scissor );
  16897. };
  16898. this.setScissor = function ( x, y, width, height ) {
  16899. if ( x.isVector4 ) {
  16900. _scissor.set( x.x, x.y, x.z, x.w );
  16901. } else {
  16902. _scissor.set( x, y, width, height );
  16903. }
  16904. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  16905. };
  16906. this.getScissorTest = function () {
  16907. return _scissorTest;
  16908. };
  16909. this.setScissorTest = function ( boolean ) {
  16910. state.setScissorTest( _scissorTest = boolean );
  16911. };
  16912. this.setOpaqueSort = function ( method ) {
  16913. _opaqueSort = method;
  16914. };
  16915. this.setTransparentSort = function ( method ) {
  16916. _transparentSort = method;
  16917. };
  16918. // Clearing
  16919. this.getClearColor = function ( target ) {
  16920. return target.copy( background.getClearColor() );
  16921. };
  16922. this.setClearColor = function () {
  16923. background.setClearColor.apply( background, arguments );
  16924. };
  16925. this.getClearAlpha = function () {
  16926. return background.getClearAlpha();
  16927. };
  16928. this.setClearAlpha = function () {
  16929. background.setClearAlpha.apply( background, arguments );
  16930. };
  16931. this.clear = function ( color = true, depth = true, stencil = true ) {
  16932. let bits = 0;
  16933. if ( color ) {
  16934. // check if we're trying to clear an integer target
  16935. let isIntegerFormat = false;
  16936. if ( _currentRenderTarget !== null ) {
  16937. const targetFormat = _currentRenderTarget.texture.format;
  16938. isIntegerFormat = targetFormat === RGBAIntegerFormat ||
  16939. targetFormat === RGIntegerFormat ||
  16940. targetFormat === RedIntegerFormat;
  16941. }
  16942. // use the appropriate clear functions to clear the target if it's a signed
  16943. // or unsigned integer target
  16944. if ( isIntegerFormat ) {
  16945. const targetType = _currentRenderTarget.texture.type;
  16946. const isUnsignedType = targetType === UnsignedByteType ||
  16947. targetType === UnsignedIntType ||
  16948. targetType === UnsignedShortType ||
  16949. targetType === UnsignedInt248Type ||
  16950. targetType === UnsignedShort4444Type ||
  16951. targetType === UnsignedShort5551Type;
  16952. const clearColor = background.getClearColor();
  16953. const a = background.getClearAlpha();
  16954. const r = clearColor.r;
  16955. const g = clearColor.g;
  16956. const b = clearColor.b;
  16957. if ( isUnsignedType ) {
  16958. uintClearColor[ 0 ] = r;
  16959. uintClearColor[ 1 ] = g;
  16960. uintClearColor[ 2 ] = b;
  16961. uintClearColor[ 3 ] = a;
  16962. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  16963. } else {
  16964. intClearColor[ 0 ] = r;
  16965. intClearColor[ 1 ] = g;
  16966. intClearColor[ 2 ] = b;
  16967. intClearColor[ 3 ] = a;
  16968. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  16969. }
  16970. } else {
  16971. bits |= _gl.COLOR_BUFFER_BIT;
  16972. }
  16973. }
  16974. if ( depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  16975. if ( stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  16976. _gl.clear( bits );
  16977. };
  16978. this.clearColor = function () {
  16979. this.clear( true, false, false );
  16980. };
  16981. this.clearDepth = function () {
  16982. this.clear( false, true, false );
  16983. };
  16984. this.clearStencil = function () {
  16985. this.clear( false, false, true );
  16986. };
  16987. //
  16988. this.dispose = function () {
  16989. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  16990. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  16991. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16992. renderLists.dispose();
  16993. renderStates.dispose();
  16994. properties.dispose();
  16995. cubemaps.dispose();
  16996. cubeuvmaps.dispose();
  16997. objects.dispose();
  16998. bindingStates.dispose();
  16999. uniformsGroups.dispose();
  17000. programCache.dispose();
  17001. xr.dispose();
  17002. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  17003. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  17004. if ( _transmissionRenderTarget ) {
  17005. _transmissionRenderTarget.dispose();
  17006. _transmissionRenderTarget = null;
  17007. }
  17008. animation.stop();
  17009. };
  17010. // Events
  17011. function onContextLost( event ) {
  17012. event.preventDefault();
  17013. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  17014. _isContextLost = true;
  17015. }
  17016. function onContextRestore( /* event */ ) {
  17017. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  17018. _isContextLost = false;
  17019. const infoAutoReset = info.autoReset;
  17020. const shadowMapEnabled = shadowMap.enabled;
  17021. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  17022. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  17023. const shadowMapType = shadowMap.type;
  17024. initGLContext();
  17025. info.autoReset = infoAutoReset;
  17026. shadowMap.enabled = shadowMapEnabled;
  17027. shadowMap.autoUpdate = shadowMapAutoUpdate;
  17028. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  17029. shadowMap.type = shadowMapType;
  17030. }
  17031. function onContextCreationError( event ) {
  17032. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  17033. }
  17034. function onMaterialDispose( event ) {
  17035. const material = event.target;
  17036. material.removeEventListener( 'dispose', onMaterialDispose );
  17037. deallocateMaterial( material );
  17038. }
  17039. // Buffer deallocation
  17040. function deallocateMaterial( material ) {
  17041. releaseMaterialProgramReferences( material );
  17042. properties.remove( material );
  17043. }
  17044. function releaseMaterialProgramReferences( material ) {
  17045. const programs = properties.get( material ).programs;
  17046. if ( programs !== undefined ) {
  17047. programs.forEach( function ( program ) {
  17048. programCache.releaseProgram( program );
  17049. } );
  17050. if ( material.isShaderMaterial ) {
  17051. programCache.releaseShaderCache( material );
  17052. }
  17053. }
  17054. }
  17055. // Buffer rendering
  17056. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  17057. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  17058. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  17059. const program = setProgram( camera, scene, geometry, material, object );
  17060. state.setMaterial( material, frontFaceCW );
  17061. //
  17062. let index = geometry.index;
  17063. let rangeFactor = 1;
  17064. if ( material.wireframe === true ) {
  17065. index = geometries.getWireframeAttribute( geometry );
  17066. rangeFactor = 2;
  17067. }
  17068. //
  17069. const drawRange = geometry.drawRange;
  17070. const position = geometry.attributes.position;
  17071. let drawStart = drawRange.start * rangeFactor;
  17072. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  17073. if ( group !== null ) {
  17074. drawStart = Math.max( drawStart, group.start * rangeFactor );
  17075. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  17076. }
  17077. if ( index !== null ) {
  17078. drawStart = Math.max( drawStart, 0 );
  17079. drawEnd = Math.min( drawEnd, index.count );
  17080. } else if ( position !== undefined && position !== null ) {
  17081. drawStart = Math.max( drawStart, 0 );
  17082. drawEnd = Math.min( drawEnd, position.count );
  17083. }
  17084. const drawCount = drawEnd - drawStart;
  17085. if ( drawCount < 0 || drawCount === Infinity ) return;
  17086. //
  17087. bindingStates.setup( object, material, program, geometry, index );
  17088. let attribute;
  17089. let renderer = bufferRenderer;
  17090. if ( index !== null ) {
  17091. attribute = attributes.get( index );
  17092. renderer = indexedBufferRenderer;
  17093. renderer.setIndex( attribute );
  17094. }
  17095. //
  17096. if ( object.isMesh ) {
  17097. if ( material.wireframe === true ) {
  17098. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  17099. renderer.setMode( _gl.LINES );
  17100. } else {
  17101. renderer.setMode( _gl.TRIANGLES );
  17102. }
  17103. } else if ( object.isLine ) {
  17104. let lineWidth = material.linewidth;
  17105. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  17106. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  17107. if ( object.isLineSegments ) {
  17108. renderer.setMode( _gl.LINES );
  17109. } else if ( object.isLineLoop ) {
  17110. renderer.setMode( _gl.LINE_LOOP );
  17111. } else {
  17112. renderer.setMode( _gl.LINE_STRIP );
  17113. }
  17114. } else if ( object.isPoints ) {
  17115. renderer.setMode( _gl.POINTS );
  17116. } else if ( object.isSprite ) {
  17117. renderer.setMode( _gl.TRIANGLES );
  17118. }
  17119. if ( object.isInstancedMesh ) {
  17120. renderer.renderInstances( drawStart, drawCount, object.count );
  17121. } else if ( geometry.isInstancedBufferGeometry ) {
  17122. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  17123. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  17124. renderer.renderInstances( drawStart, drawCount, instanceCount );
  17125. } else {
  17126. renderer.render( drawStart, drawCount );
  17127. }
  17128. };
  17129. // Compile
  17130. this.compile = function ( scene, camera ) {
  17131. function prepare( material, scene, object ) {
  17132. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  17133. material.side = BackSide;
  17134. material.needsUpdate = true;
  17135. getProgram( material, scene, object );
  17136. material.side = FrontSide;
  17137. material.needsUpdate = true;
  17138. getProgram( material, scene, object );
  17139. material.side = DoubleSide;
  17140. } else {
  17141. getProgram( material, scene, object );
  17142. }
  17143. }
  17144. currentRenderState = renderStates.get( scene );
  17145. currentRenderState.init();
  17146. renderStateStack.push( currentRenderState );
  17147. scene.traverseVisible( function ( object ) {
  17148. if ( object.isLight && object.layers.test( camera.layers ) ) {
  17149. currentRenderState.pushLight( object );
  17150. if ( object.castShadow ) {
  17151. currentRenderState.pushShadow( object );
  17152. }
  17153. }
  17154. } );
  17155. currentRenderState.setupLights( _this.useLegacyLights );
  17156. scene.traverse( function ( object ) {
  17157. const material = object.material;
  17158. if ( material ) {
  17159. if ( Array.isArray( material ) ) {
  17160. for ( let i = 0; i < material.length; i ++ ) {
  17161. const material2 = material[ i ];
  17162. prepare( material2, scene, object );
  17163. }
  17164. } else {
  17165. prepare( material, scene, object );
  17166. }
  17167. }
  17168. } );
  17169. renderStateStack.pop();
  17170. currentRenderState = null;
  17171. };
  17172. // Animation Loop
  17173. let onAnimationFrameCallback = null;
  17174. function onAnimationFrame( time ) {
  17175. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  17176. }
  17177. function onXRSessionStart() {
  17178. animation.stop();
  17179. }
  17180. function onXRSessionEnd() {
  17181. animation.start();
  17182. }
  17183. const animation = new WebGLAnimation();
  17184. animation.setAnimationLoop( onAnimationFrame );
  17185. if ( typeof self !== 'undefined' ) animation.setContext( self );
  17186. this.setAnimationLoop = function ( callback ) {
  17187. onAnimationFrameCallback = callback;
  17188. xr.setAnimationLoop( callback );
  17189. ( callback === null ) ? animation.stop() : animation.start();
  17190. };
  17191. xr.addEventListener( 'sessionstart', onXRSessionStart );
  17192. xr.addEventListener( 'sessionend', onXRSessionEnd );
  17193. // Rendering
  17194. this.render = function ( scene, camera ) {
  17195. if ( camera !== undefined && camera.isCamera !== true ) {
  17196. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  17197. return;
  17198. }
  17199. if ( _isContextLost === true ) return;
  17200. // update scene graph
  17201. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  17202. // update camera matrices and frustum
  17203. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  17204. if ( xr.enabled === true && xr.isPresenting === true ) {
  17205. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  17206. camera = xr.getCamera(); // use XR camera for rendering
  17207. }
  17208. //
  17209. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  17210. currentRenderState = renderStates.get( scene, renderStateStack.length );
  17211. currentRenderState.init();
  17212. renderStateStack.push( currentRenderState );
  17213. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  17214. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  17215. _localClippingEnabled = this.localClippingEnabled;
  17216. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  17217. currentRenderList = renderLists.get( scene, renderListStack.length );
  17218. currentRenderList.init();
  17219. renderListStack.push( currentRenderList );
  17220. projectObject( scene, camera, 0, _this.sortObjects );
  17221. currentRenderList.finish();
  17222. if ( _this.sortObjects === true ) {
  17223. currentRenderList.sort( _opaqueSort, _transparentSort );
  17224. }
  17225. //
  17226. this.info.render.frame ++;
  17227. if ( _clippingEnabled === true ) clipping.beginShadows();
  17228. const shadowsArray = currentRenderState.state.shadowsArray;
  17229. shadowMap.render( shadowsArray, scene, camera );
  17230. if ( _clippingEnabled === true ) clipping.endShadows();
  17231. //
  17232. if ( this.info.autoReset === true ) this.info.reset();
  17233. //
  17234. background.render( currentRenderList, scene );
  17235. // render scene
  17236. currentRenderState.setupLights( _this.useLegacyLights );
  17237. if ( camera.isArrayCamera ) {
  17238. const cameras = camera.cameras;
  17239. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  17240. const camera2 = cameras[ i ];
  17241. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  17242. }
  17243. } else {
  17244. renderScene( currentRenderList, scene, camera );
  17245. }
  17246. //
  17247. if ( _currentRenderTarget !== null ) {
  17248. // resolve multisample renderbuffers to a single-sample texture if necessary
  17249. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  17250. // Generate mipmap if we're using any kind of mipmap filtering
  17251. textures.updateRenderTargetMipmap( _currentRenderTarget );
  17252. }
  17253. //
  17254. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  17255. // _gl.finish();
  17256. bindingStates.resetDefaultState();
  17257. _currentMaterialId = - 1;
  17258. _currentCamera = null;
  17259. renderStateStack.pop();
  17260. if ( renderStateStack.length > 0 ) {
  17261. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  17262. } else {
  17263. currentRenderState = null;
  17264. }
  17265. renderListStack.pop();
  17266. if ( renderListStack.length > 0 ) {
  17267. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  17268. } else {
  17269. currentRenderList = null;
  17270. }
  17271. };
  17272. function projectObject( object, camera, groupOrder, sortObjects ) {
  17273. if ( object.visible === false ) return;
  17274. const visible = object.layers.test( camera.layers );
  17275. if ( visible ) {
  17276. if ( object.isGroup ) {
  17277. groupOrder = object.renderOrder;
  17278. } else if ( object.isLOD ) {
  17279. if ( object.autoUpdate === true ) object.update( camera );
  17280. } else if ( object.isLight ) {
  17281. currentRenderState.pushLight( object );
  17282. if ( object.castShadow ) {
  17283. currentRenderState.pushShadow( object );
  17284. }
  17285. } else if ( object.isSprite ) {
  17286. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  17287. if ( sortObjects ) {
  17288. _vector3.setFromMatrixPosition( object.matrixWorld )
  17289. .applyMatrix4( _projScreenMatrix );
  17290. }
  17291. const geometry = objects.update( object );
  17292. const material = object.material;
  17293. if ( material.visible ) {
  17294. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  17295. }
  17296. }
  17297. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  17298. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  17299. const geometry = objects.update( object );
  17300. const material = object.material;
  17301. if ( sortObjects ) {
  17302. if ( object.boundingSphere !== undefined ) {
  17303. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  17304. _vector3.copy( object.boundingSphere.center );
  17305. } else {
  17306. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  17307. _vector3.copy( geometry.boundingSphere.center );
  17308. }
  17309. _vector3
  17310. .applyMatrix4( object.matrixWorld )
  17311. .applyMatrix4( _projScreenMatrix );
  17312. }
  17313. if ( Array.isArray( material ) ) {
  17314. const groups = geometry.groups;
  17315. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17316. const group = groups[ i ];
  17317. const groupMaterial = material[ group.materialIndex ];
  17318. if ( groupMaterial && groupMaterial.visible ) {
  17319. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  17320. }
  17321. }
  17322. } else if ( material.visible ) {
  17323. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  17324. }
  17325. }
  17326. }
  17327. }
  17328. const children = object.children;
  17329. for ( let i = 0, l = children.length; i < l; i ++ ) {
  17330. projectObject( children[ i ], camera, groupOrder, sortObjects );
  17331. }
  17332. }
  17333. function renderScene( currentRenderList, scene, camera, viewport ) {
  17334. const opaqueObjects = currentRenderList.opaque;
  17335. const transmissiveObjects = currentRenderList.transmissive;
  17336. const transparentObjects = currentRenderList.transparent;
  17337. currentRenderState.setupLightsView( camera );
  17338. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  17339. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  17340. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  17341. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  17342. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  17343. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  17344. // Ensure depth buffer writing is enabled so it can be cleared on next render
  17345. state.buffers.depth.setTest( true );
  17346. state.buffers.depth.setMask( true );
  17347. state.buffers.color.setMask( true );
  17348. state.setPolygonOffset( false );
  17349. }
  17350. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  17351. const isWebGL2 = capabilities.isWebGL2;
  17352. if ( _transmissionRenderTarget === null ) {
  17353. _transmissionRenderTarget = new WebGLRenderTarget( 1, 1, {
  17354. generateMipmaps: true,
  17355. type: extensions.has( 'EXT_color_buffer_half_float' ) ? HalfFloatType : UnsignedByteType,
  17356. minFilter: LinearMipmapLinearFilter,
  17357. samples: ( isWebGL2 ) ? 4 : 0
  17358. } );
  17359. // debug
  17360. /*
  17361. const geometry = new PlaneGeometry();
  17362. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  17363. const mesh = new Mesh( geometry, material );
  17364. scene.add( mesh );
  17365. */
  17366. }
  17367. _this.getDrawingBufferSize( _vector2 );
  17368. if ( isWebGL2 ) {
  17369. _transmissionRenderTarget.setSize( _vector2.x, _vector2.y );
  17370. } else {
  17371. _transmissionRenderTarget.setSize( floorPowerOfTwo( _vector2.x ), floorPowerOfTwo( _vector2.y ) );
  17372. }
  17373. //
  17374. const currentRenderTarget = _this.getRenderTarget();
  17375. _this.setRenderTarget( _transmissionRenderTarget );
  17376. _this.getClearColor( _currentClearColor );
  17377. _currentClearAlpha = _this.getClearAlpha();
  17378. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  17379. _this.clear();
  17380. // Turn off the features which can affect the frag color for opaque objects pass.
  17381. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  17382. const currentToneMapping = _this.toneMapping;
  17383. _this.toneMapping = NoToneMapping;
  17384. renderObjects( opaqueObjects, scene, camera );
  17385. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  17386. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  17387. let renderTargetNeedsUpdate = false;
  17388. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  17389. const renderItem = transmissiveObjects[ i ];
  17390. const object = renderItem.object;
  17391. const geometry = renderItem.geometry;
  17392. const material = renderItem.material;
  17393. const group = renderItem.group;
  17394. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  17395. const currentSide = material.side;
  17396. material.side = BackSide;
  17397. material.needsUpdate = true;
  17398. renderObject( object, scene, camera, geometry, material, group );
  17399. material.side = currentSide;
  17400. material.needsUpdate = true;
  17401. renderTargetNeedsUpdate = true;
  17402. }
  17403. }
  17404. if ( renderTargetNeedsUpdate === true ) {
  17405. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  17406. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  17407. }
  17408. _this.setRenderTarget( currentRenderTarget );
  17409. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  17410. _this.toneMapping = currentToneMapping;
  17411. }
  17412. function renderObjects( renderList, scene, camera ) {
  17413. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  17414. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  17415. const renderItem = renderList[ i ];
  17416. const object = renderItem.object;
  17417. const geometry = renderItem.geometry;
  17418. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  17419. const group = renderItem.group;
  17420. if ( object.layers.test( camera.layers ) ) {
  17421. renderObject( object, scene, camera, geometry, material, group );
  17422. }
  17423. }
  17424. }
  17425. function renderObject( object, scene, camera, geometry, material, group ) {
  17426. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  17427. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  17428. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  17429. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  17430. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  17431. material.side = BackSide;
  17432. material.needsUpdate = true;
  17433. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17434. material.side = FrontSide;
  17435. material.needsUpdate = true;
  17436. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17437. material.side = DoubleSide;
  17438. } else {
  17439. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17440. }
  17441. object.onAfterRender( _this, scene, camera, geometry, material, group );
  17442. }
  17443. function getProgram( material, scene, object ) {
  17444. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17445. const materialProperties = properties.get( material );
  17446. const lights = currentRenderState.state.lights;
  17447. const shadowsArray = currentRenderState.state.shadowsArray;
  17448. const lightsStateVersion = lights.state.version;
  17449. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  17450. const programCacheKey = programCache.getProgramCacheKey( parameters );
  17451. let programs = materialProperties.programs;
  17452. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  17453. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  17454. materialProperties.fog = scene.fog;
  17455. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  17456. if ( programs === undefined ) {
  17457. // new material
  17458. material.addEventListener( 'dispose', onMaterialDispose );
  17459. programs = new Map();
  17460. materialProperties.programs = programs;
  17461. }
  17462. let program = programs.get( programCacheKey );
  17463. if ( program !== undefined ) {
  17464. // early out if program and light state is identical
  17465. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  17466. updateCommonMaterialProperties( material, parameters );
  17467. return program;
  17468. }
  17469. } else {
  17470. parameters.uniforms = programCache.getUniforms( material );
  17471. material.onBuild( object, parameters, _this );
  17472. material.onBeforeCompile( parameters, _this );
  17473. program = programCache.acquireProgram( parameters, programCacheKey );
  17474. programs.set( programCacheKey, program );
  17475. materialProperties.uniforms = parameters.uniforms;
  17476. }
  17477. const uniforms = materialProperties.uniforms;
  17478. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  17479. uniforms.clippingPlanes = clipping.uniform;
  17480. }
  17481. updateCommonMaterialProperties( material, parameters );
  17482. // store the light setup it was created for
  17483. materialProperties.needsLights = materialNeedsLights( material );
  17484. materialProperties.lightsStateVersion = lightsStateVersion;
  17485. if ( materialProperties.needsLights ) {
  17486. // wire up the material to this renderer's lighting state
  17487. uniforms.ambientLightColor.value = lights.state.ambient;
  17488. uniforms.lightProbe.value = lights.state.probe;
  17489. uniforms.directionalLights.value = lights.state.directional;
  17490. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  17491. uniforms.spotLights.value = lights.state.spot;
  17492. uniforms.spotLightShadows.value = lights.state.spotShadow;
  17493. uniforms.rectAreaLights.value = lights.state.rectArea;
  17494. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  17495. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  17496. uniforms.pointLights.value = lights.state.point;
  17497. uniforms.pointLightShadows.value = lights.state.pointShadow;
  17498. uniforms.hemisphereLights.value = lights.state.hemi;
  17499. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  17500. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  17501. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  17502. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  17503. uniforms.spotLightMap.value = lights.state.spotLightMap;
  17504. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  17505. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  17506. // TODO (abelnation): add area lights shadow info to uniforms
  17507. }
  17508. const progUniforms = program.getUniforms();
  17509. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  17510. materialProperties.currentProgram = program;
  17511. materialProperties.uniformsList = uniformsList;
  17512. return program;
  17513. }
  17514. function updateCommonMaterialProperties( material, parameters ) {
  17515. const materialProperties = properties.get( material );
  17516. materialProperties.outputColorSpace = parameters.outputColorSpace;
  17517. materialProperties.instancing = parameters.instancing;
  17518. materialProperties.skinning = parameters.skinning;
  17519. materialProperties.morphTargets = parameters.morphTargets;
  17520. materialProperties.morphNormals = parameters.morphNormals;
  17521. materialProperties.morphColors = parameters.morphColors;
  17522. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  17523. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  17524. materialProperties.numIntersection = parameters.numClipIntersection;
  17525. materialProperties.vertexAlphas = parameters.vertexAlphas;
  17526. materialProperties.vertexTangents = parameters.vertexTangents;
  17527. materialProperties.toneMapping = parameters.toneMapping;
  17528. }
  17529. function setProgram( camera, scene, geometry, material, object ) {
  17530. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17531. textures.resetTextureUnits();
  17532. const fog = scene.fog;
  17533. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  17534. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  17535. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  17536. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  17537. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  17538. const morphTargets = !! geometry.morphAttributes.position;
  17539. const morphNormals = !! geometry.morphAttributes.normal;
  17540. const morphColors = !! geometry.morphAttributes.color;
  17541. const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping;
  17542. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  17543. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  17544. const materialProperties = properties.get( material );
  17545. const lights = currentRenderState.state.lights;
  17546. if ( _clippingEnabled === true ) {
  17547. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  17548. const useCache =
  17549. camera === _currentCamera &&
  17550. material.id === _currentMaterialId;
  17551. // we might want to call this function with some ClippingGroup
  17552. // object instead of the material, once it becomes feasible
  17553. // (#8465, #8379)
  17554. clipping.setState( material, camera, useCache );
  17555. }
  17556. }
  17557. //
  17558. let needsProgramChange = false;
  17559. if ( material.version === materialProperties.__version ) {
  17560. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  17561. needsProgramChange = true;
  17562. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  17563. needsProgramChange = true;
  17564. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  17565. needsProgramChange = true;
  17566. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  17567. needsProgramChange = true;
  17568. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  17569. needsProgramChange = true;
  17570. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  17571. needsProgramChange = true;
  17572. } else if ( materialProperties.envMap !== envMap ) {
  17573. needsProgramChange = true;
  17574. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  17575. needsProgramChange = true;
  17576. } else if ( materialProperties.numClippingPlanes !== undefined &&
  17577. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  17578. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  17579. needsProgramChange = true;
  17580. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  17581. needsProgramChange = true;
  17582. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  17583. needsProgramChange = true;
  17584. } else if ( materialProperties.morphTargets !== morphTargets ) {
  17585. needsProgramChange = true;
  17586. } else if ( materialProperties.morphNormals !== morphNormals ) {
  17587. needsProgramChange = true;
  17588. } else if ( materialProperties.morphColors !== morphColors ) {
  17589. needsProgramChange = true;
  17590. } else if ( materialProperties.toneMapping !== toneMapping ) {
  17591. needsProgramChange = true;
  17592. } else if ( capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount ) {
  17593. needsProgramChange = true;
  17594. }
  17595. } else {
  17596. needsProgramChange = true;
  17597. materialProperties.__version = material.version;
  17598. }
  17599. //
  17600. let program = materialProperties.currentProgram;
  17601. if ( needsProgramChange === true ) {
  17602. program = getProgram( material, scene, object );
  17603. }
  17604. let refreshProgram = false;
  17605. let refreshMaterial = false;
  17606. let refreshLights = false;
  17607. const p_uniforms = program.getUniforms(),
  17608. m_uniforms = materialProperties.uniforms;
  17609. if ( state.useProgram( program.program ) ) {
  17610. refreshProgram = true;
  17611. refreshMaterial = true;
  17612. refreshLights = true;
  17613. }
  17614. if ( material.id !== _currentMaterialId ) {
  17615. _currentMaterialId = material.id;
  17616. refreshMaterial = true;
  17617. }
  17618. if ( refreshProgram || _currentCamera !== camera ) {
  17619. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  17620. if ( capabilities.logarithmicDepthBuffer ) {
  17621. p_uniforms.setValue( _gl, 'logDepthBufFC',
  17622. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  17623. }
  17624. if ( _currentCamera !== camera ) {
  17625. _currentCamera = camera;
  17626. // lighting uniforms depend on the camera so enforce an update
  17627. // now, in case this material supports lights - or later, when
  17628. // the next material that does gets activated:
  17629. refreshMaterial = true; // set to true on material change
  17630. refreshLights = true; // remains set until update done
  17631. }
  17632. // load material specific uniforms
  17633. // (shader material also gets them for the sake of genericity)
  17634. if ( material.isShaderMaterial ||
  17635. material.isMeshPhongMaterial ||
  17636. material.isMeshToonMaterial ||
  17637. material.isMeshStandardMaterial ||
  17638. material.envMap ) {
  17639. const uCamPos = p_uniforms.map.cameraPosition;
  17640. if ( uCamPos !== undefined ) {
  17641. uCamPos.setValue( _gl,
  17642. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  17643. }
  17644. }
  17645. if ( material.isMeshPhongMaterial ||
  17646. material.isMeshToonMaterial ||
  17647. material.isMeshLambertMaterial ||
  17648. material.isMeshBasicMaterial ||
  17649. material.isMeshStandardMaterial ||
  17650. material.isShaderMaterial ) {
  17651. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  17652. }
  17653. if ( material.isMeshPhongMaterial ||
  17654. material.isMeshToonMaterial ||
  17655. material.isMeshLambertMaterial ||
  17656. material.isMeshBasicMaterial ||
  17657. material.isMeshStandardMaterial ||
  17658. material.isShaderMaterial ||
  17659. material.isShadowMaterial ||
  17660. object.isSkinnedMesh ) {
  17661. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  17662. }
  17663. }
  17664. // skinning and morph target uniforms must be set even if material didn't change
  17665. // auto-setting of texture unit for bone and morph texture must go before other textures
  17666. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  17667. if ( object.isSkinnedMesh ) {
  17668. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  17669. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  17670. const skeleton = object.skeleton;
  17671. if ( skeleton ) {
  17672. if ( capabilities.floatVertexTextures ) {
  17673. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  17674. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  17675. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  17676. } else {
  17677. console.warn( 'THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.' );
  17678. }
  17679. }
  17680. }
  17681. const morphAttributes = geometry.morphAttributes;
  17682. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined && capabilities.isWebGL2 === true ) ) {
  17683. morphtargets.update( object, geometry, program );
  17684. }
  17685. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  17686. materialProperties.receiveShadow = object.receiveShadow;
  17687. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  17688. }
  17689. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  17690. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  17691. m_uniforms.envMap.value = envMap;
  17692. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  17693. }
  17694. if ( refreshMaterial ) {
  17695. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  17696. if ( materialProperties.needsLights ) {
  17697. // the current material requires lighting info
  17698. // note: all lighting uniforms are always set correctly
  17699. // they simply reference the renderer's state for their
  17700. // values
  17701. //
  17702. // use the current material's .needsUpdate flags to set
  17703. // the GL state when required
  17704. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  17705. }
  17706. // refresh uniforms common to several materials
  17707. if ( fog && material.fog === true ) {
  17708. materials.refreshFogUniforms( m_uniforms, fog );
  17709. }
  17710. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget );
  17711. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17712. }
  17713. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  17714. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17715. material.uniformsNeedUpdate = false;
  17716. }
  17717. if ( material.isSpriteMaterial ) {
  17718. p_uniforms.setValue( _gl, 'center', object.center );
  17719. }
  17720. // common matrices
  17721. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  17722. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  17723. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  17724. // UBOs
  17725. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  17726. const groups = material.uniformsGroups;
  17727. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17728. if ( capabilities.isWebGL2 ) {
  17729. const group = groups[ i ];
  17730. uniformsGroups.update( group, program );
  17731. uniformsGroups.bind( group, program );
  17732. } else {
  17733. console.warn( 'THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.' );
  17734. }
  17735. }
  17736. }
  17737. return program;
  17738. }
  17739. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  17740. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  17741. uniforms.ambientLightColor.needsUpdate = value;
  17742. uniforms.lightProbe.needsUpdate = value;
  17743. uniforms.directionalLights.needsUpdate = value;
  17744. uniforms.directionalLightShadows.needsUpdate = value;
  17745. uniforms.pointLights.needsUpdate = value;
  17746. uniforms.pointLightShadows.needsUpdate = value;
  17747. uniforms.spotLights.needsUpdate = value;
  17748. uniforms.spotLightShadows.needsUpdate = value;
  17749. uniforms.rectAreaLights.needsUpdate = value;
  17750. uniforms.hemisphereLights.needsUpdate = value;
  17751. }
  17752. function materialNeedsLights( material ) {
  17753. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  17754. material.isMeshStandardMaterial || material.isShadowMaterial ||
  17755. ( material.isShaderMaterial && material.lights === true );
  17756. }
  17757. this.getActiveCubeFace = function () {
  17758. return _currentActiveCubeFace;
  17759. };
  17760. this.getActiveMipmapLevel = function () {
  17761. return _currentActiveMipmapLevel;
  17762. };
  17763. this.getRenderTarget = function () {
  17764. return _currentRenderTarget;
  17765. };
  17766. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  17767. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  17768. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  17769. const renderTargetProperties = properties.get( renderTarget );
  17770. renderTargetProperties.__hasExternalTextures = true;
  17771. if ( renderTargetProperties.__hasExternalTextures ) {
  17772. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  17773. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  17774. // The multisample_render_to_texture extension doesn't work properly if there
  17775. // are midframe flushes and an external depth buffer. Disable use of the extension.
  17776. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  17777. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  17778. renderTargetProperties.__useRenderToTexture = false;
  17779. }
  17780. }
  17781. }
  17782. };
  17783. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  17784. const renderTargetProperties = properties.get( renderTarget );
  17785. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  17786. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  17787. };
  17788. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  17789. _currentRenderTarget = renderTarget;
  17790. _currentActiveCubeFace = activeCubeFace;
  17791. _currentActiveMipmapLevel = activeMipmapLevel;
  17792. let useDefaultFramebuffer = true;
  17793. let framebuffer = null;
  17794. let isCube = false;
  17795. let isRenderTarget3D = false;
  17796. if ( renderTarget ) {
  17797. const renderTargetProperties = properties.get( renderTarget );
  17798. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  17799. // We need to make sure to rebind the framebuffer.
  17800. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  17801. useDefaultFramebuffer = false;
  17802. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  17803. textures.setupRenderTarget( renderTarget );
  17804. } else if ( renderTargetProperties.__hasExternalTextures ) {
  17805. // Color and depth texture must be rebound in order for the swapchain to update.
  17806. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  17807. }
  17808. const texture = renderTarget.texture;
  17809. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  17810. isRenderTarget3D = true;
  17811. }
  17812. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17813. if ( renderTarget.isWebGLCubeRenderTarget ) {
  17814. framebuffer = __webglFramebuffer[ activeCubeFace ];
  17815. isCube = true;
  17816. } else if ( ( capabilities.isWebGL2 && renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  17817. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  17818. } else {
  17819. framebuffer = __webglFramebuffer;
  17820. }
  17821. _currentViewport.copy( renderTarget.viewport );
  17822. _currentScissor.copy( renderTarget.scissor );
  17823. _currentScissorTest = renderTarget.scissorTest;
  17824. } else {
  17825. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  17826. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  17827. _currentScissorTest = _scissorTest;
  17828. }
  17829. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  17830. if ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) {
  17831. state.drawBuffers( renderTarget, framebuffer );
  17832. }
  17833. state.viewport( _currentViewport );
  17834. state.scissor( _currentScissor );
  17835. state.setScissorTest( _currentScissorTest );
  17836. if ( isCube ) {
  17837. const textureProperties = properties.get( renderTarget.texture );
  17838. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  17839. } else if ( isRenderTarget3D ) {
  17840. const textureProperties = properties.get( renderTarget.texture );
  17841. const layer = activeCubeFace || 0;
  17842. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  17843. }
  17844. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  17845. };
  17846. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  17847. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  17848. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  17849. return;
  17850. }
  17851. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17852. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  17853. framebuffer = framebuffer[ activeCubeFaceIndex ];
  17854. }
  17855. if ( framebuffer ) {
  17856. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  17857. try {
  17858. const texture = renderTarget.texture;
  17859. const textureFormat = texture.format;
  17860. const textureType = texture.type;
  17861. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  17862. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  17863. return;
  17864. }
  17865. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) );
  17866. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  17867. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  17868. ! halfFloatSupportedByExt ) {
  17869. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  17870. return;
  17871. }
  17872. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  17873. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  17874. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  17875. }
  17876. } finally {
  17877. // restore framebuffer of current render target if necessary
  17878. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  17879. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  17880. }
  17881. }
  17882. };
  17883. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  17884. const levelScale = Math.pow( 2, - level );
  17885. const width = Math.floor( texture.image.width * levelScale );
  17886. const height = Math.floor( texture.image.height * levelScale );
  17887. textures.setTexture2D( texture, 0 );
  17888. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, position.x, position.y, width, height );
  17889. state.unbindTexture();
  17890. };
  17891. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  17892. const width = srcTexture.image.width;
  17893. const height = srcTexture.image.height;
  17894. const glFormat = utils.convert( dstTexture.format );
  17895. const glType = utils.convert( dstTexture.type );
  17896. textures.setTexture2D( dstTexture, 0 );
  17897. // As another texture upload may have changed pixelStorei
  17898. // parameters, make sure they are correct for the dstTexture
  17899. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  17900. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  17901. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  17902. if ( srcTexture.isDataTexture ) {
  17903. _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  17904. } else {
  17905. if ( srcTexture.isCompressedTexture ) {
  17906. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  17907. } else {
  17908. _gl.texSubImage2D( _gl.TEXTURE_2D, level, position.x, position.y, glFormat, glType, srcTexture.image );
  17909. }
  17910. }
  17911. // Generate mipmaps only when copying level 0
  17912. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( _gl.TEXTURE_2D );
  17913. state.unbindTexture();
  17914. };
  17915. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  17916. if ( _this.isWebGL1Renderer ) {
  17917. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' );
  17918. return;
  17919. }
  17920. const width = sourceBox.max.x - sourceBox.min.x + 1;
  17921. const height = sourceBox.max.y - sourceBox.min.y + 1;
  17922. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  17923. const glFormat = utils.convert( dstTexture.format );
  17924. const glType = utils.convert( dstTexture.type );
  17925. let glTarget;
  17926. if ( dstTexture.isData3DTexture ) {
  17927. textures.setTexture3D( dstTexture, 0 );
  17928. glTarget = _gl.TEXTURE_3D;
  17929. } else if ( dstTexture.isDataArrayTexture ) {
  17930. textures.setTexture2DArray( dstTexture, 0 );
  17931. glTarget = _gl.TEXTURE_2D_ARRAY;
  17932. } else {
  17933. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  17934. return;
  17935. }
  17936. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  17937. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  17938. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  17939. const unpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  17940. const unpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  17941. const unpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  17942. const unpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  17943. const unpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  17944. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image;
  17945. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  17946. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  17947. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, sourceBox.min.x );
  17948. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, sourceBox.min.y );
  17949. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, sourceBox.min.z );
  17950. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  17951. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data );
  17952. } else {
  17953. if ( srcTexture.isCompressedArrayTexture ) {
  17954. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' );
  17955. _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data );
  17956. } else {
  17957. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image );
  17958. }
  17959. }
  17960. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, unpackRowLen );
  17961. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, unpackImageHeight );
  17962. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, unpackSkipPixels );
  17963. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, unpackSkipRows );
  17964. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, unpackSkipImages );
  17965. // Generate mipmaps only when copying level 0
  17966. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  17967. state.unbindTexture();
  17968. };
  17969. this.initTexture = function ( texture ) {
  17970. if ( texture.isCubeTexture ) {
  17971. textures.setTextureCube( texture, 0 );
  17972. } else if ( texture.isData3DTexture ) {
  17973. textures.setTexture3D( texture, 0 );
  17974. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  17975. textures.setTexture2DArray( texture, 0 );
  17976. } else {
  17977. textures.setTexture2D( texture, 0 );
  17978. }
  17979. state.unbindTexture();
  17980. };
  17981. this.resetState = function () {
  17982. _currentActiveCubeFace = 0;
  17983. _currentActiveMipmapLevel = 0;
  17984. _currentRenderTarget = null;
  17985. state.reset();
  17986. bindingStates.reset();
  17987. };
  17988. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17989. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17990. }
  17991. }
  17992. get coordinateSystem() {
  17993. return WebGLCoordinateSystem;
  17994. }
  17995. get physicallyCorrectLights() { // @deprecated, r150
  17996. console.warn( 'THREE.WebGLRenderer: the property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead.' );
  17997. return ! this.useLegacyLights;
  17998. }
  17999. set physicallyCorrectLights( value ) { // @deprecated, r150
  18000. console.warn( 'THREE.WebGLRenderer: the property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead.' );
  18001. this.useLegacyLights = ! value;
  18002. }
  18003. get outputEncoding() { // @deprecated, r152
  18004. console.warn( 'THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead.' );
  18005. return this.outputColorSpace === SRGBColorSpace ? sRGBEncoding : LinearEncoding;
  18006. }
  18007. set outputEncoding( encoding ) { // @deprecated, r152
  18008. console.warn( 'THREE.WebGLRenderer: Property .outputEncoding has been removed. Use .outputColorSpace instead.' );
  18009. this.outputColorSpace = encoding === sRGBEncoding ? SRGBColorSpace : LinearSRGBColorSpace;
  18010. }
  18011. }
  18012. class WebGL1Renderer extends WebGLRenderer {}
  18013. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  18014. class FogExp2 {
  18015. constructor( color, density = 0.00025 ) {
  18016. this.isFogExp2 = true;
  18017. this.name = '';
  18018. this.color = new Color( color );
  18019. this.density = density;
  18020. }
  18021. clone() {
  18022. return new FogExp2( this.color, this.density );
  18023. }
  18024. toJSON( /* meta */ ) {
  18025. return {
  18026. type: 'FogExp2',
  18027. color: this.color.getHex(),
  18028. density: this.density
  18029. };
  18030. }
  18031. }
  18032. class Fog {
  18033. constructor( color, near = 1, far = 1000 ) {
  18034. this.isFog = true;
  18035. this.name = '';
  18036. this.color = new Color( color );
  18037. this.near = near;
  18038. this.far = far;
  18039. }
  18040. clone() {
  18041. return new Fog( this.color, this.near, this.far );
  18042. }
  18043. toJSON( /* meta */ ) {
  18044. return {
  18045. type: 'Fog',
  18046. color: this.color.getHex(),
  18047. near: this.near,
  18048. far: this.far
  18049. };
  18050. }
  18051. }
  18052. class Scene extends Object3D {
  18053. constructor() {
  18054. super();
  18055. this.isScene = true;
  18056. this.type = 'Scene';
  18057. this.background = null;
  18058. this.environment = null;
  18059. this.fog = null;
  18060. this.backgroundBlurriness = 0;
  18061. this.backgroundIntensity = 1;
  18062. this.overrideMaterial = null;
  18063. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  18064. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  18065. }
  18066. }
  18067. copy( source, recursive ) {
  18068. super.copy( source, recursive );
  18069. if ( source.background !== null ) this.background = source.background.clone();
  18070. if ( source.environment !== null ) this.environment = source.environment.clone();
  18071. if ( source.fog !== null ) this.fog = source.fog.clone();
  18072. this.backgroundBlurriness = source.backgroundBlurriness;
  18073. this.backgroundIntensity = source.backgroundIntensity;
  18074. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  18075. this.matrixAutoUpdate = source.matrixAutoUpdate;
  18076. return this;
  18077. }
  18078. toJSON( meta ) {
  18079. const data = super.toJSON( meta );
  18080. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  18081. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  18082. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  18083. return data;
  18084. }
  18085. }
  18086. class InterleavedBuffer {
  18087. constructor( array, stride ) {
  18088. this.isInterleavedBuffer = true;
  18089. this.array = array;
  18090. this.stride = stride;
  18091. this.count = array !== undefined ? array.length / stride : 0;
  18092. this.usage = StaticDrawUsage;
  18093. this.updateRange = { offset: 0, count: - 1 };
  18094. this.version = 0;
  18095. this.uuid = generateUUID();
  18096. }
  18097. onUploadCallback() {}
  18098. set needsUpdate( value ) {
  18099. if ( value === true ) this.version ++;
  18100. }
  18101. setUsage( value ) {
  18102. this.usage = value;
  18103. return this;
  18104. }
  18105. copy( source ) {
  18106. this.array = new source.array.constructor( source.array );
  18107. this.count = source.count;
  18108. this.stride = source.stride;
  18109. this.usage = source.usage;
  18110. return this;
  18111. }
  18112. copyAt( index1, attribute, index2 ) {
  18113. index1 *= this.stride;
  18114. index2 *= attribute.stride;
  18115. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  18116. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  18117. }
  18118. return this;
  18119. }
  18120. set( value, offset = 0 ) {
  18121. this.array.set( value, offset );
  18122. return this;
  18123. }
  18124. clone( data ) {
  18125. if ( data.arrayBuffers === undefined ) {
  18126. data.arrayBuffers = {};
  18127. }
  18128. if ( this.array.buffer._uuid === undefined ) {
  18129. this.array.buffer._uuid = generateUUID();
  18130. }
  18131. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  18132. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  18133. }
  18134. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  18135. const ib = new this.constructor( array, this.stride );
  18136. ib.setUsage( this.usage );
  18137. return ib;
  18138. }
  18139. onUpload( callback ) {
  18140. this.onUploadCallback = callback;
  18141. return this;
  18142. }
  18143. toJSON( data ) {
  18144. if ( data.arrayBuffers === undefined ) {
  18145. data.arrayBuffers = {};
  18146. }
  18147. // generate UUID for array buffer if necessary
  18148. if ( this.array.buffer._uuid === undefined ) {
  18149. this.array.buffer._uuid = generateUUID();
  18150. }
  18151. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  18152. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  18153. }
  18154. //
  18155. return {
  18156. uuid: this.uuid,
  18157. buffer: this.array.buffer._uuid,
  18158. type: this.array.constructor.name,
  18159. stride: this.stride
  18160. };
  18161. }
  18162. }
  18163. const _vector$5 = /*@__PURE__*/ new Vector3();
  18164. class InterleavedBufferAttribute {
  18165. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  18166. this.isInterleavedBufferAttribute = true;
  18167. this.name = '';
  18168. this.data = interleavedBuffer;
  18169. this.itemSize = itemSize;
  18170. this.offset = offset;
  18171. this.normalized = normalized;
  18172. }
  18173. get count() {
  18174. return this.data.count;
  18175. }
  18176. get array() {
  18177. return this.data.array;
  18178. }
  18179. set needsUpdate( value ) {
  18180. this.data.needsUpdate = value;
  18181. }
  18182. applyMatrix4( m ) {
  18183. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  18184. _vector$5.fromBufferAttribute( this, i );
  18185. _vector$5.applyMatrix4( m );
  18186. this.setXYZ( i, _vector$5.x, _vector$5.y, _vector$5.z );
  18187. }
  18188. return this;
  18189. }
  18190. applyNormalMatrix( m ) {
  18191. for ( let i = 0, l = this.count; i < l; i ++ ) {
  18192. _vector$5.fromBufferAttribute( this, i );
  18193. _vector$5.applyNormalMatrix( m );
  18194. this.setXYZ( i, _vector$5.x, _vector$5.y, _vector$5.z );
  18195. }
  18196. return this;
  18197. }
  18198. transformDirection( m ) {
  18199. for ( let i = 0, l = this.count; i < l; i ++ ) {
  18200. _vector$5.fromBufferAttribute( this, i );
  18201. _vector$5.transformDirection( m );
  18202. this.setXYZ( i, _vector$5.x, _vector$5.y, _vector$5.z );
  18203. }
  18204. return this;
  18205. }
  18206. setX( index, x ) {
  18207. if ( this.normalized ) x = normalize( x, this.array );
  18208. this.data.array[ index * this.data.stride + this.offset ] = x;
  18209. return this;
  18210. }
  18211. setY( index, y ) {
  18212. if ( this.normalized ) y = normalize( y, this.array );
  18213. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  18214. return this;
  18215. }
  18216. setZ( index, z ) {
  18217. if ( this.normalized ) z = normalize( z, this.array );
  18218. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  18219. return this;
  18220. }
  18221. setW( index, w ) {
  18222. if ( this.normalized ) w = normalize( w, this.array );
  18223. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  18224. return this;
  18225. }
  18226. getX( index ) {
  18227. let x = this.data.array[ index * this.data.stride + this.offset ];
  18228. if ( this.normalized ) x = denormalize( x, this.array );
  18229. return x;
  18230. }
  18231. getY( index ) {
  18232. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  18233. if ( this.normalized ) y = denormalize( y, this.array );
  18234. return y;
  18235. }
  18236. getZ( index ) {
  18237. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  18238. if ( this.normalized ) z = denormalize( z, this.array );
  18239. return z;
  18240. }
  18241. getW( index ) {
  18242. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  18243. if ( this.normalized ) w = denormalize( w, this.array );
  18244. return w;
  18245. }
  18246. setXY( index, x, y ) {
  18247. index = index * this.data.stride + this.offset;
  18248. if ( this.normalized ) {
  18249. x = normalize( x, this.array );
  18250. y = normalize( y, this.array );
  18251. }
  18252. this.data.array[ index + 0 ] = x;
  18253. this.data.array[ index + 1 ] = y;
  18254. return this;
  18255. }
  18256. setXYZ( index, x, y, z ) {
  18257. index = index * this.data.stride + this.offset;
  18258. if ( this.normalized ) {
  18259. x = normalize( x, this.array );
  18260. y = normalize( y, this.array );
  18261. z = normalize( z, this.array );
  18262. }
  18263. this.data.array[ index + 0 ] = x;
  18264. this.data.array[ index + 1 ] = y;
  18265. this.data.array[ index + 2 ] = z;
  18266. return this;
  18267. }
  18268. setXYZW( index, x, y, z, w ) {
  18269. index = index * this.data.stride + this.offset;
  18270. if ( this.normalized ) {
  18271. x = normalize( x, this.array );
  18272. y = normalize( y, this.array );
  18273. z = normalize( z, this.array );
  18274. w = normalize( w, this.array );
  18275. }
  18276. this.data.array[ index + 0 ] = x;
  18277. this.data.array[ index + 1 ] = y;
  18278. this.data.array[ index + 2 ] = z;
  18279. this.data.array[ index + 3 ] = w;
  18280. return this;
  18281. }
  18282. clone( data ) {
  18283. if ( data === undefined ) {
  18284. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  18285. const array = [];
  18286. for ( let i = 0; i < this.count; i ++ ) {
  18287. const index = i * this.data.stride + this.offset;
  18288. for ( let j = 0; j < this.itemSize; j ++ ) {
  18289. array.push( this.data.array[ index + j ] );
  18290. }
  18291. }
  18292. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  18293. } else {
  18294. if ( data.interleavedBuffers === undefined ) {
  18295. data.interleavedBuffers = {};
  18296. }
  18297. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  18298. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  18299. }
  18300. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  18301. }
  18302. }
  18303. toJSON( data ) {
  18304. if ( data === undefined ) {
  18305. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  18306. const array = [];
  18307. for ( let i = 0; i < this.count; i ++ ) {
  18308. const index = i * this.data.stride + this.offset;
  18309. for ( let j = 0; j < this.itemSize; j ++ ) {
  18310. array.push( this.data.array[ index + j ] );
  18311. }
  18312. }
  18313. // de-interleave data and save it as an ordinary buffer attribute for now
  18314. return {
  18315. itemSize: this.itemSize,
  18316. type: this.array.constructor.name,
  18317. array: array,
  18318. normalized: this.normalized
  18319. };
  18320. } else {
  18321. // save as true interleaved attribute
  18322. if ( data.interleavedBuffers === undefined ) {
  18323. data.interleavedBuffers = {};
  18324. }
  18325. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  18326. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  18327. }
  18328. return {
  18329. isInterleavedBufferAttribute: true,
  18330. itemSize: this.itemSize,
  18331. data: this.data.uuid,
  18332. offset: this.offset,
  18333. normalized: this.normalized
  18334. };
  18335. }
  18336. }
  18337. }
  18338. class SpriteMaterial extends Material {
  18339. constructor( parameters ) {
  18340. super();
  18341. this.isSpriteMaterial = true;
  18342. this.type = 'SpriteMaterial';
  18343. this.color = new Color( 0xffffff );
  18344. this.map = null;
  18345. this.alphaMap = null;
  18346. this.rotation = 0;
  18347. this.sizeAttenuation = true;
  18348. this.transparent = true;
  18349. this.fog = true;
  18350. this.setValues( parameters );
  18351. }
  18352. copy( source ) {
  18353. super.copy( source );
  18354. this.color.copy( source.color );
  18355. this.map = source.map;
  18356. this.alphaMap = source.alphaMap;
  18357. this.rotation = source.rotation;
  18358. this.sizeAttenuation = source.sizeAttenuation;
  18359. this.fog = source.fog;
  18360. return this;
  18361. }
  18362. }
  18363. let _geometry;
  18364. const _intersectPoint = /*@__PURE__*/ new Vector3();
  18365. const _worldScale = /*@__PURE__*/ new Vector3();
  18366. const _mvPosition = /*@__PURE__*/ new Vector3();
  18367. const _alignedPosition = /*@__PURE__*/ new Vector2();
  18368. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  18369. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  18370. const _vA = /*@__PURE__*/ new Vector3();
  18371. const _vB = /*@__PURE__*/ new Vector3();
  18372. const _vC = /*@__PURE__*/ new Vector3();
  18373. const _uvA = /*@__PURE__*/ new Vector2();
  18374. const _uvB = /*@__PURE__*/ new Vector2();
  18375. const _uvC = /*@__PURE__*/ new Vector2();
  18376. class Sprite extends Object3D {
  18377. constructor( material ) {
  18378. super();
  18379. this.isSprite = true;
  18380. this.type = 'Sprite';
  18381. if ( _geometry === undefined ) {
  18382. _geometry = new BufferGeometry();
  18383. const float32Array = new Float32Array( [
  18384. - 0.5, - 0.5, 0, 0, 0,
  18385. 0.5, - 0.5, 0, 1, 0,
  18386. 0.5, 0.5, 0, 1, 1,
  18387. - 0.5, 0.5, 0, 0, 1
  18388. ] );
  18389. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  18390. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  18391. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  18392. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  18393. }
  18394. this.geometry = _geometry;
  18395. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  18396. this.center = new Vector2( 0.5, 0.5 );
  18397. }
  18398. raycast( raycaster, intersects ) {
  18399. if ( raycaster.camera === null ) {
  18400. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18401. }
  18402. _worldScale.setFromMatrixScale( this.matrixWorld );
  18403. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18404. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18405. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18406. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18407. _worldScale.multiplyScalar( - _mvPosition.z );
  18408. }
  18409. const rotation = this.material.rotation;
  18410. let sin, cos;
  18411. if ( rotation !== 0 ) {
  18412. cos = Math.cos( rotation );
  18413. sin = Math.sin( rotation );
  18414. }
  18415. const center = this.center;
  18416. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18417. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18418. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18419. _uvA.set( 0, 0 );
  18420. _uvB.set( 1, 0 );
  18421. _uvC.set( 1, 1 );
  18422. // check first triangle
  18423. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18424. if ( intersect === null ) {
  18425. // check second triangle
  18426. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18427. _uvB.set( 0, 1 );
  18428. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18429. if ( intersect === null ) {
  18430. return;
  18431. }
  18432. }
  18433. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18434. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18435. intersects.push( {
  18436. distance: distance,
  18437. point: _intersectPoint.clone(),
  18438. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18439. face: null,
  18440. object: this
  18441. } );
  18442. }
  18443. copy( source, recursive ) {
  18444. super.copy( source, recursive );
  18445. if ( source.center !== undefined ) this.center.copy( source.center );
  18446. this.material = source.material;
  18447. return this;
  18448. }
  18449. }
  18450. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18451. // compute position in camera space
  18452. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18453. // to check if rotation is not zero
  18454. if ( sin !== undefined ) {
  18455. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  18456. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  18457. } else {
  18458. _rotatedPosition.copy( _alignedPosition );
  18459. }
  18460. vertexPosition.copy( mvPosition );
  18461. vertexPosition.x += _rotatedPosition.x;
  18462. vertexPosition.y += _rotatedPosition.y;
  18463. // transform to world space
  18464. vertexPosition.applyMatrix4( _viewWorldMatrix );
  18465. }
  18466. const _v1$2 = /*@__PURE__*/ new Vector3();
  18467. const _v2$1 = /*@__PURE__*/ new Vector3();
  18468. class LOD extends Object3D {
  18469. constructor() {
  18470. super();
  18471. this._currentLevel = 0;
  18472. this.type = 'LOD';
  18473. Object.defineProperties( this, {
  18474. levels: {
  18475. enumerable: true,
  18476. value: []
  18477. },
  18478. isLOD: {
  18479. value: true,
  18480. }
  18481. } );
  18482. this.autoUpdate = true;
  18483. }
  18484. copy( source ) {
  18485. super.copy( source, false );
  18486. const levels = source.levels;
  18487. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18488. const level = levels[ i ];
  18489. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  18490. }
  18491. this.autoUpdate = source.autoUpdate;
  18492. return this;
  18493. }
  18494. addLevel( object, distance = 0, hysteresis = 0 ) {
  18495. distance = Math.abs( distance );
  18496. const levels = this.levels;
  18497. let l;
  18498. for ( l = 0; l < levels.length; l ++ ) {
  18499. if ( distance < levels[ l ].distance ) {
  18500. break;
  18501. }
  18502. }
  18503. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18504. this.add( object );
  18505. return this;
  18506. }
  18507. getCurrentLevel() {
  18508. return this._currentLevel;
  18509. }
  18510. getObjectForDistance( distance ) {
  18511. const levels = this.levels;
  18512. if ( levels.length > 0 ) {
  18513. let i, l;
  18514. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18515. let levelDistance = levels[ i ].distance;
  18516. if ( levels[ i ].object.visible ) {
  18517. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18518. }
  18519. if ( distance < levelDistance ) {
  18520. break;
  18521. }
  18522. }
  18523. return levels[ i - 1 ].object;
  18524. }
  18525. return null;
  18526. }
  18527. raycast( raycaster, intersects ) {
  18528. const levels = this.levels;
  18529. if ( levels.length > 0 ) {
  18530. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18531. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18532. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18533. }
  18534. }
  18535. update( camera ) {
  18536. const levels = this.levels;
  18537. if ( levels.length > 1 ) {
  18538. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18539. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18540. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18541. levels[ 0 ].object.visible = true;
  18542. let i, l;
  18543. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18544. let levelDistance = levels[ i ].distance;
  18545. if ( levels[ i ].object.visible ) {
  18546. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18547. }
  18548. if ( distance >= levelDistance ) {
  18549. levels[ i - 1 ].object.visible = false;
  18550. levels[ i ].object.visible = true;
  18551. } else {
  18552. break;
  18553. }
  18554. }
  18555. this._currentLevel = i - 1;
  18556. for ( ; i < l; i ++ ) {
  18557. levels[ i ].object.visible = false;
  18558. }
  18559. }
  18560. }
  18561. toJSON( meta ) {
  18562. const data = super.toJSON( meta );
  18563. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18564. data.object.levels = [];
  18565. const levels = this.levels;
  18566. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18567. const level = levels[ i ];
  18568. data.object.levels.push( {
  18569. object: level.object.uuid,
  18570. distance: level.distance,
  18571. hysteresis: level.hysteresis
  18572. } );
  18573. }
  18574. return data;
  18575. }
  18576. }
  18577. const _basePosition = /*@__PURE__*/ new Vector3();
  18578. const _skinIndex = /*@__PURE__*/ new Vector4();
  18579. const _skinWeight = /*@__PURE__*/ new Vector4();
  18580. const _vector3 = /*@__PURE__*/ new Vector3();
  18581. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18582. const _vertex = /*@__PURE__*/ new Vector3();
  18583. const _sphere$3 = /*@__PURE__*/ new Sphere();
  18584. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  18585. const _ray$2 = /*@__PURE__*/ new Ray();
  18586. class SkinnedMesh extends Mesh {
  18587. constructor( geometry, material ) {
  18588. super( geometry, material );
  18589. this.isSkinnedMesh = true;
  18590. this.type = 'SkinnedMesh';
  18591. this.bindMode = 'attached';
  18592. this.bindMatrix = new Matrix4();
  18593. this.bindMatrixInverse = new Matrix4();
  18594. this.boundingBox = null;
  18595. this.boundingSphere = null;
  18596. }
  18597. computeBoundingBox() {
  18598. const geometry = this.geometry;
  18599. if ( this.boundingBox === null ) {
  18600. this.boundingBox = new Box3();
  18601. }
  18602. this.boundingBox.makeEmpty();
  18603. const positionAttribute = geometry.getAttribute( 'position' );
  18604. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18605. _vertex.fromBufferAttribute( positionAttribute, i );
  18606. this.applyBoneTransform( i, _vertex );
  18607. this.boundingBox.expandByPoint( _vertex );
  18608. }
  18609. }
  18610. computeBoundingSphere() {
  18611. const geometry = this.geometry;
  18612. if ( this.boundingSphere === null ) {
  18613. this.boundingSphere = new Sphere();
  18614. }
  18615. this.boundingSphere.makeEmpty();
  18616. const positionAttribute = geometry.getAttribute( 'position' );
  18617. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18618. _vertex.fromBufferAttribute( positionAttribute, i );
  18619. this.applyBoneTransform( i, _vertex );
  18620. this.boundingSphere.expandByPoint( _vertex );
  18621. }
  18622. }
  18623. copy( source, recursive ) {
  18624. super.copy( source, recursive );
  18625. this.bindMode = source.bindMode;
  18626. this.bindMatrix.copy( source.bindMatrix );
  18627. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18628. this.skeleton = source.skeleton;
  18629. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18630. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18631. return this;
  18632. }
  18633. raycast( raycaster, intersects ) {
  18634. const material = this.material;
  18635. const matrixWorld = this.matrixWorld;
  18636. if ( material === undefined ) return;
  18637. // test with bounding sphere in world space
  18638. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18639. _sphere$3.copy( this.boundingSphere );
  18640. _sphere$3.applyMatrix4( matrixWorld );
  18641. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  18642. // convert ray to local space of skinned mesh
  18643. _inverseMatrix$2.copy( matrixWorld ).invert();
  18644. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  18645. // test with bounding box in local space
  18646. if ( this.boundingBox !== null ) {
  18647. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  18648. }
  18649. // test for intersections with geometry
  18650. this._computeIntersections( raycaster, intersects, _ray$2 );
  18651. }
  18652. getVertexPosition( index, target ) {
  18653. super.getVertexPosition( index, target );
  18654. this.applyBoneTransform( index, target );
  18655. return target;
  18656. }
  18657. bind( skeleton, bindMatrix ) {
  18658. this.skeleton = skeleton;
  18659. if ( bindMatrix === undefined ) {
  18660. this.updateMatrixWorld( true );
  18661. this.skeleton.calculateInverses();
  18662. bindMatrix = this.matrixWorld;
  18663. }
  18664. this.bindMatrix.copy( bindMatrix );
  18665. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18666. }
  18667. pose() {
  18668. this.skeleton.pose();
  18669. }
  18670. normalizeSkinWeights() {
  18671. const vector = new Vector4();
  18672. const skinWeight = this.geometry.attributes.skinWeight;
  18673. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18674. vector.fromBufferAttribute( skinWeight, i );
  18675. const scale = 1.0 / vector.manhattanLength();
  18676. if ( scale !== Infinity ) {
  18677. vector.multiplyScalar( scale );
  18678. } else {
  18679. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18680. }
  18681. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18682. }
  18683. }
  18684. updateMatrixWorld( force ) {
  18685. super.updateMatrixWorld( force );
  18686. if ( this.bindMode === 'attached' ) {
  18687. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18688. } else if ( this.bindMode === 'detached' ) {
  18689. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18690. } else {
  18691. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18692. }
  18693. }
  18694. applyBoneTransform( index, vector ) {
  18695. const skeleton = this.skeleton;
  18696. const geometry = this.geometry;
  18697. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18698. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18699. _basePosition.copy( vector ).applyMatrix4( this.bindMatrix );
  18700. vector.set( 0, 0, 0 );
  18701. for ( let i = 0; i < 4; i ++ ) {
  18702. const weight = _skinWeight.getComponent( i );
  18703. if ( weight !== 0 ) {
  18704. const boneIndex = _skinIndex.getComponent( i );
  18705. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18706. vector.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18707. }
  18708. }
  18709. return vector.applyMatrix4( this.bindMatrixInverse );
  18710. }
  18711. boneTransform( index, vector ) { // @deprecated, r151
  18712. console.warn( 'THREE.SkinnedMesh: .boneTransform() was renamed to .applyBoneTransform() in r151.' );
  18713. return this.applyBoneTransform( index, vector );
  18714. }
  18715. }
  18716. class Bone extends Object3D {
  18717. constructor() {
  18718. super();
  18719. this.isBone = true;
  18720. this.type = 'Bone';
  18721. }
  18722. }
  18723. class DataTexture extends Texture {
  18724. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  18725. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  18726. this.isDataTexture = true;
  18727. this.image = { data: data, width: width, height: height };
  18728. this.generateMipmaps = false;
  18729. this.flipY = false;
  18730. this.unpackAlignment = 1;
  18731. }
  18732. }
  18733. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18734. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18735. class Skeleton {
  18736. constructor( bones = [], boneInverses = [] ) {
  18737. this.uuid = generateUUID();
  18738. this.bones = bones.slice( 0 );
  18739. this.boneInverses = boneInverses;
  18740. this.boneMatrices = null;
  18741. this.boneTexture = null;
  18742. this.boneTextureSize = 0;
  18743. this.init();
  18744. }
  18745. init() {
  18746. const bones = this.bones;
  18747. const boneInverses = this.boneInverses;
  18748. this.boneMatrices = new Float32Array( bones.length * 16 );
  18749. // calculate inverse bone matrices if necessary
  18750. if ( boneInverses.length === 0 ) {
  18751. this.calculateInverses();
  18752. } else {
  18753. // handle special case
  18754. if ( bones.length !== boneInverses.length ) {
  18755. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18756. this.boneInverses = [];
  18757. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18758. this.boneInverses.push( new Matrix4() );
  18759. }
  18760. }
  18761. }
  18762. }
  18763. calculateInverses() {
  18764. this.boneInverses.length = 0;
  18765. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18766. const inverse = new Matrix4();
  18767. if ( this.bones[ i ] ) {
  18768. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18769. }
  18770. this.boneInverses.push( inverse );
  18771. }
  18772. }
  18773. pose() {
  18774. // recover the bind-time world matrices
  18775. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18776. const bone = this.bones[ i ];
  18777. if ( bone ) {
  18778. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18779. }
  18780. }
  18781. // compute the local matrices, positions, rotations and scales
  18782. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18783. const bone = this.bones[ i ];
  18784. if ( bone ) {
  18785. if ( bone.parent && bone.parent.isBone ) {
  18786. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18787. bone.matrix.multiply( bone.matrixWorld );
  18788. } else {
  18789. bone.matrix.copy( bone.matrixWorld );
  18790. }
  18791. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18792. }
  18793. }
  18794. }
  18795. update() {
  18796. const bones = this.bones;
  18797. const boneInverses = this.boneInverses;
  18798. const boneMatrices = this.boneMatrices;
  18799. const boneTexture = this.boneTexture;
  18800. // flatten bone matrices to array
  18801. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18802. // compute the offset between the current and the original transform
  18803. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18804. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18805. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18806. }
  18807. if ( boneTexture !== null ) {
  18808. boneTexture.needsUpdate = true;
  18809. }
  18810. }
  18811. clone() {
  18812. return new Skeleton( this.bones, this.boneInverses );
  18813. }
  18814. computeBoneTexture() {
  18815. // layout (1 matrix = 4 pixels)
  18816. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18817. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18818. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18819. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18820. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18821. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18822. size = ceilPowerOfTwo( size );
  18823. size = Math.max( size, 4 );
  18824. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18825. boneMatrices.set( this.boneMatrices ); // copy current values
  18826. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18827. boneTexture.needsUpdate = true;
  18828. this.boneMatrices = boneMatrices;
  18829. this.boneTexture = boneTexture;
  18830. this.boneTextureSize = size;
  18831. return this;
  18832. }
  18833. getBoneByName( name ) {
  18834. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18835. const bone = this.bones[ i ];
  18836. if ( bone.name === name ) {
  18837. return bone;
  18838. }
  18839. }
  18840. return undefined;
  18841. }
  18842. dispose( ) {
  18843. if ( this.boneTexture !== null ) {
  18844. this.boneTexture.dispose();
  18845. this.boneTexture = null;
  18846. }
  18847. }
  18848. fromJSON( json, bones ) {
  18849. this.uuid = json.uuid;
  18850. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18851. const uuid = json.bones[ i ];
  18852. let bone = bones[ uuid ];
  18853. if ( bone === undefined ) {
  18854. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  18855. bone = new Bone();
  18856. }
  18857. this.bones.push( bone );
  18858. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18859. }
  18860. this.init();
  18861. return this;
  18862. }
  18863. toJSON() {
  18864. const data = {
  18865. metadata: {
  18866. version: 4.6,
  18867. type: 'Skeleton',
  18868. generator: 'Skeleton.toJSON'
  18869. },
  18870. bones: [],
  18871. boneInverses: []
  18872. };
  18873. data.uuid = this.uuid;
  18874. const bones = this.bones;
  18875. const boneInverses = this.boneInverses;
  18876. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18877. const bone = bones[ i ];
  18878. data.bones.push( bone.uuid );
  18879. const boneInverse = boneInverses[ i ];
  18880. data.boneInverses.push( boneInverse.toArray() );
  18881. }
  18882. return data;
  18883. }
  18884. }
  18885. class InstancedBufferAttribute extends BufferAttribute {
  18886. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18887. super( array, itemSize, normalized );
  18888. this.isInstancedBufferAttribute = true;
  18889. this.meshPerAttribute = meshPerAttribute;
  18890. }
  18891. copy( source ) {
  18892. super.copy( source );
  18893. this.meshPerAttribute = source.meshPerAttribute;
  18894. return this;
  18895. }
  18896. toJSON() {
  18897. const data = super.toJSON();
  18898. data.meshPerAttribute = this.meshPerAttribute;
  18899. data.isInstancedBufferAttribute = true;
  18900. return data;
  18901. }
  18902. }
  18903. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18904. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18905. const _instanceIntersects = [];
  18906. const _box3 = /*@__PURE__*/ new Box3();
  18907. const _identity = /*@__PURE__*/ new Matrix4();
  18908. const _mesh = /*@__PURE__*/ new Mesh();
  18909. const _sphere$2 = /*@__PURE__*/ new Sphere();
  18910. class InstancedMesh extends Mesh {
  18911. constructor( geometry, material, count ) {
  18912. super( geometry, material );
  18913. this.isInstancedMesh = true;
  18914. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18915. this.instanceColor = null;
  18916. this.count = count;
  18917. this.boundingBox = null;
  18918. this.boundingSphere = null;
  18919. for ( let i = 0; i < count; i ++ ) {
  18920. this.setMatrixAt( i, _identity );
  18921. }
  18922. }
  18923. computeBoundingBox() {
  18924. const geometry = this.geometry;
  18925. const count = this.count;
  18926. if ( this.boundingBox === null ) {
  18927. this.boundingBox = new Box3();
  18928. }
  18929. if ( geometry.boundingBox === null ) {
  18930. geometry.computeBoundingBox();
  18931. }
  18932. this.boundingBox.makeEmpty();
  18933. for ( let i = 0; i < count; i ++ ) {
  18934. this.getMatrixAt( i, _instanceLocalMatrix );
  18935. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  18936. this.boundingBox.union( _box3 );
  18937. }
  18938. }
  18939. computeBoundingSphere() {
  18940. const geometry = this.geometry;
  18941. const count = this.count;
  18942. if ( this.boundingSphere === null ) {
  18943. this.boundingSphere = new Sphere();
  18944. }
  18945. if ( geometry.boundingSphere === null ) {
  18946. geometry.computeBoundingSphere();
  18947. }
  18948. this.boundingSphere.makeEmpty();
  18949. for ( let i = 0; i < count; i ++ ) {
  18950. this.getMatrixAt( i, _instanceLocalMatrix );
  18951. _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  18952. this.boundingSphere.union( _sphere$2 );
  18953. }
  18954. }
  18955. copy( source, recursive ) {
  18956. super.copy( source, recursive );
  18957. this.instanceMatrix.copy( source.instanceMatrix );
  18958. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  18959. this.count = source.count;
  18960. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18961. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18962. return this;
  18963. }
  18964. getColorAt( index, color ) {
  18965. color.fromArray( this.instanceColor.array, index * 3 );
  18966. }
  18967. getMatrixAt( index, matrix ) {
  18968. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  18969. }
  18970. raycast( raycaster, intersects ) {
  18971. const matrixWorld = this.matrixWorld;
  18972. const raycastTimes = this.count;
  18973. _mesh.geometry = this.geometry;
  18974. _mesh.material = this.material;
  18975. if ( _mesh.material === undefined ) return;
  18976. // test with bounding sphere first
  18977. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18978. _sphere$2.copy( this.boundingSphere );
  18979. _sphere$2.applyMatrix4( matrixWorld );
  18980. if ( raycaster.ray.intersectsSphere( _sphere$2 ) === false ) return;
  18981. // now test each instance
  18982. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  18983. // calculate the world matrix for each instance
  18984. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  18985. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  18986. // the mesh represents this single instance
  18987. _mesh.matrixWorld = _instanceWorldMatrix;
  18988. _mesh.raycast( raycaster, _instanceIntersects );
  18989. // process the result of raycast
  18990. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  18991. const intersect = _instanceIntersects[ i ];
  18992. intersect.instanceId = instanceId;
  18993. intersect.object = this;
  18994. intersects.push( intersect );
  18995. }
  18996. _instanceIntersects.length = 0;
  18997. }
  18998. }
  18999. setColorAt( index, color ) {
  19000. if ( this.instanceColor === null ) {
  19001. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  19002. }
  19003. color.toArray( this.instanceColor.array, index * 3 );
  19004. }
  19005. setMatrixAt( index, matrix ) {
  19006. matrix.toArray( this.instanceMatrix.array, index * 16 );
  19007. }
  19008. updateMorphTargets() {
  19009. }
  19010. dispose() {
  19011. this.dispatchEvent( { type: 'dispose' } );
  19012. }
  19013. }
  19014. class LineBasicMaterial extends Material {
  19015. constructor( parameters ) {
  19016. super();
  19017. this.isLineBasicMaterial = true;
  19018. this.type = 'LineBasicMaterial';
  19019. this.color = new Color( 0xffffff );
  19020. this.map = null;
  19021. this.linewidth = 1;
  19022. this.linecap = 'round';
  19023. this.linejoin = 'round';
  19024. this.fog = true;
  19025. this.setValues( parameters );
  19026. }
  19027. copy( source ) {
  19028. super.copy( source );
  19029. this.color.copy( source.color );
  19030. this.map = source.map;
  19031. this.linewidth = source.linewidth;
  19032. this.linecap = source.linecap;
  19033. this.linejoin = source.linejoin;
  19034. this.fog = source.fog;
  19035. return this;
  19036. }
  19037. }
  19038. const _start$1 = /*@__PURE__*/ new Vector3();
  19039. const _end$1 = /*@__PURE__*/ new Vector3();
  19040. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  19041. const _ray$1 = /*@__PURE__*/ new Ray();
  19042. const _sphere$1 = /*@__PURE__*/ new Sphere();
  19043. class Line extends Object3D {
  19044. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  19045. super();
  19046. this.isLine = true;
  19047. this.type = 'Line';
  19048. this.geometry = geometry;
  19049. this.material = material;
  19050. this.updateMorphTargets();
  19051. }
  19052. copy( source, recursive ) {
  19053. super.copy( source, recursive );
  19054. this.material = source.material;
  19055. this.geometry = source.geometry;
  19056. return this;
  19057. }
  19058. computeLineDistances() {
  19059. const geometry = this.geometry;
  19060. // we assume non-indexed geometry
  19061. if ( geometry.index === null ) {
  19062. const positionAttribute = geometry.attributes.position;
  19063. const lineDistances = [ 0 ];
  19064. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  19065. _start$1.fromBufferAttribute( positionAttribute, i - 1 );
  19066. _end$1.fromBufferAttribute( positionAttribute, i );
  19067. lineDistances[ i ] = lineDistances[ i - 1 ];
  19068. lineDistances[ i ] += _start$1.distanceTo( _end$1 );
  19069. }
  19070. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  19071. } else {
  19072. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  19073. }
  19074. return this;
  19075. }
  19076. raycast( raycaster, intersects ) {
  19077. const geometry = this.geometry;
  19078. const matrixWorld = this.matrixWorld;
  19079. const threshold = raycaster.params.Line.threshold;
  19080. const drawRange = geometry.drawRange;
  19081. // Checking boundingSphere distance to ray
  19082. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19083. _sphere$1.copy( geometry.boundingSphere );
  19084. _sphere$1.applyMatrix4( matrixWorld );
  19085. _sphere$1.radius += threshold;
  19086. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  19087. //
  19088. _inverseMatrix$1.copy( matrixWorld ).invert();
  19089. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  19090. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  19091. const localThresholdSq = localThreshold * localThreshold;
  19092. const vStart = new Vector3();
  19093. const vEnd = new Vector3();
  19094. const interSegment = new Vector3();
  19095. const interRay = new Vector3();
  19096. const step = this.isLineSegments ? 2 : 1;
  19097. const index = geometry.index;
  19098. const attributes = geometry.attributes;
  19099. const positionAttribute = attributes.position;
  19100. if ( index !== null ) {
  19101. const start = Math.max( 0, drawRange.start );
  19102. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  19103. for ( let i = start, l = end - 1; i < l; i += step ) {
  19104. const a = index.getX( i );
  19105. const b = index.getX( i + 1 );
  19106. vStart.fromBufferAttribute( positionAttribute, a );
  19107. vEnd.fromBufferAttribute( positionAttribute, b );
  19108. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  19109. if ( distSq > localThresholdSq ) continue;
  19110. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  19111. const distance = raycaster.ray.origin.distanceTo( interRay );
  19112. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  19113. intersects.push( {
  19114. distance: distance,
  19115. // What do we want? intersection point on the ray or on the segment??
  19116. // point: raycaster.ray.at( distance ),
  19117. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  19118. index: i,
  19119. face: null,
  19120. faceIndex: null,
  19121. object: this
  19122. } );
  19123. }
  19124. } else {
  19125. const start = Math.max( 0, drawRange.start );
  19126. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  19127. for ( let i = start, l = end - 1; i < l; i += step ) {
  19128. vStart.fromBufferAttribute( positionAttribute, i );
  19129. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  19130. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  19131. if ( distSq > localThresholdSq ) continue;
  19132. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  19133. const distance = raycaster.ray.origin.distanceTo( interRay );
  19134. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  19135. intersects.push( {
  19136. distance: distance,
  19137. // What do we want? intersection point on the ray or on the segment??
  19138. // point: raycaster.ray.at( distance ),
  19139. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  19140. index: i,
  19141. face: null,
  19142. faceIndex: null,
  19143. object: this
  19144. } );
  19145. }
  19146. }
  19147. }
  19148. updateMorphTargets() {
  19149. const geometry = this.geometry;
  19150. const morphAttributes = geometry.morphAttributes;
  19151. const keys = Object.keys( morphAttributes );
  19152. if ( keys.length > 0 ) {
  19153. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  19154. if ( morphAttribute !== undefined ) {
  19155. this.morphTargetInfluences = [];
  19156. this.morphTargetDictionary = {};
  19157. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  19158. const name = morphAttribute[ m ].name || String( m );
  19159. this.morphTargetInfluences.push( 0 );
  19160. this.morphTargetDictionary[ name ] = m;
  19161. }
  19162. }
  19163. }
  19164. }
  19165. }
  19166. const _start = /*@__PURE__*/ new Vector3();
  19167. const _end = /*@__PURE__*/ new Vector3();
  19168. class LineSegments extends Line {
  19169. constructor( geometry, material ) {
  19170. super( geometry, material );
  19171. this.isLineSegments = true;
  19172. this.type = 'LineSegments';
  19173. }
  19174. computeLineDistances() {
  19175. const geometry = this.geometry;
  19176. // we assume non-indexed geometry
  19177. if ( geometry.index === null ) {
  19178. const positionAttribute = geometry.attributes.position;
  19179. const lineDistances = [];
  19180. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  19181. _start.fromBufferAttribute( positionAttribute, i );
  19182. _end.fromBufferAttribute( positionAttribute, i + 1 );
  19183. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  19184. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  19185. }
  19186. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  19187. } else {
  19188. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  19189. }
  19190. return this;
  19191. }
  19192. }
  19193. class LineLoop extends Line {
  19194. constructor( geometry, material ) {
  19195. super( geometry, material );
  19196. this.isLineLoop = true;
  19197. this.type = 'LineLoop';
  19198. }
  19199. }
  19200. class PointsMaterial extends Material {
  19201. constructor( parameters ) {
  19202. super();
  19203. this.isPointsMaterial = true;
  19204. this.type = 'PointsMaterial';
  19205. this.color = new Color( 0xffffff );
  19206. this.map = null;
  19207. this.alphaMap = null;
  19208. this.size = 1;
  19209. this.sizeAttenuation = true;
  19210. this.fog = true;
  19211. this.setValues( parameters );
  19212. }
  19213. copy( source ) {
  19214. super.copy( source );
  19215. this.color.copy( source.color );
  19216. this.map = source.map;
  19217. this.alphaMap = source.alphaMap;
  19218. this.size = source.size;
  19219. this.sizeAttenuation = source.sizeAttenuation;
  19220. this.fog = source.fog;
  19221. return this;
  19222. }
  19223. }
  19224. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  19225. const _ray = /*@__PURE__*/ new Ray();
  19226. const _sphere = /*@__PURE__*/ new Sphere();
  19227. const _position$2 = /*@__PURE__*/ new Vector3();
  19228. class Points extends Object3D {
  19229. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  19230. super();
  19231. this.isPoints = true;
  19232. this.type = 'Points';
  19233. this.geometry = geometry;
  19234. this.material = material;
  19235. this.updateMorphTargets();
  19236. }
  19237. copy( source, recursive ) {
  19238. super.copy( source, recursive );
  19239. this.material = source.material;
  19240. this.geometry = source.geometry;
  19241. return this;
  19242. }
  19243. raycast( raycaster, intersects ) {
  19244. const geometry = this.geometry;
  19245. const matrixWorld = this.matrixWorld;
  19246. const threshold = raycaster.params.Points.threshold;
  19247. const drawRange = geometry.drawRange;
  19248. // Checking boundingSphere distance to ray
  19249. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19250. _sphere.copy( geometry.boundingSphere );
  19251. _sphere.applyMatrix4( matrixWorld );
  19252. _sphere.radius += threshold;
  19253. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  19254. //
  19255. _inverseMatrix.copy( matrixWorld ).invert();
  19256. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  19257. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  19258. const localThresholdSq = localThreshold * localThreshold;
  19259. const index = geometry.index;
  19260. const attributes = geometry.attributes;
  19261. const positionAttribute = attributes.position;
  19262. if ( index !== null ) {
  19263. const start = Math.max( 0, drawRange.start );
  19264. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  19265. for ( let i = start, il = end; i < il; i ++ ) {
  19266. const a = index.getX( i );
  19267. _position$2.fromBufferAttribute( positionAttribute, a );
  19268. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  19269. }
  19270. } else {
  19271. const start = Math.max( 0, drawRange.start );
  19272. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  19273. for ( let i = start, l = end; i < l; i ++ ) {
  19274. _position$2.fromBufferAttribute( positionAttribute, i );
  19275. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  19276. }
  19277. }
  19278. }
  19279. updateMorphTargets() {
  19280. const geometry = this.geometry;
  19281. const morphAttributes = geometry.morphAttributes;
  19282. const keys = Object.keys( morphAttributes );
  19283. if ( keys.length > 0 ) {
  19284. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  19285. if ( morphAttribute !== undefined ) {
  19286. this.morphTargetInfluences = [];
  19287. this.morphTargetDictionary = {};
  19288. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  19289. const name = morphAttribute[ m ].name || String( m );
  19290. this.morphTargetInfluences.push( 0 );
  19291. this.morphTargetDictionary[ name ] = m;
  19292. }
  19293. }
  19294. }
  19295. }
  19296. }
  19297. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  19298. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  19299. if ( rayPointDistanceSq < localThresholdSq ) {
  19300. const intersectPoint = new Vector3();
  19301. _ray.closestPointToPoint( point, intersectPoint );
  19302. intersectPoint.applyMatrix4( matrixWorld );
  19303. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  19304. if ( distance < raycaster.near || distance > raycaster.far ) return;
  19305. intersects.push( {
  19306. distance: distance,
  19307. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  19308. point: intersectPoint,
  19309. index: index,
  19310. face: null,
  19311. object: object
  19312. } );
  19313. }
  19314. }
  19315. class VideoTexture extends Texture {
  19316. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  19317. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  19318. this.isVideoTexture = true;
  19319. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  19320. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  19321. this.generateMipmaps = false;
  19322. const scope = this;
  19323. function updateVideo() {
  19324. scope.needsUpdate = true;
  19325. video.requestVideoFrameCallback( updateVideo );
  19326. }
  19327. if ( 'requestVideoFrameCallback' in video ) {
  19328. video.requestVideoFrameCallback( updateVideo );
  19329. }
  19330. }
  19331. clone() {
  19332. return new this.constructor( this.image ).copy( this );
  19333. }
  19334. update() {
  19335. const video = this.image;
  19336. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  19337. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  19338. this.needsUpdate = true;
  19339. }
  19340. }
  19341. }
  19342. class FramebufferTexture extends Texture {
  19343. constructor( width, height ) {
  19344. super( { width, height } );
  19345. this.isFramebufferTexture = true;
  19346. this.magFilter = NearestFilter;
  19347. this.minFilter = NearestFilter;
  19348. this.generateMipmaps = false;
  19349. this.needsUpdate = true;
  19350. }
  19351. }
  19352. class CompressedTexture extends Texture {
  19353. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  19354. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  19355. this.isCompressedTexture = true;
  19356. this.image = { width: width, height: height };
  19357. this.mipmaps = mipmaps;
  19358. // no flipping for cube textures
  19359. // (also flipping doesn't work for compressed textures )
  19360. this.flipY = false;
  19361. // can't generate mipmaps for compressed textures
  19362. // mips must be embedded in DDS files
  19363. this.generateMipmaps = false;
  19364. }
  19365. }
  19366. class CompressedArrayTexture extends CompressedTexture {
  19367. constructor( mipmaps, width, height, depth, format, type ) {
  19368. super( mipmaps, width, height, format, type );
  19369. this.isCompressedArrayTexture = true;
  19370. this.image.depth = depth;
  19371. this.wrapR = ClampToEdgeWrapping;
  19372. }
  19373. }
  19374. class CanvasTexture extends Texture {
  19375. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  19376. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  19377. this.isCanvasTexture = true;
  19378. this.needsUpdate = true;
  19379. }
  19380. }
  19381. /**
  19382. * Extensible curve object.
  19383. *
  19384. * Some common of curve methods:
  19385. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  19386. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  19387. * .getPoints(), .getSpacedPoints()
  19388. * .getLength()
  19389. * .updateArcLengths()
  19390. *
  19391. * This following curves inherit from THREE.Curve:
  19392. *
  19393. * -- 2D curves --
  19394. * THREE.ArcCurve
  19395. * THREE.CubicBezierCurve
  19396. * THREE.EllipseCurve
  19397. * THREE.LineCurve
  19398. * THREE.QuadraticBezierCurve
  19399. * THREE.SplineCurve
  19400. *
  19401. * -- 3D curves --
  19402. * THREE.CatmullRomCurve3
  19403. * THREE.CubicBezierCurve3
  19404. * THREE.LineCurve3
  19405. * THREE.QuadraticBezierCurve3
  19406. *
  19407. * A series of curves can be represented as a THREE.CurvePath.
  19408. *
  19409. **/
  19410. class Curve {
  19411. constructor() {
  19412. this.type = 'Curve';
  19413. this.arcLengthDivisions = 200;
  19414. }
  19415. // Virtual base class method to overwrite and implement in subclasses
  19416. // - t [0 .. 1]
  19417. getPoint( /* t, optionalTarget */ ) {
  19418. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  19419. return null;
  19420. }
  19421. // Get point at relative position in curve according to arc length
  19422. // - u [0 .. 1]
  19423. getPointAt( u, optionalTarget ) {
  19424. const t = this.getUtoTmapping( u );
  19425. return this.getPoint( t, optionalTarget );
  19426. }
  19427. // Get sequence of points using getPoint( t )
  19428. getPoints( divisions = 5 ) {
  19429. const points = [];
  19430. for ( let d = 0; d <= divisions; d ++ ) {
  19431. points.push( this.getPoint( d / divisions ) );
  19432. }
  19433. return points;
  19434. }
  19435. // Get sequence of points using getPointAt( u )
  19436. getSpacedPoints( divisions = 5 ) {
  19437. const points = [];
  19438. for ( let d = 0; d <= divisions; d ++ ) {
  19439. points.push( this.getPointAt( d / divisions ) );
  19440. }
  19441. return points;
  19442. }
  19443. // Get total curve arc length
  19444. getLength() {
  19445. const lengths = this.getLengths();
  19446. return lengths[ lengths.length - 1 ];
  19447. }
  19448. // Get list of cumulative segment lengths
  19449. getLengths( divisions = this.arcLengthDivisions ) {
  19450. if ( this.cacheArcLengths &&
  19451. ( this.cacheArcLengths.length === divisions + 1 ) &&
  19452. ! this.needsUpdate ) {
  19453. return this.cacheArcLengths;
  19454. }
  19455. this.needsUpdate = false;
  19456. const cache = [];
  19457. let current, last = this.getPoint( 0 );
  19458. let sum = 0;
  19459. cache.push( 0 );
  19460. for ( let p = 1; p <= divisions; p ++ ) {
  19461. current = this.getPoint( p / divisions );
  19462. sum += current.distanceTo( last );
  19463. cache.push( sum );
  19464. last = current;
  19465. }
  19466. this.cacheArcLengths = cache;
  19467. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  19468. }
  19469. updateArcLengths() {
  19470. this.needsUpdate = true;
  19471. this.getLengths();
  19472. }
  19473. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  19474. getUtoTmapping( u, distance ) {
  19475. const arcLengths = this.getLengths();
  19476. let i = 0;
  19477. const il = arcLengths.length;
  19478. let targetArcLength; // The targeted u distance value to get
  19479. if ( distance ) {
  19480. targetArcLength = distance;
  19481. } else {
  19482. targetArcLength = u * arcLengths[ il - 1 ];
  19483. }
  19484. // binary search for the index with largest value smaller than target u distance
  19485. let low = 0, high = il - 1, comparison;
  19486. while ( low <= high ) {
  19487. 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
  19488. comparison = arcLengths[ i ] - targetArcLength;
  19489. if ( comparison < 0 ) {
  19490. low = i + 1;
  19491. } else if ( comparison > 0 ) {
  19492. high = i - 1;
  19493. } else {
  19494. high = i;
  19495. break;
  19496. // DONE
  19497. }
  19498. }
  19499. i = high;
  19500. if ( arcLengths[ i ] === targetArcLength ) {
  19501. return i / ( il - 1 );
  19502. }
  19503. // we could get finer grain at lengths, or use simple interpolation between two points
  19504. const lengthBefore = arcLengths[ i ];
  19505. const lengthAfter = arcLengths[ i + 1 ];
  19506. const segmentLength = lengthAfter - lengthBefore;
  19507. // determine where we are between the 'before' and 'after' points
  19508. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  19509. // add that fractional amount to t
  19510. const t = ( i + segmentFraction ) / ( il - 1 );
  19511. return t;
  19512. }
  19513. // Returns a unit vector tangent at t
  19514. // In case any sub curve does not implement its tangent derivation,
  19515. // 2 points a small delta apart will be used to find its gradient
  19516. // which seems to give a reasonable approximation
  19517. getTangent( t, optionalTarget ) {
  19518. const delta = 0.0001;
  19519. let t1 = t - delta;
  19520. let t2 = t + delta;
  19521. // Capping in case of danger
  19522. if ( t1 < 0 ) t1 = 0;
  19523. if ( t2 > 1 ) t2 = 1;
  19524. const pt1 = this.getPoint( t1 );
  19525. const pt2 = this.getPoint( t2 );
  19526. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  19527. tangent.copy( pt2 ).sub( pt1 ).normalize();
  19528. return tangent;
  19529. }
  19530. getTangentAt( u, optionalTarget ) {
  19531. const t = this.getUtoTmapping( u );
  19532. return this.getTangent( t, optionalTarget );
  19533. }
  19534. computeFrenetFrames( segments, closed ) {
  19535. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19536. const normal = new Vector3();
  19537. const tangents = [];
  19538. const normals = [];
  19539. const binormals = [];
  19540. const vec = new Vector3();
  19541. const mat = new Matrix4();
  19542. // compute the tangent vectors for each segment on the curve
  19543. for ( let i = 0; i <= segments; i ++ ) {
  19544. const u = i / segments;
  19545. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  19546. }
  19547. // select an initial normal vector perpendicular to the first tangent vector,
  19548. // and in the direction of the minimum tangent xyz component
  19549. normals[ 0 ] = new Vector3();
  19550. binormals[ 0 ] = new Vector3();
  19551. let min = Number.MAX_VALUE;
  19552. const tx = Math.abs( tangents[ 0 ].x );
  19553. const ty = Math.abs( tangents[ 0 ].y );
  19554. const tz = Math.abs( tangents[ 0 ].z );
  19555. if ( tx <= min ) {
  19556. min = tx;
  19557. normal.set( 1, 0, 0 );
  19558. }
  19559. if ( ty <= min ) {
  19560. min = ty;
  19561. normal.set( 0, 1, 0 );
  19562. }
  19563. if ( tz <= min ) {
  19564. normal.set( 0, 0, 1 );
  19565. }
  19566. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19567. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19568. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19569. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  19570. for ( let i = 1; i <= segments; i ++ ) {
  19571. normals[ i ] = normals[ i - 1 ].clone();
  19572. binormals[ i ] = binormals[ i - 1 ].clone();
  19573. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  19574. if ( vec.length() > Number.EPSILON ) {
  19575. vec.normalize();
  19576. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  19577. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19578. }
  19579. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19580. }
  19581. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19582. if ( closed === true ) {
  19583. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  19584. theta /= segments;
  19585. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  19586. theta = - theta;
  19587. }
  19588. for ( let i = 1; i <= segments; i ++ ) {
  19589. // twist a little...
  19590. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19591. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19592. }
  19593. }
  19594. return {
  19595. tangents: tangents,
  19596. normals: normals,
  19597. binormals: binormals
  19598. };
  19599. }
  19600. clone() {
  19601. return new this.constructor().copy( this );
  19602. }
  19603. copy( source ) {
  19604. this.arcLengthDivisions = source.arcLengthDivisions;
  19605. return this;
  19606. }
  19607. toJSON() {
  19608. const data = {
  19609. metadata: {
  19610. version: 4.6,
  19611. type: 'Curve',
  19612. generator: 'Curve.toJSON'
  19613. }
  19614. };
  19615. data.arcLengthDivisions = this.arcLengthDivisions;
  19616. data.type = this.type;
  19617. return data;
  19618. }
  19619. fromJSON( json ) {
  19620. this.arcLengthDivisions = json.arcLengthDivisions;
  19621. return this;
  19622. }
  19623. }
  19624. class EllipseCurve extends Curve {
  19625. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  19626. super();
  19627. this.isEllipseCurve = true;
  19628. this.type = 'EllipseCurve';
  19629. this.aX = aX;
  19630. this.aY = aY;
  19631. this.xRadius = xRadius;
  19632. this.yRadius = yRadius;
  19633. this.aStartAngle = aStartAngle;
  19634. this.aEndAngle = aEndAngle;
  19635. this.aClockwise = aClockwise;
  19636. this.aRotation = aRotation;
  19637. }
  19638. getPoint( t, optionalTarget ) {
  19639. const point = optionalTarget || new Vector2();
  19640. const twoPi = Math.PI * 2;
  19641. let deltaAngle = this.aEndAngle - this.aStartAngle;
  19642. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  19643. // ensures that deltaAngle is 0 .. 2 PI
  19644. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  19645. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  19646. if ( deltaAngle < Number.EPSILON ) {
  19647. if ( samePoints ) {
  19648. deltaAngle = 0;
  19649. } else {
  19650. deltaAngle = twoPi;
  19651. }
  19652. }
  19653. if ( this.aClockwise === true && ! samePoints ) {
  19654. if ( deltaAngle === twoPi ) {
  19655. deltaAngle = - twoPi;
  19656. } else {
  19657. deltaAngle = deltaAngle - twoPi;
  19658. }
  19659. }
  19660. const angle = this.aStartAngle + t * deltaAngle;
  19661. let x = this.aX + this.xRadius * Math.cos( angle );
  19662. let y = this.aY + this.yRadius * Math.sin( angle );
  19663. if ( this.aRotation !== 0 ) {
  19664. const cos = Math.cos( this.aRotation );
  19665. const sin = Math.sin( this.aRotation );
  19666. const tx = x - this.aX;
  19667. const ty = y - this.aY;
  19668. // Rotate the point about the center of the ellipse.
  19669. x = tx * cos - ty * sin + this.aX;
  19670. y = tx * sin + ty * cos + this.aY;
  19671. }
  19672. return point.set( x, y );
  19673. }
  19674. copy( source ) {
  19675. super.copy( source );
  19676. this.aX = source.aX;
  19677. this.aY = source.aY;
  19678. this.xRadius = source.xRadius;
  19679. this.yRadius = source.yRadius;
  19680. this.aStartAngle = source.aStartAngle;
  19681. this.aEndAngle = source.aEndAngle;
  19682. this.aClockwise = source.aClockwise;
  19683. this.aRotation = source.aRotation;
  19684. return this;
  19685. }
  19686. toJSON() {
  19687. const data = super.toJSON();
  19688. data.aX = this.aX;
  19689. data.aY = this.aY;
  19690. data.xRadius = this.xRadius;
  19691. data.yRadius = this.yRadius;
  19692. data.aStartAngle = this.aStartAngle;
  19693. data.aEndAngle = this.aEndAngle;
  19694. data.aClockwise = this.aClockwise;
  19695. data.aRotation = this.aRotation;
  19696. return data;
  19697. }
  19698. fromJSON( json ) {
  19699. super.fromJSON( json );
  19700. this.aX = json.aX;
  19701. this.aY = json.aY;
  19702. this.xRadius = json.xRadius;
  19703. this.yRadius = json.yRadius;
  19704. this.aStartAngle = json.aStartAngle;
  19705. this.aEndAngle = json.aEndAngle;
  19706. this.aClockwise = json.aClockwise;
  19707. this.aRotation = json.aRotation;
  19708. return this;
  19709. }
  19710. }
  19711. class ArcCurve extends EllipseCurve {
  19712. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19713. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  19714. this.isArcCurve = true;
  19715. this.type = 'ArcCurve';
  19716. }
  19717. }
  19718. /**
  19719. * Centripetal CatmullRom Curve - which is useful for avoiding
  19720. * cusps and self-intersections in non-uniform catmull rom curves.
  19721. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  19722. *
  19723. * curve.type accepts centripetal(default), chordal and catmullrom
  19724. * curve.tension is used for catmullrom which defaults to 0.5
  19725. */
  19726. /*
  19727. Based on an optimized c++ solution in
  19728. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  19729. - http://ideone.com/NoEbVM
  19730. This CubicPoly class could be used for reusing some variables and calculations,
  19731. but for three.js curve use, it could be possible inlined and flatten into a single function call
  19732. which can be placed in CurveUtils.
  19733. */
  19734. function CubicPoly() {
  19735. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  19736. /*
  19737. * Compute coefficients for a cubic polynomial
  19738. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  19739. * such that
  19740. * p(0) = x0, p(1) = x1
  19741. * and
  19742. * p'(0) = t0, p'(1) = t1.
  19743. */
  19744. function init( x0, x1, t0, t1 ) {
  19745. c0 = x0;
  19746. c1 = t0;
  19747. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  19748. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  19749. }
  19750. return {
  19751. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  19752. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  19753. },
  19754. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  19755. // compute tangents when parameterized in [t1,t2]
  19756. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  19757. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  19758. // rescale tangents for parametrization in [0,1]
  19759. t1 *= dt1;
  19760. t2 *= dt1;
  19761. init( x1, x2, t1, t2 );
  19762. },
  19763. calc: function ( t ) {
  19764. const t2 = t * t;
  19765. const t3 = t2 * t;
  19766. return c0 + c1 * t + c2 * t2 + c3 * t3;
  19767. }
  19768. };
  19769. }
  19770. //
  19771. const tmp = /*@__PURE__*/ new Vector3();
  19772. const px = /*@__PURE__*/ new CubicPoly();
  19773. const py = /*@__PURE__*/ new CubicPoly();
  19774. const pz = /*@__PURE__*/ new CubicPoly();
  19775. class CatmullRomCurve3 extends Curve {
  19776. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  19777. super();
  19778. this.isCatmullRomCurve3 = true;
  19779. this.type = 'CatmullRomCurve3';
  19780. this.points = points;
  19781. this.closed = closed;
  19782. this.curveType = curveType;
  19783. this.tension = tension;
  19784. }
  19785. getPoint( t, optionalTarget = new Vector3() ) {
  19786. const point = optionalTarget;
  19787. const points = this.points;
  19788. const l = points.length;
  19789. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  19790. let intPoint = Math.floor( p );
  19791. let weight = p - intPoint;
  19792. if ( this.closed ) {
  19793. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  19794. } else if ( weight === 0 && intPoint === l - 1 ) {
  19795. intPoint = l - 2;
  19796. weight = 1;
  19797. }
  19798. let p0, p3; // 4 points (p1 & p2 defined below)
  19799. if ( this.closed || intPoint > 0 ) {
  19800. p0 = points[ ( intPoint - 1 ) % l ];
  19801. } else {
  19802. // extrapolate first point
  19803. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  19804. p0 = tmp;
  19805. }
  19806. const p1 = points[ intPoint % l ];
  19807. const p2 = points[ ( intPoint + 1 ) % l ];
  19808. if ( this.closed || intPoint + 2 < l ) {
  19809. p3 = points[ ( intPoint + 2 ) % l ];
  19810. } else {
  19811. // extrapolate last point
  19812. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  19813. p3 = tmp;
  19814. }
  19815. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  19816. // init Centripetal / Chordal Catmull-Rom
  19817. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  19818. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  19819. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  19820. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  19821. // safety check for repeated points
  19822. if ( dt1 < 1e-4 ) dt1 = 1.0;
  19823. if ( dt0 < 1e-4 ) dt0 = dt1;
  19824. if ( dt2 < 1e-4 ) dt2 = dt1;
  19825. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  19826. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  19827. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  19828. } else if ( this.curveType === 'catmullrom' ) {
  19829. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  19830. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  19831. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  19832. }
  19833. point.set(
  19834. px.calc( weight ),
  19835. py.calc( weight ),
  19836. pz.calc( weight )
  19837. );
  19838. return point;
  19839. }
  19840. copy( source ) {
  19841. super.copy( source );
  19842. this.points = [];
  19843. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19844. const point = source.points[ i ];
  19845. this.points.push( point.clone() );
  19846. }
  19847. this.closed = source.closed;
  19848. this.curveType = source.curveType;
  19849. this.tension = source.tension;
  19850. return this;
  19851. }
  19852. toJSON() {
  19853. const data = super.toJSON();
  19854. data.points = [];
  19855. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19856. const point = this.points[ i ];
  19857. data.points.push( point.toArray() );
  19858. }
  19859. data.closed = this.closed;
  19860. data.curveType = this.curveType;
  19861. data.tension = this.tension;
  19862. return data;
  19863. }
  19864. fromJSON( json ) {
  19865. super.fromJSON( json );
  19866. this.points = [];
  19867. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19868. const point = json.points[ i ];
  19869. this.points.push( new Vector3().fromArray( point ) );
  19870. }
  19871. this.closed = json.closed;
  19872. this.curveType = json.curveType;
  19873. this.tension = json.tension;
  19874. return this;
  19875. }
  19876. }
  19877. /**
  19878. * Bezier Curves formulas obtained from
  19879. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  19880. */
  19881. function CatmullRom( t, p0, p1, p2, p3 ) {
  19882. const v0 = ( p2 - p0 ) * 0.5;
  19883. const v1 = ( p3 - p1 ) * 0.5;
  19884. const t2 = t * t;
  19885. const t3 = t * t2;
  19886. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  19887. }
  19888. //
  19889. function QuadraticBezierP0( t, p ) {
  19890. const k = 1 - t;
  19891. return k * k * p;
  19892. }
  19893. function QuadraticBezierP1( t, p ) {
  19894. return 2 * ( 1 - t ) * t * p;
  19895. }
  19896. function QuadraticBezierP2( t, p ) {
  19897. return t * t * p;
  19898. }
  19899. function QuadraticBezier( t, p0, p1, p2 ) {
  19900. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  19901. QuadraticBezierP2( t, p2 );
  19902. }
  19903. //
  19904. function CubicBezierP0( t, p ) {
  19905. const k = 1 - t;
  19906. return k * k * k * p;
  19907. }
  19908. function CubicBezierP1( t, p ) {
  19909. const k = 1 - t;
  19910. return 3 * k * k * t * p;
  19911. }
  19912. function CubicBezierP2( t, p ) {
  19913. return 3 * ( 1 - t ) * t * t * p;
  19914. }
  19915. function CubicBezierP3( t, p ) {
  19916. return t * t * t * p;
  19917. }
  19918. function CubicBezier( t, p0, p1, p2, p3 ) {
  19919. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  19920. CubicBezierP3( t, p3 );
  19921. }
  19922. class CubicBezierCurve extends Curve {
  19923. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  19924. super();
  19925. this.isCubicBezierCurve = true;
  19926. this.type = 'CubicBezierCurve';
  19927. this.v0 = v0;
  19928. this.v1 = v1;
  19929. this.v2 = v2;
  19930. this.v3 = v3;
  19931. }
  19932. getPoint( t, optionalTarget = new Vector2() ) {
  19933. const point = optionalTarget;
  19934. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19935. point.set(
  19936. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19937. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  19938. );
  19939. return point;
  19940. }
  19941. copy( source ) {
  19942. super.copy( source );
  19943. this.v0.copy( source.v0 );
  19944. this.v1.copy( source.v1 );
  19945. this.v2.copy( source.v2 );
  19946. this.v3.copy( source.v3 );
  19947. return this;
  19948. }
  19949. toJSON() {
  19950. const data = super.toJSON();
  19951. data.v0 = this.v0.toArray();
  19952. data.v1 = this.v1.toArray();
  19953. data.v2 = this.v2.toArray();
  19954. data.v3 = this.v3.toArray();
  19955. return data;
  19956. }
  19957. fromJSON( json ) {
  19958. super.fromJSON( json );
  19959. this.v0.fromArray( json.v0 );
  19960. this.v1.fromArray( json.v1 );
  19961. this.v2.fromArray( json.v2 );
  19962. this.v3.fromArray( json.v3 );
  19963. return this;
  19964. }
  19965. }
  19966. class CubicBezierCurve3 extends Curve {
  19967. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  19968. super();
  19969. this.isCubicBezierCurve3 = true;
  19970. this.type = 'CubicBezierCurve3';
  19971. this.v0 = v0;
  19972. this.v1 = v1;
  19973. this.v2 = v2;
  19974. this.v3 = v3;
  19975. }
  19976. getPoint( t, optionalTarget = new Vector3() ) {
  19977. const point = optionalTarget;
  19978. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19979. point.set(
  19980. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19981. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  19982. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  19983. );
  19984. return point;
  19985. }
  19986. copy( source ) {
  19987. super.copy( source );
  19988. this.v0.copy( source.v0 );
  19989. this.v1.copy( source.v1 );
  19990. this.v2.copy( source.v2 );
  19991. this.v3.copy( source.v3 );
  19992. return this;
  19993. }
  19994. toJSON() {
  19995. const data = super.toJSON();
  19996. data.v0 = this.v0.toArray();
  19997. data.v1 = this.v1.toArray();
  19998. data.v2 = this.v2.toArray();
  19999. data.v3 = this.v3.toArray();
  20000. return data;
  20001. }
  20002. fromJSON( json ) {
  20003. super.fromJSON( json );
  20004. this.v0.fromArray( json.v0 );
  20005. this.v1.fromArray( json.v1 );
  20006. this.v2.fromArray( json.v2 );
  20007. this.v3.fromArray( json.v3 );
  20008. return this;
  20009. }
  20010. }
  20011. class LineCurve extends Curve {
  20012. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  20013. super();
  20014. this.isLineCurve = true;
  20015. this.type = 'LineCurve';
  20016. this.v1 = v1;
  20017. this.v2 = v2;
  20018. }
  20019. getPoint( t, optionalTarget = new Vector2() ) {
  20020. const point = optionalTarget;
  20021. if ( t === 1 ) {
  20022. point.copy( this.v2 );
  20023. } else {
  20024. point.copy( this.v2 ).sub( this.v1 );
  20025. point.multiplyScalar( t ).add( this.v1 );
  20026. }
  20027. return point;
  20028. }
  20029. // Line curve is linear, so we can overwrite default getPointAt
  20030. getPointAt( u, optionalTarget ) {
  20031. return this.getPoint( u, optionalTarget );
  20032. }
  20033. getTangent( t, optionalTarget = new Vector2() ) {
  20034. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  20035. }
  20036. getTangentAt( u, optionalTarget ) {
  20037. return this.getTangent( u, optionalTarget );
  20038. }
  20039. copy( source ) {
  20040. super.copy( source );
  20041. this.v1.copy( source.v1 );
  20042. this.v2.copy( source.v2 );
  20043. return this;
  20044. }
  20045. toJSON() {
  20046. const data = super.toJSON();
  20047. data.v1 = this.v1.toArray();
  20048. data.v2 = this.v2.toArray();
  20049. return data;
  20050. }
  20051. fromJSON( json ) {
  20052. super.fromJSON( json );
  20053. this.v1.fromArray( json.v1 );
  20054. this.v2.fromArray( json.v2 );
  20055. return this;
  20056. }
  20057. }
  20058. class LineCurve3 extends Curve {
  20059. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  20060. super();
  20061. this.isLineCurve3 = true;
  20062. this.type = 'LineCurve3';
  20063. this.v1 = v1;
  20064. this.v2 = v2;
  20065. }
  20066. getPoint( t, optionalTarget = new Vector3() ) {
  20067. const point = optionalTarget;
  20068. if ( t === 1 ) {
  20069. point.copy( this.v2 );
  20070. } else {
  20071. point.copy( this.v2 ).sub( this.v1 );
  20072. point.multiplyScalar( t ).add( this.v1 );
  20073. }
  20074. return point;
  20075. }
  20076. // Line curve is linear, so we can overwrite default getPointAt
  20077. getPointAt( u, optionalTarget ) {
  20078. return this.getPoint( u, optionalTarget );
  20079. }
  20080. getTangent( t, optionalTarget = new Vector3() ) {
  20081. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  20082. }
  20083. getTangentAt( u, optionalTarget ) {
  20084. return this.getTangent( u, optionalTarget );
  20085. }
  20086. copy( source ) {
  20087. super.copy( source );
  20088. this.v1.copy( source.v1 );
  20089. this.v2.copy( source.v2 );
  20090. return this;
  20091. }
  20092. toJSON() {
  20093. const data = super.toJSON();
  20094. data.v1 = this.v1.toArray();
  20095. data.v2 = this.v2.toArray();
  20096. return data;
  20097. }
  20098. fromJSON( json ) {
  20099. super.fromJSON( json );
  20100. this.v1.fromArray( json.v1 );
  20101. this.v2.fromArray( json.v2 );
  20102. return this;
  20103. }
  20104. }
  20105. class QuadraticBezierCurve extends Curve {
  20106. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  20107. super();
  20108. this.isQuadraticBezierCurve = true;
  20109. this.type = 'QuadraticBezierCurve';
  20110. this.v0 = v0;
  20111. this.v1 = v1;
  20112. this.v2 = v2;
  20113. }
  20114. getPoint( t, optionalTarget = new Vector2() ) {
  20115. const point = optionalTarget;
  20116. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  20117. point.set(
  20118. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  20119. QuadraticBezier( t, v0.y, v1.y, v2.y )
  20120. );
  20121. return point;
  20122. }
  20123. copy( source ) {
  20124. super.copy( source );
  20125. this.v0.copy( source.v0 );
  20126. this.v1.copy( source.v1 );
  20127. this.v2.copy( source.v2 );
  20128. return this;
  20129. }
  20130. toJSON() {
  20131. const data = super.toJSON();
  20132. data.v0 = this.v0.toArray();
  20133. data.v1 = this.v1.toArray();
  20134. data.v2 = this.v2.toArray();
  20135. return data;
  20136. }
  20137. fromJSON( json ) {
  20138. super.fromJSON( json );
  20139. this.v0.fromArray( json.v0 );
  20140. this.v1.fromArray( json.v1 );
  20141. this.v2.fromArray( json.v2 );
  20142. return this;
  20143. }
  20144. }
  20145. class QuadraticBezierCurve3 extends Curve {
  20146. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  20147. super();
  20148. this.isQuadraticBezierCurve3 = true;
  20149. this.type = 'QuadraticBezierCurve3';
  20150. this.v0 = v0;
  20151. this.v1 = v1;
  20152. this.v2 = v2;
  20153. }
  20154. getPoint( t, optionalTarget = new Vector3() ) {
  20155. const point = optionalTarget;
  20156. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  20157. point.set(
  20158. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  20159. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  20160. QuadraticBezier( t, v0.z, v1.z, v2.z )
  20161. );
  20162. return point;
  20163. }
  20164. copy( source ) {
  20165. super.copy( source );
  20166. this.v0.copy( source.v0 );
  20167. this.v1.copy( source.v1 );
  20168. this.v2.copy( source.v2 );
  20169. return this;
  20170. }
  20171. toJSON() {
  20172. const data = super.toJSON();
  20173. data.v0 = this.v0.toArray();
  20174. data.v1 = this.v1.toArray();
  20175. data.v2 = this.v2.toArray();
  20176. return data;
  20177. }
  20178. fromJSON( json ) {
  20179. super.fromJSON( json );
  20180. this.v0.fromArray( json.v0 );
  20181. this.v1.fromArray( json.v1 );
  20182. this.v2.fromArray( json.v2 );
  20183. return this;
  20184. }
  20185. }
  20186. class SplineCurve extends Curve {
  20187. constructor( points = [] ) {
  20188. super();
  20189. this.isSplineCurve = true;
  20190. this.type = 'SplineCurve';
  20191. this.points = points;
  20192. }
  20193. getPoint( t, optionalTarget = new Vector2() ) {
  20194. const point = optionalTarget;
  20195. const points = this.points;
  20196. const p = ( points.length - 1 ) * t;
  20197. const intPoint = Math.floor( p );
  20198. const weight = p - intPoint;
  20199. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  20200. const p1 = points[ intPoint ];
  20201. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  20202. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  20203. point.set(
  20204. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  20205. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  20206. );
  20207. return point;
  20208. }
  20209. copy( source ) {
  20210. super.copy( source );
  20211. this.points = [];
  20212. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  20213. const point = source.points[ i ];
  20214. this.points.push( point.clone() );
  20215. }
  20216. return this;
  20217. }
  20218. toJSON() {
  20219. const data = super.toJSON();
  20220. data.points = [];
  20221. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  20222. const point = this.points[ i ];
  20223. data.points.push( point.toArray() );
  20224. }
  20225. return data;
  20226. }
  20227. fromJSON( json ) {
  20228. super.fromJSON( json );
  20229. this.points = [];
  20230. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  20231. const point = json.points[ i ];
  20232. this.points.push( new Vector2().fromArray( point ) );
  20233. }
  20234. return this;
  20235. }
  20236. }
  20237. var Curves = /*#__PURE__*/Object.freeze({
  20238. __proto__: null,
  20239. ArcCurve: ArcCurve,
  20240. CatmullRomCurve3: CatmullRomCurve3,
  20241. CubicBezierCurve: CubicBezierCurve,
  20242. CubicBezierCurve3: CubicBezierCurve3,
  20243. EllipseCurve: EllipseCurve,
  20244. LineCurve: LineCurve,
  20245. LineCurve3: LineCurve3,
  20246. QuadraticBezierCurve: QuadraticBezierCurve,
  20247. QuadraticBezierCurve3: QuadraticBezierCurve3,
  20248. SplineCurve: SplineCurve
  20249. });
  20250. /**************************************************************
  20251. * Curved Path - a curve path is simply a array of connected
  20252. * curves, but retains the api of a curve
  20253. **************************************************************/
  20254. class CurvePath extends Curve {
  20255. constructor() {
  20256. super();
  20257. this.type = 'CurvePath';
  20258. this.curves = [];
  20259. this.autoClose = false; // Automatically closes the path
  20260. }
  20261. add( curve ) {
  20262. this.curves.push( curve );
  20263. }
  20264. closePath() {
  20265. // Add a line curve if start and end of lines are not connected
  20266. const startPoint = this.curves[ 0 ].getPoint( 0 );
  20267. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  20268. if ( ! startPoint.equals( endPoint ) ) {
  20269. this.curves.push( new LineCurve( endPoint, startPoint ) );
  20270. }
  20271. }
  20272. // To get accurate point with reference to
  20273. // entire path distance at time t,
  20274. // following has to be done:
  20275. // 1. Length of each sub path have to be known
  20276. // 2. Locate and identify type of curve
  20277. // 3. Get t for the curve
  20278. // 4. Return curve.getPointAt(t')
  20279. getPoint( t, optionalTarget ) {
  20280. const d = t * this.getLength();
  20281. const curveLengths = this.getCurveLengths();
  20282. let i = 0;
  20283. // To think about boundaries points.
  20284. while ( i < curveLengths.length ) {
  20285. if ( curveLengths[ i ] >= d ) {
  20286. const diff = curveLengths[ i ] - d;
  20287. const curve = this.curves[ i ];
  20288. const segmentLength = curve.getLength();
  20289. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  20290. return curve.getPointAt( u, optionalTarget );
  20291. }
  20292. i ++;
  20293. }
  20294. return null;
  20295. // loop where sum != 0, sum > d , sum+1 <d
  20296. }
  20297. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  20298. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  20299. // getPoint() depends on getLength
  20300. getLength() {
  20301. const lens = this.getCurveLengths();
  20302. return lens[ lens.length - 1 ];
  20303. }
  20304. // cacheLengths must be recalculated.
  20305. updateArcLengths() {
  20306. this.needsUpdate = true;
  20307. this.cacheLengths = null;
  20308. this.getCurveLengths();
  20309. }
  20310. // Compute lengths and cache them
  20311. // We cannot overwrite getLengths() because UtoT mapping uses it.
  20312. getCurveLengths() {
  20313. // We use cache values if curves and cache array are same length
  20314. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  20315. return this.cacheLengths;
  20316. }
  20317. // Get length of sub-curve
  20318. // Push sums into cached array
  20319. const lengths = [];
  20320. let sums = 0;
  20321. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  20322. sums += this.curves[ i ].getLength();
  20323. lengths.push( sums );
  20324. }
  20325. this.cacheLengths = lengths;
  20326. return lengths;
  20327. }
  20328. getSpacedPoints( divisions = 40 ) {
  20329. const points = [];
  20330. for ( let i = 0; i <= divisions; i ++ ) {
  20331. points.push( this.getPoint( i / divisions ) );
  20332. }
  20333. if ( this.autoClose ) {
  20334. points.push( points[ 0 ] );
  20335. }
  20336. return points;
  20337. }
  20338. getPoints( divisions = 12 ) {
  20339. const points = [];
  20340. let last;
  20341. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  20342. const curve = curves[ i ];
  20343. const resolution = curve.isEllipseCurve ? divisions * 2
  20344. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  20345. : curve.isSplineCurve ? divisions * curve.points.length
  20346. : divisions;
  20347. const pts = curve.getPoints( resolution );
  20348. for ( let j = 0; j < pts.length; j ++ ) {
  20349. const point = pts[ j ];
  20350. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  20351. points.push( point );
  20352. last = point;
  20353. }
  20354. }
  20355. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  20356. points.push( points[ 0 ] );
  20357. }
  20358. return points;
  20359. }
  20360. copy( source ) {
  20361. super.copy( source );
  20362. this.curves = [];
  20363. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  20364. const curve = source.curves[ i ];
  20365. this.curves.push( curve.clone() );
  20366. }
  20367. this.autoClose = source.autoClose;
  20368. return this;
  20369. }
  20370. toJSON() {
  20371. const data = super.toJSON();
  20372. data.autoClose = this.autoClose;
  20373. data.curves = [];
  20374. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  20375. const curve = this.curves[ i ];
  20376. data.curves.push( curve.toJSON() );
  20377. }
  20378. return data;
  20379. }
  20380. fromJSON( json ) {
  20381. super.fromJSON( json );
  20382. this.autoClose = json.autoClose;
  20383. this.curves = [];
  20384. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  20385. const curve = json.curves[ i ];
  20386. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  20387. }
  20388. return this;
  20389. }
  20390. }
  20391. class Path extends CurvePath {
  20392. constructor( points ) {
  20393. super();
  20394. this.type = 'Path';
  20395. this.currentPoint = new Vector2();
  20396. if ( points ) {
  20397. this.setFromPoints( points );
  20398. }
  20399. }
  20400. setFromPoints( points ) {
  20401. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  20402. for ( let i = 1, l = points.length; i < l; i ++ ) {
  20403. this.lineTo( points[ i ].x, points[ i ].y );
  20404. }
  20405. return this;
  20406. }
  20407. moveTo( x, y ) {
  20408. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  20409. return this;
  20410. }
  20411. lineTo( x, y ) {
  20412. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  20413. this.curves.push( curve );
  20414. this.currentPoint.set( x, y );
  20415. return this;
  20416. }
  20417. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  20418. const curve = new QuadraticBezierCurve(
  20419. this.currentPoint.clone(),
  20420. new Vector2( aCPx, aCPy ),
  20421. new Vector2( aX, aY )
  20422. );
  20423. this.curves.push( curve );
  20424. this.currentPoint.set( aX, aY );
  20425. return this;
  20426. }
  20427. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  20428. const curve = new CubicBezierCurve(
  20429. this.currentPoint.clone(),
  20430. new Vector2( aCP1x, aCP1y ),
  20431. new Vector2( aCP2x, aCP2y ),
  20432. new Vector2( aX, aY )
  20433. );
  20434. this.curves.push( curve );
  20435. this.currentPoint.set( aX, aY );
  20436. return this;
  20437. }
  20438. splineThru( pts /*Array of Vector*/ ) {
  20439. const npts = [ this.currentPoint.clone() ].concat( pts );
  20440. const curve = new SplineCurve( npts );
  20441. this.curves.push( curve );
  20442. this.currentPoint.copy( pts[ pts.length - 1 ] );
  20443. return this;
  20444. }
  20445. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20446. const x0 = this.currentPoint.x;
  20447. const y0 = this.currentPoint.y;
  20448. this.absarc( aX + x0, aY + y0, aRadius,
  20449. aStartAngle, aEndAngle, aClockwise );
  20450. return this;
  20451. }
  20452. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  20453. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  20454. return this;
  20455. }
  20456. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20457. const x0 = this.currentPoint.x;
  20458. const y0 = this.currentPoint.y;
  20459. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20460. return this;
  20461. }
  20462. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  20463. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  20464. if ( this.curves.length > 0 ) {
  20465. // if a previous curve is present, attempt to join
  20466. const firstPoint = curve.getPoint( 0 );
  20467. if ( ! firstPoint.equals( this.currentPoint ) ) {
  20468. this.lineTo( firstPoint.x, firstPoint.y );
  20469. }
  20470. }
  20471. this.curves.push( curve );
  20472. const lastPoint = curve.getPoint( 1 );
  20473. this.currentPoint.copy( lastPoint );
  20474. return this;
  20475. }
  20476. copy( source ) {
  20477. super.copy( source );
  20478. this.currentPoint.copy( source.currentPoint );
  20479. return this;
  20480. }
  20481. toJSON() {
  20482. const data = super.toJSON();
  20483. data.currentPoint = this.currentPoint.toArray();
  20484. return data;
  20485. }
  20486. fromJSON( json ) {
  20487. super.fromJSON( json );
  20488. this.currentPoint.fromArray( json.currentPoint );
  20489. return this;
  20490. }
  20491. }
  20492. class LatheGeometry extends BufferGeometry {
  20493. 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 ) {
  20494. super();
  20495. this.type = 'LatheGeometry';
  20496. this.parameters = {
  20497. points: points,
  20498. segments: segments,
  20499. phiStart: phiStart,
  20500. phiLength: phiLength
  20501. };
  20502. segments = Math.floor( segments );
  20503. // clamp phiLength so it's in range of [ 0, 2PI ]
  20504. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  20505. // buffers
  20506. const indices = [];
  20507. const vertices = [];
  20508. const uvs = [];
  20509. const initNormals = [];
  20510. const normals = [];
  20511. // helper variables
  20512. const inverseSegments = 1.0 / segments;
  20513. const vertex = new Vector3();
  20514. const uv = new Vector2();
  20515. const normal = new Vector3();
  20516. const curNormal = new Vector3();
  20517. const prevNormal = new Vector3();
  20518. let dx = 0;
  20519. let dy = 0;
  20520. // pre-compute normals for initial "meridian"
  20521. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  20522. switch ( j ) {
  20523. case 0: // special handling for 1st vertex on path
  20524. dx = points[ j + 1 ].x - points[ j ].x;
  20525. dy = points[ j + 1 ].y - points[ j ].y;
  20526. normal.x = dy * 1.0;
  20527. normal.y = - dx;
  20528. normal.z = dy * 0.0;
  20529. prevNormal.copy( normal );
  20530. normal.normalize();
  20531. initNormals.push( normal.x, normal.y, normal.z );
  20532. break;
  20533. case ( points.length - 1 ): // special handling for last Vertex on path
  20534. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  20535. break;
  20536. default: // default handling for all vertices in between
  20537. dx = points[ j + 1 ].x - points[ j ].x;
  20538. dy = points[ j + 1 ].y - points[ j ].y;
  20539. normal.x = dy * 1.0;
  20540. normal.y = - dx;
  20541. normal.z = dy * 0.0;
  20542. curNormal.copy( normal );
  20543. normal.x += prevNormal.x;
  20544. normal.y += prevNormal.y;
  20545. normal.z += prevNormal.z;
  20546. normal.normalize();
  20547. initNormals.push( normal.x, normal.y, normal.z );
  20548. prevNormal.copy( curNormal );
  20549. }
  20550. }
  20551. // generate vertices, uvs and normals
  20552. for ( let i = 0; i <= segments; i ++ ) {
  20553. const phi = phiStart + i * inverseSegments * phiLength;
  20554. const sin = Math.sin( phi );
  20555. const cos = Math.cos( phi );
  20556. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  20557. // vertex
  20558. vertex.x = points[ j ].x * sin;
  20559. vertex.y = points[ j ].y;
  20560. vertex.z = points[ j ].x * cos;
  20561. vertices.push( vertex.x, vertex.y, vertex.z );
  20562. // uv
  20563. uv.x = i / segments;
  20564. uv.y = j / ( points.length - 1 );
  20565. uvs.push( uv.x, uv.y );
  20566. // normal
  20567. const x = initNormals[ 3 * j + 0 ] * sin;
  20568. const y = initNormals[ 3 * j + 1 ];
  20569. const z = initNormals[ 3 * j + 0 ] * cos;
  20570. normals.push( x, y, z );
  20571. }
  20572. }
  20573. // indices
  20574. for ( let i = 0; i < segments; i ++ ) {
  20575. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  20576. const base = j + i * points.length;
  20577. const a = base;
  20578. const b = base + points.length;
  20579. const c = base + points.length + 1;
  20580. const d = base + 1;
  20581. // faces
  20582. indices.push( a, b, d );
  20583. indices.push( c, d, b );
  20584. }
  20585. }
  20586. // build geometry
  20587. this.setIndex( indices );
  20588. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20589. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20590. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20591. }
  20592. copy( source ) {
  20593. super.copy( source );
  20594. this.parameters = Object.assign( {}, source.parameters );
  20595. return this;
  20596. }
  20597. static fromJSON( data ) {
  20598. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  20599. }
  20600. }
  20601. class CapsuleGeometry extends LatheGeometry {
  20602. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  20603. const path = new Path();
  20604. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  20605. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  20606. super( path.getPoints( capSegments ), radialSegments );
  20607. this.type = 'CapsuleGeometry';
  20608. this.parameters = {
  20609. radius: radius,
  20610. height: length,
  20611. capSegments: capSegments,
  20612. radialSegments: radialSegments,
  20613. };
  20614. }
  20615. static fromJSON( data ) {
  20616. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  20617. }
  20618. }
  20619. class CircleGeometry extends BufferGeometry {
  20620. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20621. super();
  20622. this.type = 'CircleGeometry';
  20623. this.parameters = {
  20624. radius: radius,
  20625. segments: segments,
  20626. thetaStart: thetaStart,
  20627. thetaLength: thetaLength
  20628. };
  20629. segments = Math.max( 3, segments );
  20630. // buffers
  20631. const indices = [];
  20632. const vertices = [];
  20633. const normals = [];
  20634. const uvs = [];
  20635. // helper variables
  20636. const vertex = new Vector3();
  20637. const uv = new Vector2();
  20638. // center point
  20639. vertices.push( 0, 0, 0 );
  20640. normals.push( 0, 0, 1 );
  20641. uvs.push( 0.5, 0.5 );
  20642. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  20643. const segment = thetaStart + s / segments * thetaLength;
  20644. // vertex
  20645. vertex.x = radius * Math.cos( segment );
  20646. vertex.y = radius * Math.sin( segment );
  20647. vertices.push( vertex.x, vertex.y, vertex.z );
  20648. // normal
  20649. normals.push( 0, 0, 1 );
  20650. // uvs
  20651. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  20652. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  20653. uvs.push( uv.x, uv.y );
  20654. }
  20655. // indices
  20656. for ( let i = 1; i <= segments; i ++ ) {
  20657. indices.push( i, i + 1, 0 );
  20658. }
  20659. // build geometry
  20660. this.setIndex( indices );
  20661. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20662. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20663. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20664. }
  20665. copy( source ) {
  20666. super.copy( source );
  20667. this.parameters = Object.assign( {}, source.parameters );
  20668. return this;
  20669. }
  20670. static fromJSON( data ) {
  20671. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  20672. }
  20673. }
  20674. class CylinderGeometry extends BufferGeometry {
  20675. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20676. super();
  20677. this.type = 'CylinderGeometry';
  20678. this.parameters = {
  20679. radiusTop: radiusTop,
  20680. radiusBottom: radiusBottom,
  20681. height: height,
  20682. radialSegments: radialSegments,
  20683. heightSegments: heightSegments,
  20684. openEnded: openEnded,
  20685. thetaStart: thetaStart,
  20686. thetaLength: thetaLength
  20687. };
  20688. const scope = this;
  20689. radialSegments = Math.floor( radialSegments );
  20690. heightSegments = Math.floor( heightSegments );
  20691. // buffers
  20692. const indices = [];
  20693. const vertices = [];
  20694. const normals = [];
  20695. const uvs = [];
  20696. // helper variables
  20697. let index = 0;
  20698. const indexArray = [];
  20699. const halfHeight = height / 2;
  20700. let groupStart = 0;
  20701. // generate geometry
  20702. generateTorso();
  20703. if ( openEnded === false ) {
  20704. if ( radiusTop > 0 ) generateCap( true );
  20705. if ( radiusBottom > 0 ) generateCap( false );
  20706. }
  20707. // build geometry
  20708. this.setIndex( indices );
  20709. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20710. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20711. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20712. function generateTorso() {
  20713. const normal = new Vector3();
  20714. const vertex = new Vector3();
  20715. let groupCount = 0;
  20716. // this will be used to calculate the normal
  20717. const slope = ( radiusBottom - radiusTop ) / height;
  20718. // generate vertices, normals and uvs
  20719. for ( let y = 0; y <= heightSegments; y ++ ) {
  20720. const indexRow = [];
  20721. const v = y / heightSegments;
  20722. // calculate the radius of the current row
  20723. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  20724. for ( let x = 0; x <= radialSegments; x ++ ) {
  20725. const u = x / radialSegments;
  20726. const theta = u * thetaLength + thetaStart;
  20727. const sinTheta = Math.sin( theta );
  20728. const cosTheta = Math.cos( theta );
  20729. // vertex
  20730. vertex.x = radius * sinTheta;
  20731. vertex.y = - v * height + halfHeight;
  20732. vertex.z = radius * cosTheta;
  20733. vertices.push( vertex.x, vertex.y, vertex.z );
  20734. // normal
  20735. normal.set( sinTheta, slope, cosTheta ).normalize();
  20736. normals.push( normal.x, normal.y, normal.z );
  20737. // uv
  20738. uvs.push( u, 1 - v );
  20739. // save index of vertex in respective row
  20740. indexRow.push( index ++ );
  20741. }
  20742. // now save vertices of the row in our index array
  20743. indexArray.push( indexRow );
  20744. }
  20745. // generate indices
  20746. for ( let x = 0; x < radialSegments; x ++ ) {
  20747. for ( let y = 0; y < heightSegments; y ++ ) {
  20748. // we use the index array to access the correct indices
  20749. const a = indexArray[ y ][ x ];
  20750. const b = indexArray[ y + 1 ][ x ];
  20751. const c = indexArray[ y + 1 ][ x + 1 ];
  20752. const d = indexArray[ y ][ x + 1 ];
  20753. // faces
  20754. indices.push( a, b, d );
  20755. indices.push( b, c, d );
  20756. // update group counter
  20757. groupCount += 6;
  20758. }
  20759. }
  20760. // add a group to the geometry. this will ensure multi material support
  20761. scope.addGroup( groupStart, groupCount, 0 );
  20762. // calculate new start value for groups
  20763. groupStart += groupCount;
  20764. }
  20765. function generateCap( top ) {
  20766. // save the index of the first center vertex
  20767. const centerIndexStart = index;
  20768. const uv = new Vector2();
  20769. const vertex = new Vector3();
  20770. let groupCount = 0;
  20771. const radius = ( top === true ) ? radiusTop : radiusBottom;
  20772. const sign = ( top === true ) ? 1 : - 1;
  20773. // first we generate the center vertex data of the cap.
  20774. // because the geometry needs one set of uvs per face,
  20775. // we must generate a center vertex per face/segment
  20776. for ( let x = 1; x <= radialSegments; x ++ ) {
  20777. // vertex
  20778. vertices.push( 0, halfHeight * sign, 0 );
  20779. // normal
  20780. normals.push( 0, sign, 0 );
  20781. // uv
  20782. uvs.push( 0.5, 0.5 );
  20783. // increase index
  20784. index ++;
  20785. }
  20786. // save the index of the last center vertex
  20787. const centerIndexEnd = index;
  20788. // now we generate the surrounding vertices, normals and uvs
  20789. for ( let x = 0; x <= radialSegments; x ++ ) {
  20790. const u = x / radialSegments;
  20791. const theta = u * thetaLength + thetaStart;
  20792. const cosTheta = Math.cos( theta );
  20793. const sinTheta = Math.sin( theta );
  20794. // vertex
  20795. vertex.x = radius * sinTheta;
  20796. vertex.y = halfHeight * sign;
  20797. vertex.z = radius * cosTheta;
  20798. vertices.push( vertex.x, vertex.y, vertex.z );
  20799. // normal
  20800. normals.push( 0, sign, 0 );
  20801. // uv
  20802. uv.x = ( cosTheta * 0.5 ) + 0.5;
  20803. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  20804. uvs.push( uv.x, uv.y );
  20805. // increase index
  20806. index ++;
  20807. }
  20808. // generate indices
  20809. for ( let x = 0; x < radialSegments; x ++ ) {
  20810. const c = centerIndexStart + x;
  20811. const i = centerIndexEnd + x;
  20812. if ( top === true ) {
  20813. // face top
  20814. indices.push( i, i + 1, c );
  20815. } else {
  20816. // face bottom
  20817. indices.push( i + 1, i, c );
  20818. }
  20819. groupCount += 3;
  20820. }
  20821. // add a group to the geometry. this will ensure multi material support
  20822. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  20823. // calculate new start value for groups
  20824. groupStart += groupCount;
  20825. }
  20826. }
  20827. copy( source ) {
  20828. super.copy( source );
  20829. this.parameters = Object.assign( {}, source.parameters );
  20830. return this;
  20831. }
  20832. static fromJSON( data ) {
  20833. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  20834. }
  20835. }
  20836. class ConeGeometry extends CylinderGeometry {
  20837. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20838. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  20839. this.type = 'ConeGeometry';
  20840. this.parameters = {
  20841. radius: radius,
  20842. height: height,
  20843. radialSegments: radialSegments,
  20844. heightSegments: heightSegments,
  20845. openEnded: openEnded,
  20846. thetaStart: thetaStart,
  20847. thetaLength: thetaLength
  20848. };
  20849. }
  20850. static fromJSON( data ) {
  20851. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  20852. }
  20853. }
  20854. class PolyhedronGeometry extends BufferGeometry {
  20855. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  20856. super();
  20857. this.type = 'PolyhedronGeometry';
  20858. this.parameters = {
  20859. vertices: vertices,
  20860. indices: indices,
  20861. radius: radius,
  20862. detail: detail
  20863. };
  20864. // default buffer data
  20865. const vertexBuffer = [];
  20866. const uvBuffer = [];
  20867. // the subdivision creates the vertex buffer data
  20868. subdivide( detail );
  20869. // all vertices should lie on a conceptual sphere with a given radius
  20870. applyRadius( radius );
  20871. // finally, create the uv data
  20872. generateUVs();
  20873. // build non-indexed geometry
  20874. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  20875. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  20876. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  20877. if ( detail === 0 ) {
  20878. this.computeVertexNormals(); // flat normals
  20879. } else {
  20880. this.normalizeNormals(); // smooth normals
  20881. }
  20882. // helper functions
  20883. function subdivide( detail ) {
  20884. const a = new Vector3();
  20885. const b = new Vector3();
  20886. const c = new Vector3();
  20887. // iterate over all faces and apply a subdivision with the given detail value
  20888. for ( let i = 0; i < indices.length; i += 3 ) {
  20889. // get the vertices of the face
  20890. getVertexByIndex( indices[ i + 0 ], a );
  20891. getVertexByIndex( indices[ i + 1 ], b );
  20892. getVertexByIndex( indices[ i + 2 ], c );
  20893. // perform subdivision
  20894. subdivideFace( a, b, c, detail );
  20895. }
  20896. }
  20897. function subdivideFace( a, b, c, detail ) {
  20898. const cols = detail + 1;
  20899. // we use this multidimensional array as a data structure for creating the subdivision
  20900. const v = [];
  20901. // construct all of the vertices for this subdivision
  20902. for ( let i = 0; i <= cols; i ++ ) {
  20903. v[ i ] = [];
  20904. const aj = a.clone().lerp( c, i / cols );
  20905. const bj = b.clone().lerp( c, i / cols );
  20906. const rows = cols - i;
  20907. for ( let j = 0; j <= rows; j ++ ) {
  20908. if ( j === 0 && i === cols ) {
  20909. v[ i ][ j ] = aj;
  20910. } else {
  20911. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  20912. }
  20913. }
  20914. }
  20915. // construct all of the faces
  20916. for ( let i = 0; i < cols; i ++ ) {
  20917. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  20918. const k = Math.floor( j / 2 );
  20919. if ( j % 2 === 0 ) {
  20920. pushVertex( v[ i ][ k + 1 ] );
  20921. pushVertex( v[ i + 1 ][ k ] );
  20922. pushVertex( v[ i ][ k ] );
  20923. } else {
  20924. pushVertex( v[ i ][ k + 1 ] );
  20925. pushVertex( v[ i + 1 ][ k + 1 ] );
  20926. pushVertex( v[ i + 1 ][ k ] );
  20927. }
  20928. }
  20929. }
  20930. }
  20931. function applyRadius( radius ) {
  20932. const vertex = new Vector3();
  20933. // iterate over the entire buffer and apply the radius to each vertex
  20934. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  20935. vertex.x = vertexBuffer[ i + 0 ];
  20936. vertex.y = vertexBuffer[ i + 1 ];
  20937. vertex.z = vertexBuffer[ i + 2 ];
  20938. vertex.normalize().multiplyScalar( radius );
  20939. vertexBuffer[ i + 0 ] = vertex.x;
  20940. vertexBuffer[ i + 1 ] = vertex.y;
  20941. vertexBuffer[ i + 2 ] = vertex.z;
  20942. }
  20943. }
  20944. function generateUVs() {
  20945. const vertex = new Vector3();
  20946. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  20947. vertex.x = vertexBuffer[ i + 0 ];
  20948. vertex.y = vertexBuffer[ i + 1 ];
  20949. vertex.z = vertexBuffer[ i + 2 ];
  20950. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  20951. const v = inclination( vertex ) / Math.PI + 0.5;
  20952. uvBuffer.push( u, 1 - v );
  20953. }
  20954. correctUVs();
  20955. correctSeam();
  20956. }
  20957. function correctSeam() {
  20958. // handle case when face straddles the seam, see #3269
  20959. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  20960. // uv data of a single face
  20961. const x0 = uvBuffer[ i + 0 ];
  20962. const x1 = uvBuffer[ i + 2 ];
  20963. const x2 = uvBuffer[ i + 4 ];
  20964. const max = Math.max( x0, x1, x2 );
  20965. const min = Math.min( x0, x1, x2 );
  20966. // 0.9 is somewhat arbitrary
  20967. if ( max > 0.9 && min < 0.1 ) {
  20968. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  20969. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  20970. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  20971. }
  20972. }
  20973. }
  20974. function pushVertex( vertex ) {
  20975. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  20976. }
  20977. function getVertexByIndex( index, vertex ) {
  20978. const stride = index * 3;
  20979. vertex.x = vertices[ stride + 0 ];
  20980. vertex.y = vertices[ stride + 1 ];
  20981. vertex.z = vertices[ stride + 2 ];
  20982. }
  20983. function correctUVs() {
  20984. const a = new Vector3();
  20985. const b = new Vector3();
  20986. const c = new Vector3();
  20987. const centroid = new Vector3();
  20988. const uvA = new Vector2();
  20989. const uvB = new Vector2();
  20990. const uvC = new Vector2();
  20991. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  20992. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  20993. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  20994. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  20995. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  20996. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  20997. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  20998. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  20999. const azi = azimuth( centroid );
  21000. correctUV( uvA, j + 0, a, azi );
  21001. correctUV( uvB, j + 2, b, azi );
  21002. correctUV( uvC, j + 4, c, azi );
  21003. }
  21004. }
  21005. function correctUV( uv, stride, vector, azimuth ) {
  21006. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  21007. uvBuffer[ stride ] = uv.x - 1;
  21008. }
  21009. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  21010. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  21011. }
  21012. }
  21013. // Angle around the Y axis, counter-clockwise when looking from above.
  21014. function azimuth( vector ) {
  21015. return Math.atan2( vector.z, - vector.x );
  21016. }
  21017. // Angle above the XZ plane.
  21018. function inclination( vector ) {
  21019. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  21020. }
  21021. }
  21022. copy( source ) {
  21023. super.copy( source );
  21024. this.parameters = Object.assign( {}, source.parameters );
  21025. return this;
  21026. }
  21027. static fromJSON( data ) {
  21028. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  21029. }
  21030. }
  21031. class DodecahedronGeometry extends PolyhedronGeometry {
  21032. constructor( radius = 1, detail = 0 ) {
  21033. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21034. const r = 1 / t;
  21035. const vertices = [
  21036. // (±1, ±1, ±1)
  21037. - 1, - 1, - 1, - 1, - 1, 1,
  21038. - 1, 1, - 1, - 1, 1, 1,
  21039. 1, - 1, - 1, 1, - 1, 1,
  21040. 1, 1, - 1, 1, 1, 1,
  21041. // (0, ±1/φ, ±φ)
  21042. 0, - r, - t, 0, - r, t,
  21043. 0, r, - t, 0, r, t,
  21044. // (±1/φ, ±φ, 0)
  21045. - r, - t, 0, - r, t, 0,
  21046. r, - t, 0, r, t, 0,
  21047. // (±φ, 0, ±1/φ)
  21048. - t, 0, - r, t, 0, - r,
  21049. - t, 0, r, t, 0, r
  21050. ];
  21051. const indices = [
  21052. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  21053. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  21054. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  21055. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  21056. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  21057. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  21058. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  21059. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  21060. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  21061. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  21062. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  21063. 1, 12, 14, 1, 14, 5, 1, 5, 9
  21064. ];
  21065. super( vertices, indices, radius, detail );
  21066. this.type = 'DodecahedronGeometry';
  21067. this.parameters = {
  21068. radius: radius,
  21069. detail: detail
  21070. };
  21071. }
  21072. static fromJSON( data ) {
  21073. return new DodecahedronGeometry( data.radius, data.detail );
  21074. }
  21075. }
  21076. const _v0 = /*@__PURE__*/ new Vector3();
  21077. const _v1$1 = /*@__PURE__*/ new Vector3();
  21078. const _normal = /*@__PURE__*/ new Vector3();
  21079. const _triangle = /*@__PURE__*/ new Triangle();
  21080. class EdgesGeometry extends BufferGeometry {
  21081. constructor( geometry = null, thresholdAngle = 1 ) {
  21082. super();
  21083. this.type = 'EdgesGeometry';
  21084. this.parameters = {
  21085. geometry: geometry,
  21086. thresholdAngle: thresholdAngle
  21087. };
  21088. if ( geometry !== null ) {
  21089. const precisionPoints = 4;
  21090. const precision = Math.pow( 10, precisionPoints );
  21091. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  21092. const indexAttr = geometry.getIndex();
  21093. const positionAttr = geometry.getAttribute( 'position' );
  21094. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  21095. const indexArr = [ 0, 0, 0 ];
  21096. const vertKeys = [ 'a', 'b', 'c' ];
  21097. const hashes = new Array( 3 );
  21098. const edgeData = {};
  21099. const vertices = [];
  21100. for ( let i = 0; i < indexCount; i += 3 ) {
  21101. if ( indexAttr ) {
  21102. indexArr[ 0 ] = indexAttr.getX( i );
  21103. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  21104. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  21105. } else {
  21106. indexArr[ 0 ] = i;
  21107. indexArr[ 1 ] = i + 1;
  21108. indexArr[ 2 ] = i + 2;
  21109. }
  21110. const { a, b, c } = _triangle;
  21111. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  21112. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  21113. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  21114. _triangle.getNormal( _normal );
  21115. // create hashes for the edge from the vertices
  21116. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  21117. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  21118. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  21119. // skip degenerate triangles
  21120. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  21121. continue;
  21122. }
  21123. // iterate over every edge
  21124. for ( let j = 0; j < 3; j ++ ) {
  21125. // get the first and next vertex making up the edge
  21126. const jNext = ( j + 1 ) % 3;
  21127. const vecHash0 = hashes[ j ];
  21128. const vecHash1 = hashes[ jNext ];
  21129. const v0 = _triangle[ vertKeys[ j ] ];
  21130. const v1 = _triangle[ vertKeys[ jNext ] ];
  21131. const hash = `${ vecHash0 }_${ vecHash1 }`;
  21132. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  21133. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  21134. // if we found a sibling edge add it into the vertex array if
  21135. // it meets the angle threshold and delete the edge from the map.
  21136. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  21137. vertices.push( v0.x, v0.y, v0.z );
  21138. vertices.push( v1.x, v1.y, v1.z );
  21139. }
  21140. edgeData[ reverseHash ] = null;
  21141. } else if ( ! ( hash in edgeData ) ) {
  21142. // if we've already got an edge here then skip adding a new one
  21143. edgeData[ hash ] = {
  21144. index0: indexArr[ j ],
  21145. index1: indexArr[ jNext ],
  21146. normal: _normal.clone(),
  21147. };
  21148. }
  21149. }
  21150. }
  21151. // iterate over all remaining, unmatched edges and add them to the vertex array
  21152. for ( const key in edgeData ) {
  21153. if ( edgeData[ key ] ) {
  21154. const { index0, index1 } = edgeData[ key ];
  21155. _v0.fromBufferAttribute( positionAttr, index0 );
  21156. _v1$1.fromBufferAttribute( positionAttr, index1 );
  21157. vertices.push( _v0.x, _v0.y, _v0.z );
  21158. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  21159. }
  21160. }
  21161. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21162. }
  21163. }
  21164. copy( source ) {
  21165. super.copy( source );
  21166. this.parameters = Object.assign( {}, source.parameters );
  21167. return this;
  21168. }
  21169. }
  21170. class Shape extends Path {
  21171. constructor( points ) {
  21172. super( points );
  21173. this.uuid = generateUUID();
  21174. this.type = 'Shape';
  21175. this.holes = [];
  21176. }
  21177. getPointsHoles( divisions ) {
  21178. const holesPts = [];
  21179. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  21180. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  21181. }
  21182. return holesPts;
  21183. }
  21184. // get points of shape and holes (keypoints based on segments parameter)
  21185. extractPoints( divisions ) {
  21186. return {
  21187. shape: this.getPoints( divisions ),
  21188. holes: this.getPointsHoles( divisions )
  21189. };
  21190. }
  21191. copy( source ) {
  21192. super.copy( source );
  21193. this.holes = [];
  21194. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  21195. const hole = source.holes[ i ];
  21196. this.holes.push( hole.clone() );
  21197. }
  21198. return this;
  21199. }
  21200. toJSON() {
  21201. const data = super.toJSON();
  21202. data.uuid = this.uuid;
  21203. data.holes = [];
  21204. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  21205. const hole = this.holes[ i ];
  21206. data.holes.push( hole.toJSON() );
  21207. }
  21208. return data;
  21209. }
  21210. fromJSON( json ) {
  21211. super.fromJSON( json );
  21212. this.uuid = json.uuid;
  21213. this.holes = [];
  21214. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  21215. const hole = json.holes[ i ];
  21216. this.holes.push( new Path().fromJSON( hole ) );
  21217. }
  21218. return this;
  21219. }
  21220. }
  21221. /**
  21222. * Port from https://github.com/mapbox/earcut (v2.2.4)
  21223. */
  21224. const Earcut = {
  21225. triangulate: function ( data, holeIndices, dim = 2 ) {
  21226. const hasHoles = holeIndices && holeIndices.length;
  21227. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  21228. let outerNode = linkedList( data, 0, outerLen, dim, true );
  21229. const triangles = [];
  21230. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  21231. let minX, minY, maxX, maxY, x, y, invSize;
  21232. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  21233. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  21234. if ( data.length > 80 * dim ) {
  21235. minX = maxX = data[ 0 ];
  21236. minY = maxY = data[ 1 ];
  21237. for ( let i = dim; i < outerLen; i += dim ) {
  21238. x = data[ i ];
  21239. y = data[ i + 1 ];
  21240. if ( x < minX ) minX = x;
  21241. if ( y < minY ) minY = y;
  21242. if ( x > maxX ) maxX = x;
  21243. if ( y > maxY ) maxY = y;
  21244. }
  21245. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  21246. invSize = Math.max( maxX - minX, maxY - minY );
  21247. invSize = invSize !== 0 ? 32767 / invSize : 0;
  21248. }
  21249. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  21250. return triangles;
  21251. }
  21252. };
  21253. // create a circular doubly linked list from polygon points in the specified winding order
  21254. function linkedList( data, start, end, dim, clockwise ) {
  21255. let i, last;
  21256. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  21257. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  21258. } else {
  21259. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  21260. }
  21261. if ( last && equals( last, last.next ) ) {
  21262. removeNode( last );
  21263. last = last.next;
  21264. }
  21265. return last;
  21266. }
  21267. // eliminate colinear or duplicate points
  21268. function filterPoints( start, end ) {
  21269. if ( ! start ) return start;
  21270. if ( ! end ) end = start;
  21271. let p = start,
  21272. again;
  21273. do {
  21274. again = false;
  21275. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  21276. removeNode( p );
  21277. p = end = p.prev;
  21278. if ( p === p.next ) break;
  21279. again = true;
  21280. } else {
  21281. p = p.next;
  21282. }
  21283. } while ( again || p !== end );
  21284. return end;
  21285. }
  21286. // main ear slicing loop which triangulates a polygon (given as a linked list)
  21287. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  21288. if ( ! ear ) return;
  21289. // interlink polygon nodes in z-order
  21290. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  21291. let stop = ear,
  21292. prev, next;
  21293. // iterate through ears, slicing them one by one
  21294. while ( ear.prev !== ear.next ) {
  21295. prev = ear.prev;
  21296. next = ear.next;
  21297. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  21298. // cut off the triangle
  21299. triangles.push( prev.i / dim | 0 );
  21300. triangles.push( ear.i / dim | 0 );
  21301. triangles.push( next.i / dim | 0 );
  21302. removeNode( ear );
  21303. // skipping the next vertex leads to less sliver triangles
  21304. ear = next.next;
  21305. stop = next.next;
  21306. continue;
  21307. }
  21308. ear = next;
  21309. // if we looped through the whole remaining polygon and can't find any more ears
  21310. if ( ear === stop ) {
  21311. // try filtering points and slicing again
  21312. if ( ! pass ) {
  21313. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  21314. // if this didn't work, try curing all small self-intersections locally
  21315. } else if ( pass === 1 ) {
  21316. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  21317. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  21318. // as a last resort, try splitting the remaining polygon into two
  21319. } else if ( pass === 2 ) {
  21320. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  21321. }
  21322. break;
  21323. }
  21324. }
  21325. }
  21326. // check whether a polygon node forms a valid ear with adjacent nodes
  21327. function isEar( ear ) {
  21328. const a = ear.prev,
  21329. b = ear,
  21330. c = ear.next;
  21331. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  21332. // now make sure we don't have other points inside the potential ear
  21333. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  21334. // triangle bbox; min & max are calculated like this for speed
  21335. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  21336. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  21337. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  21338. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  21339. let p = c.next;
  21340. while ( p !== a ) {
  21341. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  21342. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  21343. area( p.prev, p, p.next ) >= 0 ) return false;
  21344. p = p.next;
  21345. }
  21346. return true;
  21347. }
  21348. function isEarHashed( ear, minX, minY, invSize ) {
  21349. const a = ear.prev,
  21350. b = ear,
  21351. c = ear.next;
  21352. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  21353. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  21354. // triangle bbox; min & max are calculated like this for speed
  21355. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  21356. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  21357. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  21358. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  21359. // z-order range for the current triangle bbox;
  21360. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  21361. maxZ = zOrder( x1, y1, minX, minY, invSize );
  21362. let p = ear.prevZ,
  21363. n = ear.nextZ;
  21364. // look for points inside the triangle in both directions
  21365. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  21366. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  21367. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  21368. p = p.prevZ;
  21369. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  21370. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  21371. n = n.nextZ;
  21372. }
  21373. // look for remaining points in decreasing z-order
  21374. while ( p && p.z >= minZ ) {
  21375. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  21376. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  21377. p = p.prevZ;
  21378. }
  21379. // look for remaining points in increasing z-order
  21380. while ( n && n.z <= maxZ ) {
  21381. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  21382. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  21383. n = n.nextZ;
  21384. }
  21385. return true;
  21386. }
  21387. // go through all polygon nodes and cure small local self-intersections
  21388. function cureLocalIntersections( start, triangles, dim ) {
  21389. let p = start;
  21390. do {
  21391. const a = p.prev,
  21392. b = p.next.next;
  21393. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  21394. triangles.push( a.i / dim | 0 );
  21395. triangles.push( p.i / dim | 0 );
  21396. triangles.push( b.i / dim | 0 );
  21397. // remove two nodes involved
  21398. removeNode( p );
  21399. removeNode( p.next );
  21400. p = start = b;
  21401. }
  21402. p = p.next;
  21403. } while ( p !== start );
  21404. return filterPoints( p );
  21405. }
  21406. // try splitting polygon into two and triangulate them independently
  21407. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  21408. // look for a valid diagonal that divides the polygon into two
  21409. let a = start;
  21410. do {
  21411. let b = a.next.next;
  21412. while ( b !== a.prev ) {
  21413. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  21414. // split the polygon in two by the diagonal
  21415. let c = splitPolygon( a, b );
  21416. // filter colinear points around the cuts
  21417. a = filterPoints( a, a.next );
  21418. c = filterPoints( c, c.next );
  21419. // run earcut on each half
  21420. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  21421. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  21422. return;
  21423. }
  21424. b = b.next;
  21425. }
  21426. a = a.next;
  21427. } while ( a !== start );
  21428. }
  21429. // link every hole into the outer loop, producing a single-ring polygon without holes
  21430. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  21431. const queue = [];
  21432. let i, len, start, end, list;
  21433. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  21434. start = holeIndices[ i ] * dim;
  21435. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  21436. list = linkedList( data, start, end, dim, false );
  21437. if ( list === list.next ) list.steiner = true;
  21438. queue.push( getLeftmost( list ) );
  21439. }
  21440. queue.sort( compareX );
  21441. // process holes from left to right
  21442. for ( i = 0; i < queue.length; i ++ ) {
  21443. outerNode = eliminateHole( queue[ i ], outerNode );
  21444. }
  21445. return outerNode;
  21446. }
  21447. function compareX( a, b ) {
  21448. return a.x - b.x;
  21449. }
  21450. // find a bridge between vertices that connects hole with an outer ring and link it
  21451. function eliminateHole( hole, outerNode ) {
  21452. const bridge = findHoleBridge( hole, outerNode );
  21453. if ( ! bridge ) {
  21454. return outerNode;
  21455. }
  21456. const bridgeReverse = splitPolygon( bridge, hole );
  21457. // filter collinear points around the cuts
  21458. filterPoints( bridgeReverse, bridgeReverse.next );
  21459. return filterPoints( bridge, bridge.next );
  21460. }
  21461. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  21462. function findHoleBridge( hole, outerNode ) {
  21463. let p = outerNode,
  21464. qx = - Infinity,
  21465. m;
  21466. const hx = hole.x, hy = hole.y;
  21467. // find a segment intersected by a ray from the hole's leftmost point to the left;
  21468. // segment's endpoint with lesser x will be potential connection point
  21469. do {
  21470. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  21471. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  21472. if ( x <= hx && x > qx ) {
  21473. qx = x;
  21474. m = p.x < p.next.x ? p : p.next;
  21475. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  21476. }
  21477. }
  21478. p = p.next;
  21479. } while ( p !== outerNode );
  21480. if ( ! m ) return null;
  21481. // look for points inside the triangle of hole point, segment intersection and endpoint;
  21482. // if there are no points found, we have a valid connection;
  21483. // otherwise choose the point of the minimum angle with the ray as connection point
  21484. const stop = m,
  21485. mx = m.x,
  21486. my = m.y;
  21487. let tanMin = Infinity, tan;
  21488. p = m;
  21489. do {
  21490. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  21491. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  21492. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  21493. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  21494. m = p;
  21495. tanMin = tan;
  21496. }
  21497. }
  21498. p = p.next;
  21499. } while ( p !== stop );
  21500. return m;
  21501. }
  21502. // whether sector in vertex m contains sector in vertex p in the same coordinates
  21503. function sectorContainsSector( m, p ) {
  21504. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  21505. }
  21506. // interlink polygon nodes in z-order
  21507. function indexCurve( start, minX, minY, invSize ) {
  21508. let p = start;
  21509. do {
  21510. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  21511. p.prevZ = p.prev;
  21512. p.nextZ = p.next;
  21513. p = p.next;
  21514. } while ( p !== start );
  21515. p.prevZ.nextZ = null;
  21516. p.prevZ = null;
  21517. sortLinked( p );
  21518. }
  21519. // Simon Tatham's linked list merge sort algorithm
  21520. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  21521. function sortLinked( list ) {
  21522. let i, p, q, e, tail, numMerges, pSize, qSize,
  21523. inSize = 1;
  21524. do {
  21525. p = list;
  21526. list = null;
  21527. tail = null;
  21528. numMerges = 0;
  21529. while ( p ) {
  21530. numMerges ++;
  21531. q = p;
  21532. pSize = 0;
  21533. for ( i = 0; i < inSize; i ++ ) {
  21534. pSize ++;
  21535. q = q.nextZ;
  21536. if ( ! q ) break;
  21537. }
  21538. qSize = inSize;
  21539. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  21540. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  21541. e = p;
  21542. p = p.nextZ;
  21543. pSize --;
  21544. } else {
  21545. e = q;
  21546. q = q.nextZ;
  21547. qSize --;
  21548. }
  21549. if ( tail ) tail.nextZ = e;
  21550. else list = e;
  21551. e.prevZ = tail;
  21552. tail = e;
  21553. }
  21554. p = q;
  21555. }
  21556. tail.nextZ = null;
  21557. inSize *= 2;
  21558. } while ( numMerges > 1 );
  21559. return list;
  21560. }
  21561. // z-order of a point given coords and inverse of the longer side of data bbox
  21562. function zOrder( x, y, minX, minY, invSize ) {
  21563. // coords are transformed into non-negative 15-bit integer range
  21564. x = ( x - minX ) * invSize | 0;
  21565. y = ( y - minY ) * invSize | 0;
  21566. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  21567. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  21568. x = ( x | ( x << 2 ) ) & 0x33333333;
  21569. x = ( x | ( x << 1 ) ) & 0x55555555;
  21570. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  21571. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  21572. y = ( y | ( y << 2 ) ) & 0x33333333;
  21573. y = ( y | ( y << 1 ) ) & 0x55555555;
  21574. return x | ( y << 1 );
  21575. }
  21576. // find the leftmost node of a polygon ring
  21577. function getLeftmost( start ) {
  21578. let p = start,
  21579. leftmost = start;
  21580. do {
  21581. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  21582. p = p.next;
  21583. } while ( p !== start );
  21584. return leftmost;
  21585. }
  21586. // check if a point lies within a convex triangle
  21587. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  21588. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  21589. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  21590. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  21591. }
  21592. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  21593. function isValidDiagonal( a, b ) {
  21594. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  21595. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  21596. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  21597. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  21598. }
  21599. // signed area of a triangle
  21600. function area( p, q, r ) {
  21601. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  21602. }
  21603. // check if two points are equal
  21604. function equals( p1, p2 ) {
  21605. return p1.x === p2.x && p1.y === p2.y;
  21606. }
  21607. // check if two segments intersect
  21608. function intersects( p1, q1, p2, q2 ) {
  21609. const o1 = sign( area( p1, q1, p2 ) );
  21610. const o2 = sign( area( p1, q1, q2 ) );
  21611. const o3 = sign( area( p2, q2, p1 ) );
  21612. const o4 = sign( area( p2, q2, q1 ) );
  21613. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  21614. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  21615. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  21616. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  21617. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  21618. return false;
  21619. }
  21620. // for collinear points p, q, r, check if point q lies on segment pr
  21621. function onSegment( p, q, r ) {
  21622. 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 );
  21623. }
  21624. function sign( num ) {
  21625. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  21626. }
  21627. // check if a polygon diagonal intersects any polygon segments
  21628. function intersectsPolygon( a, b ) {
  21629. let p = a;
  21630. do {
  21631. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  21632. intersects( p, p.next, a, b ) ) return true;
  21633. p = p.next;
  21634. } while ( p !== a );
  21635. return false;
  21636. }
  21637. // check if a polygon diagonal is locally inside the polygon
  21638. function locallyInside( a, b ) {
  21639. return area( a.prev, a, a.next ) < 0 ?
  21640. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  21641. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  21642. }
  21643. // check if the middle point of a polygon diagonal is inside the polygon
  21644. function middleInside( a, b ) {
  21645. let p = a,
  21646. inside = false;
  21647. const px = ( a.x + b.x ) / 2,
  21648. py = ( a.y + b.y ) / 2;
  21649. do {
  21650. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  21651. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  21652. inside = ! inside;
  21653. p = p.next;
  21654. } while ( p !== a );
  21655. return inside;
  21656. }
  21657. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  21658. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  21659. function splitPolygon( a, b ) {
  21660. const a2 = new Node( a.i, a.x, a.y ),
  21661. b2 = new Node( b.i, b.x, b.y ),
  21662. an = a.next,
  21663. bp = b.prev;
  21664. a.next = b;
  21665. b.prev = a;
  21666. a2.next = an;
  21667. an.prev = a2;
  21668. b2.next = a2;
  21669. a2.prev = b2;
  21670. bp.next = b2;
  21671. b2.prev = bp;
  21672. return b2;
  21673. }
  21674. // create a node and optionally link it with previous one (in a circular doubly linked list)
  21675. function insertNode( i, x, y, last ) {
  21676. const p = new Node( i, x, y );
  21677. if ( ! last ) {
  21678. p.prev = p;
  21679. p.next = p;
  21680. } else {
  21681. p.next = last.next;
  21682. p.prev = last;
  21683. last.next.prev = p;
  21684. last.next = p;
  21685. }
  21686. return p;
  21687. }
  21688. function removeNode( p ) {
  21689. p.next.prev = p.prev;
  21690. p.prev.next = p.next;
  21691. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  21692. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  21693. }
  21694. function Node( i, x, y ) {
  21695. // vertex index in coordinates array
  21696. this.i = i;
  21697. // vertex coordinates
  21698. this.x = x;
  21699. this.y = y;
  21700. // previous and next vertex nodes in a polygon ring
  21701. this.prev = null;
  21702. this.next = null;
  21703. // z-order curve value
  21704. this.z = 0;
  21705. // previous and next nodes in z-order
  21706. this.prevZ = null;
  21707. this.nextZ = null;
  21708. // indicates whether this is a steiner point
  21709. this.steiner = false;
  21710. }
  21711. function signedArea( data, start, end, dim ) {
  21712. let sum = 0;
  21713. for ( let i = start, j = end - dim; i < end; i += dim ) {
  21714. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  21715. j = i;
  21716. }
  21717. return sum;
  21718. }
  21719. class ShapeUtils {
  21720. // calculate area of the contour polygon
  21721. static area( contour ) {
  21722. const n = contour.length;
  21723. let a = 0.0;
  21724. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  21725. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  21726. }
  21727. return a * 0.5;
  21728. }
  21729. static isClockWise( pts ) {
  21730. return ShapeUtils.area( pts ) < 0;
  21731. }
  21732. static triangulateShape( contour, holes ) {
  21733. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  21734. const holeIndices = []; // array of hole indices
  21735. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  21736. removeDupEndPts( contour );
  21737. addContour( vertices, contour );
  21738. //
  21739. let holeIndex = contour.length;
  21740. holes.forEach( removeDupEndPts );
  21741. for ( let i = 0; i < holes.length; i ++ ) {
  21742. holeIndices.push( holeIndex );
  21743. holeIndex += holes[ i ].length;
  21744. addContour( vertices, holes[ i ] );
  21745. }
  21746. //
  21747. const triangles = Earcut.triangulate( vertices, holeIndices );
  21748. //
  21749. for ( let i = 0; i < triangles.length; i += 3 ) {
  21750. faces.push( triangles.slice( i, i + 3 ) );
  21751. }
  21752. return faces;
  21753. }
  21754. }
  21755. function removeDupEndPts( points ) {
  21756. const l = points.length;
  21757. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  21758. points.pop();
  21759. }
  21760. }
  21761. function addContour( vertices, contour ) {
  21762. for ( let i = 0; i < contour.length; i ++ ) {
  21763. vertices.push( contour[ i ].x );
  21764. vertices.push( contour[ i ].y );
  21765. }
  21766. }
  21767. /**
  21768. * Creates extruded geometry from a path shape.
  21769. *
  21770. * parameters = {
  21771. *
  21772. * curveSegments: <int>, // number of points on the curves
  21773. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  21774. * depth: <float>, // Depth to extrude the shape
  21775. *
  21776. * bevelEnabled: <bool>, // turn on bevel
  21777. * bevelThickness: <float>, // how deep into the original shape bevel goes
  21778. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  21779. * bevelOffset: <float>, // how far from shape outline does bevel start
  21780. * bevelSegments: <int>, // number of bevel layers
  21781. *
  21782. * extrudePath: <THREE.Curve> // curve to extrude shape along
  21783. *
  21784. * UVGenerator: <Object> // object that provides UV generator functions
  21785. *
  21786. * }
  21787. */
  21788. class ExtrudeGeometry extends BufferGeometry {
  21789. 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 = {} ) {
  21790. super();
  21791. this.type = 'ExtrudeGeometry';
  21792. this.parameters = {
  21793. shapes: shapes,
  21794. options: options
  21795. };
  21796. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  21797. const scope = this;
  21798. const verticesArray = [];
  21799. const uvArray = [];
  21800. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21801. const shape = shapes[ i ];
  21802. addShape( shape );
  21803. }
  21804. // build geometry
  21805. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  21806. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  21807. this.computeVertexNormals();
  21808. // functions
  21809. function addShape( shape ) {
  21810. const placeholder = [];
  21811. // options
  21812. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  21813. const steps = options.steps !== undefined ? options.steps : 1;
  21814. const depth = options.depth !== undefined ? options.depth : 1;
  21815. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  21816. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  21817. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  21818. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  21819. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  21820. const extrudePath = options.extrudePath;
  21821. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  21822. //
  21823. let extrudePts, extrudeByPath = false;
  21824. let splineTube, binormal, normal, position2;
  21825. if ( extrudePath ) {
  21826. extrudePts = extrudePath.getSpacedPoints( steps );
  21827. extrudeByPath = true;
  21828. bevelEnabled = false; // bevels not supported for path extrusion
  21829. // SETUP TNB variables
  21830. // TODO1 - have a .isClosed in spline?
  21831. splineTube = extrudePath.computeFrenetFrames( steps, false );
  21832. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  21833. binormal = new Vector3();
  21834. normal = new Vector3();
  21835. position2 = new Vector3();
  21836. }
  21837. // Safeguards if bevels are not enabled
  21838. if ( ! bevelEnabled ) {
  21839. bevelSegments = 0;
  21840. bevelThickness = 0;
  21841. bevelSize = 0;
  21842. bevelOffset = 0;
  21843. }
  21844. // Variables initialization
  21845. const shapePoints = shape.extractPoints( curveSegments );
  21846. let vertices = shapePoints.shape;
  21847. const holes = shapePoints.holes;
  21848. const reverse = ! ShapeUtils.isClockWise( vertices );
  21849. if ( reverse ) {
  21850. vertices = vertices.reverse();
  21851. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  21852. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21853. const ahole = holes[ h ];
  21854. if ( ShapeUtils.isClockWise( ahole ) ) {
  21855. holes[ h ] = ahole.reverse();
  21856. }
  21857. }
  21858. }
  21859. const faces = ShapeUtils.triangulateShape( vertices, holes );
  21860. /* Vertices */
  21861. const contour = vertices; // vertices has all points but contour has only points of circumference
  21862. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21863. const ahole = holes[ h ];
  21864. vertices = vertices.concat( ahole );
  21865. }
  21866. function scalePt2( pt, vec, size ) {
  21867. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  21868. return pt.clone().addScaledVector( vec, size );
  21869. }
  21870. const vlen = vertices.length, flen = faces.length;
  21871. // Find directions for point movement
  21872. function getBevelVec( inPt, inPrev, inNext ) {
  21873. // computes for inPt the corresponding point inPt' on a new contour
  21874. // shifted by 1 unit (length of normalized vector) to the left
  21875. // if we walk along contour clockwise, this new contour is outside the old one
  21876. //
  21877. // inPt' is the intersection of the two lines parallel to the two
  21878. // adjacent edges of inPt at a distance of 1 unit on the left side.
  21879. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  21880. // good reading for geometry algorithms (here: line-line intersection)
  21881. // http://geomalgorithms.com/a05-_intersect-1.html
  21882. const v_prev_x = inPt.x - inPrev.x,
  21883. v_prev_y = inPt.y - inPrev.y;
  21884. const v_next_x = inNext.x - inPt.x,
  21885. v_next_y = inNext.y - inPt.y;
  21886. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  21887. // check for collinear edges
  21888. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21889. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  21890. // not collinear
  21891. // length of vectors for normalizing
  21892. const v_prev_len = Math.sqrt( v_prev_lensq );
  21893. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  21894. // shift adjacent points by unit vectors to the left
  21895. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  21896. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  21897. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  21898. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  21899. // scaling factor for v_prev to intersection point
  21900. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  21901. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  21902. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21903. // vector from inPt to intersection point
  21904. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  21905. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  21906. // Don't normalize!, otherwise sharp corners become ugly
  21907. // but prevent crazy spikes
  21908. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  21909. if ( v_trans_lensq <= 2 ) {
  21910. return new Vector2( v_trans_x, v_trans_y );
  21911. } else {
  21912. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  21913. }
  21914. } else {
  21915. // handle special case of collinear edges
  21916. let direction_eq = false; // assumes: opposite
  21917. if ( v_prev_x > Number.EPSILON ) {
  21918. if ( v_next_x > Number.EPSILON ) {
  21919. direction_eq = true;
  21920. }
  21921. } else {
  21922. if ( v_prev_x < - Number.EPSILON ) {
  21923. if ( v_next_x < - Number.EPSILON ) {
  21924. direction_eq = true;
  21925. }
  21926. } else {
  21927. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  21928. direction_eq = true;
  21929. }
  21930. }
  21931. }
  21932. if ( direction_eq ) {
  21933. // console.log("Warning: lines are a straight sequence");
  21934. v_trans_x = - v_prev_y;
  21935. v_trans_y = v_prev_x;
  21936. shrink_by = Math.sqrt( v_prev_lensq );
  21937. } else {
  21938. // console.log("Warning: lines are a straight spike");
  21939. v_trans_x = v_prev_x;
  21940. v_trans_y = v_prev_y;
  21941. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  21942. }
  21943. }
  21944. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  21945. }
  21946. const contourMovements = [];
  21947. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21948. if ( j === il ) j = 0;
  21949. if ( k === il ) k = 0;
  21950. // (j)---(i)---(k)
  21951. // console.log('i,j,k', i, j , k)
  21952. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  21953. }
  21954. const holesMovements = [];
  21955. let oneHoleMovements, verticesMovements = contourMovements.concat();
  21956. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21957. const ahole = holes[ h ];
  21958. oneHoleMovements = [];
  21959. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21960. if ( j === il ) j = 0;
  21961. if ( k === il ) k = 0;
  21962. // (j)---(i)---(k)
  21963. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  21964. }
  21965. holesMovements.push( oneHoleMovements );
  21966. verticesMovements = verticesMovements.concat( oneHoleMovements );
  21967. }
  21968. // Loop bevelSegments, 1 for the front, 1 for the back
  21969. for ( let b = 0; b < bevelSegments; b ++ ) {
  21970. //for ( b = bevelSegments; b > 0; b -- ) {
  21971. const t = b / bevelSegments;
  21972. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21973. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21974. // contract shape
  21975. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21976. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21977. v( vert.x, vert.y, - z );
  21978. }
  21979. // expand holes
  21980. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21981. const ahole = holes[ h ];
  21982. oneHoleMovements = holesMovements[ h ];
  21983. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21984. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21985. v( vert.x, vert.y, - z );
  21986. }
  21987. }
  21988. }
  21989. const bs = bevelSize + bevelOffset;
  21990. // Back facing vertices
  21991. for ( let i = 0; i < vlen; i ++ ) {
  21992. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21993. if ( ! extrudeByPath ) {
  21994. v( vert.x, vert.y, 0 );
  21995. } else {
  21996. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  21997. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  21998. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  21999. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  22000. v( position2.x, position2.y, position2.z );
  22001. }
  22002. }
  22003. // Add stepped vertices...
  22004. // Including front facing vertices
  22005. for ( let s = 1; s <= steps; s ++ ) {
  22006. for ( let i = 0; i < vlen; i ++ ) {
  22007. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  22008. if ( ! extrudeByPath ) {
  22009. v( vert.x, vert.y, depth / steps * s );
  22010. } else {
  22011. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  22012. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  22013. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  22014. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  22015. v( position2.x, position2.y, position2.z );
  22016. }
  22017. }
  22018. }
  22019. // Add bevel segments planes
  22020. //for ( b = 1; b <= bevelSegments; b ++ ) {
  22021. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  22022. const t = b / bevelSegments;
  22023. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  22024. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  22025. // contract shape
  22026. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  22027. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  22028. v( vert.x, vert.y, depth + z );
  22029. }
  22030. // expand holes
  22031. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  22032. const ahole = holes[ h ];
  22033. oneHoleMovements = holesMovements[ h ];
  22034. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  22035. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  22036. if ( ! extrudeByPath ) {
  22037. v( vert.x, vert.y, depth + z );
  22038. } else {
  22039. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  22040. }
  22041. }
  22042. }
  22043. }
  22044. /* Faces */
  22045. // Top and bottom faces
  22046. buildLidFaces();
  22047. // Sides faces
  22048. buildSideFaces();
  22049. ///// Internal functions
  22050. function buildLidFaces() {
  22051. const start = verticesArray.length / 3;
  22052. if ( bevelEnabled ) {
  22053. let layer = 0; // steps + 1
  22054. let offset = vlen * layer;
  22055. // Bottom faces
  22056. for ( let i = 0; i < flen; i ++ ) {
  22057. const face = faces[ i ];
  22058. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  22059. }
  22060. layer = steps + bevelSegments * 2;
  22061. offset = vlen * layer;
  22062. // Top faces
  22063. for ( let i = 0; i < flen; i ++ ) {
  22064. const face = faces[ i ];
  22065. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  22066. }
  22067. } else {
  22068. // Bottom faces
  22069. for ( let i = 0; i < flen; i ++ ) {
  22070. const face = faces[ i ];
  22071. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  22072. }
  22073. // Top faces
  22074. for ( let i = 0; i < flen; i ++ ) {
  22075. const face = faces[ i ];
  22076. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  22077. }
  22078. }
  22079. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  22080. }
  22081. // Create faces for the z-sides of the shape
  22082. function buildSideFaces() {
  22083. const start = verticesArray.length / 3;
  22084. let layeroffset = 0;
  22085. sidewalls( contour, layeroffset );
  22086. layeroffset += contour.length;
  22087. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  22088. const ahole = holes[ h ];
  22089. sidewalls( ahole, layeroffset );
  22090. //, true
  22091. layeroffset += ahole.length;
  22092. }
  22093. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  22094. }
  22095. function sidewalls( contour, layeroffset ) {
  22096. let i = contour.length;
  22097. while ( -- i >= 0 ) {
  22098. const j = i;
  22099. let k = i - 1;
  22100. if ( k < 0 ) k = contour.length - 1;
  22101. //console.log('b', i,j, i-1, k,vertices.length);
  22102. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  22103. const slen1 = vlen * s;
  22104. const slen2 = vlen * ( s + 1 );
  22105. const a = layeroffset + j + slen1,
  22106. b = layeroffset + k + slen1,
  22107. c = layeroffset + k + slen2,
  22108. d = layeroffset + j + slen2;
  22109. f4( a, b, c, d );
  22110. }
  22111. }
  22112. }
  22113. function v( x, y, z ) {
  22114. placeholder.push( x );
  22115. placeholder.push( y );
  22116. placeholder.push( z );
  22117. }
  22118. function f3( a, b, c ) {
  22119. addVertex( a );
  22120. addVertex( b );
  22121. addVertex( c );
  22122. const nextIndex = verticesArray.length / 3;
  22123. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  22124. addUV( uvs[ 0 ] );
  22125. addUV( uvs[ 1 ] );
  22126. addUV( uvs[ 2 ] );
  22127. }
  22128. function f4( a, b, c, d ) {
  22129. addVertex( a );
  22130. addVertex( b );
  22131. addVertex( d );
  22132. addVertex( b );
  22133. addVertex( c );
  22134. addVertex( d );
  22135. const nextIndex = verticesArray.length / 3;
  22136. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  22137. addUV( uvs[ 0 ] );
  22138. addUV( uvs[ 1 ] );
  22139. addUV( uvs[ 3 ] );
  22140. addUV( uvs[ 1 ] );
  22141. addUV( uvs[ 2 ] );
  22142. addUV( uvs[ 3 ] );
  22143. }
  22144. function addVertex( index ) {
  22145. verticesArray.push( placeholder[ index * 3 + 0 ] );
  22146. verticesArray.push( placeholder[ index * 3 + 1 ] );
  22147. verticesArray.push( placeholder[ index * 3 + 2 ] );
  22148. }
  22149. function addUV( vector2 ) {
  22150. uvArray.push( vector2.x );
  22151. uvArray.push( vector2.y );
  22152. }
  22153. }
  22154. }
  22155. copy( source ) {
  22156. super.copy( source );
  22157. this.parameters = Object.assign( {}, source.parameters );
  22158. return this;
  22159. }
  22160. toJSON() {
  22161. const data = super.toJSON();
  22162. const shapes = this.parameters.shapes;
  22163. const options = this.parameters.options;
  22164. return toJSON$1( shapes, options, data );
  22165. }
  22166. static fromJSON( data, shapes ) {
  22167. const geometryShapes = [];
  22168. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  22169. const shape = shapes[ data.shapes[ j ] ];
  22170. geometryShapes.push( shape );
  22171. }
  22172. const extrudePath = data.options.extrudePath;
  22173. if ( extrudePath !== undefined ) {
  22174. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  22175. }
  22176. return new ExtrudeGeometry( geometryShapes, data.options );
  22177. }
  22178. }
  22179. const WorldUVGenerator = {
  22180. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  22181. const a_x = vertices[ indexA * 3 ];
  22182. const a_y = vertices[ indexA * 3 + 1 ];
  22183. const b_x = vertices[ indexB * 3 ];
  22184. const b_y = vertices[ indexB * 3 + 1 ];
  22185. const c_x = vertices[ indexC * 3 ];
  22186. const c_y = vertices[ indexC * 3 + 1 ];
  22187. return [
  22188. new Vector2( a_x, a_y ),
  22189. new Vector2( b_x, b_y ),
  22190. new Vector2( c_x, c_y )
  22191. ];
  22192. },
  22193. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  22194. const a_x = vertices[ indexA * 3 ];
  22195. const a_y = vertices[ indexA * 3 + 1 ];
  22196. const a_z = vertices[ indexA * 3 + 2 ];
  22197. const b_x = vertices[ indexB * 3 ];
  22198. const b_y = vertices[ indexB * 3 + 1 ];
  22199. const b_z = vertices[ indexB * 3 + 2 ];
  22200. const c_x = vertices[ indexC * 3 ];
  22201. const c_y = vertices[ indexC * 3 + 1 ];
  22202. const c_z = vertices[ indexC * 3 + 2 ];
  22203. const d_x = vertices[ indexD * 3 ];
  22204. const d_y = vertices[ indexD * 3 + 1 ];
  22205. const d_z = vertices[ indexD * 3 + 2 ];
  22206. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  22207. return [
  22208. new Vector2( a_x, 1 - a_z ),
  22209. new Vector2( b_x, 1 - b_z ),
  22210. new Vector2( c_x, 1 - c_z ),
  22211. new Vector2( d_x, 1 - d_z )
  22212. ];
  22213. } else {
  22214. return [
  22215. new Vector2( a_y, 1 - a_z ),
  22216. new Vector2( b_y, 1 - b_z ),
  22217. new Vector2( c_y, 1 - c_z ),
  22218. new Vector2( d_y, 1 - d_z )
  22219. ];
  22220. }
  22221. }
  22222. };
  22223. function toJSON$1( shapes, options, data ) {
  22224. data.shapes = [];
  22225. if ( Array.isArray( shapes ) ) {
  22226. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  22227. const shape = shapes[ i ];
  22228. data.shapes.push( shape.uuid );
  22229. }
  22230. } else {
  22231. data.shapes.push( shapes.uuid );
  22232. }
  22233. data.options = Object.assign( {}, options );
  22234. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  22235. return data;
  22236. }
  22237. class IcosahedronGeometry extends PolyhedronGeometry {
  22238. constructor( radius = 1, detail = 0 ) {
  22239. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  22240. const vertices = [
  22241. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  22242. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  22243. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  22244. ];
  22245. const indices = [
  22246. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  22247. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  22248. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  22249. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  22250. ];
  22251. super( vertices, indices, radius, detail );
  22252. this.type = 'IcosahedronGeometry';
  22253. this.parameters = {
  22254. radius: radius,
  22255. detail: detail
  22256. };
  22257. }
  22258. static fromJSON( data ) {
  22259. return new IcosahedronGeometry( data.radius, data.detail );
  22260. }
  22261. }
  22262. class OctahedronGeometry extends PolyhedronGeometry {
  22263. constructor( radius = 1, detail = 0 ) {
  22264. const vertices = [
  22265. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  22266. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  22267. ];
  22268. const indices = [
  22269. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  22270. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  22271. 1, 3, 4, 1, 4, 2
  22272. ];
  22273. super( vertices, indices, radius, detail );
  22274. this.type = 'OctahedronGeometry';
  22275. this.parameters = {
  22276. radius: radius,
  22277. detail: detail
  22278. };
  22279. }
  22280. static fromJSON( data ) {
  22281. return new OctahedronGeometry( data.radius, data.detail );
  22282. }
  22283. }
  22284. class RingGeometry extends BufferGeometry {
  22285. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22286. super();
  22287. this.type = 'RingGeometry';
  22288. this.parameters = {
  22289. innerRadius: innerRadius,
  22290. outerRadius: outerRadius,
  22291. thetaSegments: thetaSegments,
  22292. phiSegments: phiSegments,
  22293. thetaStart: thetaStart,
  22294. thetaLength: thetaLength
  22295. };
  22296. thetaSegments = Math.max( 3, thetaSegments );
  22297. phiSegments = Math.max( 1, phiSegments );
  22298. // buffers
  22299. const indices = [];
  22300. const vertices = [];
  22301. const normals = [];
  22302. const uvs = [];
  22303. // some helper variables
  22304. let radius = innerRadius;
  22305. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  22306. const vertex = new Vector3();
  22307. const uv = new Vector2();
  22308. // generate vertices, normals and uvs
  22309. for ( let j = 0; j <= phiSegments; j ++ ) {
  22310. for ( let i = 0; i <= thetaSegments; i ++ ) {
  22311. // values are generate from the inside of the ring to the outside
  22312. const segment = thetaStart + i / thetaSegments * thetaLength;
  22313. // vertex
  22314. vertex.x = radius * Math.cos( segment );
  22315. vertex.y = radius * Math.sin( segment );
  22316. vertices.push( vertex.x, vertex.y, vertex.z );
  22317. // normal
  22318. normals.push( 0, 0, 1 );
  22319. // uv
  22320. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  22321. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  22322. uvs.push( uv.x, uv.y );
  22323. }
  22324. // increase the radius for next row of vertices
  22325. radius += radiusStep;
  22326. }
  22327. // indices
  22328. for ( let j = 0; j < phiSegments; j ++ ) {
  22329. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  22330. for ( let i = 0; i < thetaSegments; i ++ ) {
  22331. const segment = i + thetaSegmentLevel;
  22332. const a = segment;
  22333. const b = segment + thetaSegments + 1;
  22334. const c = segment + thetaSegments + 2;
  22335. const d = segment + 1;
  22336. // faces
  22337. indices.push( a, b, d );
  22338. indices.push( b, c, d );
  22339. }
  22340. }
  22341. // build geometry
  22342. this.setIndex( indices );
  22343. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22344. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22345. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22346. }
  22347. copy( source ) {
  22348. super.copy( source );
  22349. this.parameters = Object.assign( {}, source.parameters );
  22350. return this;
  22351. }
  22352. static fromJSON( data ) {
  22353. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  22354. }
  22355. }
  22356. class ShapeGeometry extends BufferGeometry {
  22357. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  22358. super();
  22359. this.type = 'ShapeGeometry';
  22360. this.parameters = {
  22361. shapes: shapes,
  22362. curveSegments: curveSegments
  22363. };
  22364. // buffers
  22365. const indices = [];
  22366. const vertices = [];
  22367. const normals = [];
  22368. const uvs = [];
  22369. // helper variables
  22370. let groupStart = 0;
  22371. let groupCount = 0;
  22372. // allow single and array values for "shapes" parameter
  22373. if ( Array.isArray( shapes ) === false ) {
  22374. addShape( shapes );
  22375. } else {
  22376. for ( let i = 0; i < shapes.length; i ++ ) {
  22377. addShape( shapes[ i ] );
  22378. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  22379. groupStart += groupCount;
  22380. groupCount = 0;
  22381. }
  22382. }
  22383. // build geometry
  22384. this.setIndex( indices );
  22385. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22386. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22387. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22388. // helper functions
  22389. function addShape( shape ) {
  22390. const indexOffset = vertices.length / 3;
  22391. const points = shape.extractPoints( curveSegments );
  22392. let shapeVertices = points.shape;
  22393. const shapeHoles = points.holes;
  22394. // check direction of vertices
  22395. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  22396. shapeVertices = shapeVertices.reverse();
  22397. }
  22398. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  22399. const shapeHole = shapeHoles[ i ];
  22400. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  22401. shapeHoles[ i ] = shapeHole.reverse();
  22402. }
  22403. }
  22404. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  22405. // join vertices of inner and outer paths to a single array
  22406. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  22407. const shapeHole = shapeHoles[ i ];
  22408. shapeVertices = shapeVertices.concat( shapeHole );
  22409. }
  22410. // vertices, normals, uvs
  22411. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  22412. const vertex = shapeVertices[ i ];
  22413. vertices.push( vertex.x, vertex.y, 0 );
  22414. normals.push( 0, 0, 1 );
  22415. uvs.push( vertex.x, vertex.y ); // world uvs
  22416. }
  22417. // indices
  22418. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  22419. const face = faces[ i ];
  22420. const a = face[ 0 ] + indexOffset;
  22421. const b = face[ 1 ] + indexOffset;
  22422. const c = face[ 2 ] + indexOffset;
  22423. indices.push( a, b, c );
  22424. groupCount += 3;
  22425. }
  22426. }
  22427. }
  22428. copy( source ) {
  22429. super.copy( source );
  22430. this.parameters = Object.assign( {}, source.parameters );
  22431. return this;
  22432. }
  22433. toJSON() {
  22434. const data = super.toJSON();
  22435. const shapes = this.parameters.shapes;
  22436. return toJSON( shapes, data );
  22437. }
  22438. static fromJSON( data, shapes ) {
  22439. const geometryShapes = [];
  22440. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  22441. const shape = shapes[ data.shapes[ j ] ];
  22442. geometryShapes.push( shape );
  22443. }
  22444. return new ShapeGeometry( geometryShapes, data.curveSegments );
  22445. }
  22446. }
  22447. function toJSON( shapes, data ) {
  22448. data.shapes = [];
  22449. if ( Array.isArray( shapes ) ) {
  22450. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  22451. const shape = shapes[ i ];
  22452. data.shapes.push( shape.uuid );
  22453. }
  22454. } else {
  22455. data.shapes.push( shapes.uuid );
  22456. }
  22457. return data;
  22458. }
  22459. class SphereGeometry extends BufferGeometry {
  22460. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  22461. super();
  22462. this.type = 'SphereGeometry';
  22463. this.parameters = {
  22464. radius: radius,
  22465. widthSegments: widthSegments,
  22466. heightSegments: heightSegments,
  22467. phiStart: phiStart,
  22468. phiLength: phiLength,
  22469. thetaStart: thetaStart,
  22470. thetaLength: thetaLength
  22471. };
  22472. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  22473. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  22474. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  22475. let index = 0;
  22476. const grid = [];
  22477. const vertex = new Vector3();
  22478. const normal = new Vector3();
  22479. // buffers
  22480. const indices = [];
  22481. const vertices = [];
  22482. const normals = [];
  22483. const uvs = [];
  22484. // generate vertices, normals and uvs
  22485. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  22486. const verticesRow = [];
  22487. const v = iy / heightSegments;
  22488. // special case for the poles
  22489. let uOffset = 0;
  22490. if ( iy === 0 && thetaStart === 0 ) {
  22491. uOffset = 0.5 / widthSegments;
  22492. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  22493. uOffset = - 0.5 / widthSegments;
  22494. }
  22495. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  22496. const u = ix / widthSegments;
  22497. // vertex
  22498. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22499. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  22500. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22501. vertices.push( vertex.x, vertex.y, vertex.z );
  22502. // normal
  22503. normal.copy( vertex ).normalize();
  22504. normals.push( normal.x, normal.y, normal.z );
  22505. // uv
  22506. uvs.push( u + uOffset, 1 - v );
  22507. verticesRow.push( index ++ );
  22508. }
  22509. grid.push( verticesRow );
  22510. }
  22511. // indices
  22512. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  22513. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  22514. const a = grid[ iy ][ ix + 1 ];
  22515. const b = grid[ iy ][ ix ];
  22516. const c = grid[ iy + 1 ][ ix ];
  22517. const d = grid[ iy + 1 ][ ix + 1 ];
  22518. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  22519. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  22520. }
  22521. }
  22522. // build geometry
  22523. this.setIndex( indices );
  22524. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22525. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22526. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22527. }
  22528. copy( source ) {
  22529. super.copy( source );
  22530. this.parameters = Object.assign( {}, source.parameters );
  22531. return this;
  22532. }
  22533. static fromJSON( data ) {
  22534. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  22535. }
  22536. }
  22537. class TetrahedronGeometry extends PolyhedronGeometry {
  22538. constructor( radius = 1, detail = 0 ) {
  22539. const vertices = [
  22540. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  22541. ];
  22542. const indices = [
  22543. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  22544. ];
  22545. super( vertices, indices, radius, detail );
  22546. this.type = 'TetrahedronGeometry';
  22547. this.parameters = {
  22548. radius: radius,
  22549. detail: detail
  22550. };
  22551. }
  22552. static fromJSON( data ) {
  22553. return new TetrahedronGeometry( data.radius, data.detail );
  22554. }
  22555. }
  22556. class TorusGeometry extends BufferGeometry {
  22557. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  22558. super();
  22559. this.type = 'TorusGeometry';
  22560. this.parameters = {
  22561. radius: radius,
  22562. tube: tube,
  22563. radialSegments: radialSegments,
  22564. tubularSegments: tubularSegments,
  22565. arc: arc
  22566. };
  22567. radialSegments = Math.floor( radialSegments );
  22568. tubularSegments = Math.floor( tubularSegments );
  22569. // buffers
  22570. const indices = [];
  22571. const vertices = [];
  22572. const normals = [];
  22573. const uvs = [];
  22574. // helper variables
  22575. const center = new Vector3();
  22576. const vertex = new Vector3();
  22577. const normal = new Vector3();
  22578. // generate vertices, normals and uvs
  22579. for ( let j = 0; j <= radialSegments; j ++ ) {
  22580. for ( let i = 0; i <= tubularSegments; i ++ ) {
  22581. const u = i / tubularSegments * arc;
  22582. const v = j / radialSegments * Math.PI * 2;
  22583. // vertex
  22584. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  22585. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  22586. vertex.z = tube * Math.sin( v );
  22587. vertices.push( vertex.x, vertex.y, vertex.z );
  22588. // normal
  22589. center.x = radius * Math.cos( u );
  22590. center.y = radius * Math.sin( u );
  22591. normal.subVectors( vertex, center ).normalize();
  22592. normals.push( normal.x, normal.y, normal.z );
  22593. // uv
  22594. uvs.push( i / tubularSegments );
  22595. uvs.push( j / radialSegments );
  22596. }
  22597. }
  22598. // generate indices
  22599. for ( let j = 1; j <= radialSegments; j ++ ) {
  22600. for ( let i = 1; i <= tubularSegments; i ++ ) {
  22601. // indices
  22602. const a = ( tubularSegments + 1 ) * j + i - 1;
  22603. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  22604. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  22605. const d = ( tubularSegments + 1 ) * j + i;
  22606. // faces
  22607. indices.push( a, b, d );
  22608. indices.push( b, c, d );
  22609. }
  22610. }
  22611. // build geometry
  22612. this.setIndex( indices );
  22613. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22614. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22615. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22616. }
  22617. copy( source ) {
  22618. super.copy( source );
  22619. this.parameters = Object.assign( {}, source.parameters );
  22620. return this;
  22621. }
  22622. static fromJSON( data ) {
  22623. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  22624. }
  22625. }
  22626. class TorusKnotGeometry extends BufferGeometry {
  22627. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  22628. super();
  22629. this.type = 'TorusKnotGeometry';
  22630. this.parameters = {
  22631. radius: radius,
  22632. tube: tube,
  22633. tubularSegments: tubularSegments,
  22634. radialSegments: radialSegments,
  22635. p: p,
  22636. q: q
  22637. };
  22638. tubularSegments = Math.floor( tubularSegments );
  22639. radialSegments = Math.floor( radialSegments );
  22640. // buffers
  22641. const indices = [];
  22642. const vertices = [];
  22643. const normals = [];
  22644. const uvs = [];
  22645. // helper variables
  22646. const vertex = new Vector3();
  22647. const normal = new Vector3();
  22648. const P1 = new Vector3();
  22649. const P2 = new Vector3();
  22650. const B = new Vector3();
  22651. const T = new Vector3();
  22652. const N = new Vector3();
  22653. // generate vertices, normals and uvs
  22654. for ( let i = 0; i <= tubularSegments; ++ i ) {
  22655. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  22656. const u = i / tubularSegments * p * Math.PI * 2;
  22657. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  22658. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  22659. calculatePositionOnCurve( u, p, q, radius, P1 );
  22660. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  22661. // calculate orthonormal basis
  22662. T.subVectors( P2, P1 );
  22663. N.addVectors( P2, P1 );
  22664. B.crossVectors( T, N );
  22665. N.crossVectors( B, T );
  22666. // normalize B, N. T can be ignored, we don't use it
  22667. B.normalize();
  22668. N.normalize();
  22669. for ( let j = 0; j <= radialSegments; ++ j ) {
  22670. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  22671. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  22672. const v = j / radialSegments * Math.PI * 2;
  22673. const cx = - tube * Math.cos( v );
  22674. const cy = tube * Math.sin( v );
  22675. // now calculate the final vertex position.
  22676. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  22677. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  22678. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  22679. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  22680. vertices.push( vertex.x, vertex.y, vertex.z );
  22681. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  22682. normal.subVectors( vertex, P1 ).normalize();
  22683. normals.push( normal.x, normal.y, normal.z );
  22684. // uv
  22685. uvs.push( i / tubularSegments );
  22686. uvs.push( j / radialSegments );
  22687. }
  22688. }
  22689. // generate indices
  22690. for ( let j = 1; j <= tubularSegments; j ++ ) {
  22691. for ( let i = 1; i <= radialSegments; i ++ ) {
  22692. // indices
  22693. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  22694. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  22695. const c = ( radialSegments + 1 ) * j + i;
  22696. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  22697. // faces
  22698. indices.push( a, b, d );
  22699. indices.push( b, c, d );
  22700. }
  22701. }
  22702. // build geometry
  22703. this.setIndex( indices );
  22704. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22705. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22706. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22707. // this function calculates the current position on the torus curve
  22708. function calculatePositionOnCurve( u, p, q, radius, position ) {
  22709. const cu = Math.cos( u );
  22710. const su = Math.sin( u );
  22711. const quOverP = q / p * u;
  22712. const cs = Math.cos( quOverP );
  22713. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  22714. position.y = radius * ( 2 + cs ) * su * 0.5;
  22715. position.z = radius * Math.sin( quOverP ) * 0.5;
  22716. }
  22717. }
  22718. copy( source ) {
  22719. super.copy( source );
  22720. this.parameters = Object.assign( {}, source.parameters );
  22721. return this;
  22722. }
  22723. static fromJSON( data ) {
  22724. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  22725. }
  22726. }
  22727. class TubeGeometry extends BufferGeometry {
  22728. 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 ) {
  22729. super();
  22730. this.type = 'TubeGeometry';
  22731. this.parameters = {
  22732. path: path,
  22733. tubularSegments: tubularSegments,
  22734. radius: radius,
  22735. radialSegments: radialSegments,
  22736. closed: closed
  22737. };
  22738. const frames = path.computeFrenetFrames( tubularSegments, closed );
  22739. // expose internals
  22740. this.tangents = frames.tangents;
  22741. this.normals = frames.normals;
  22742. this.binormals = frames.binormals;
  22743. // helper variables
  22744. const vertex = new Vector3();
  22745. const normal = new Vector3();
  22746. const uv = new Vector2();
  22747. let P = new Vector3();
  22748. // buffer
  22749. const vertices = [];
  22750. const normals = [];
  22751. const uvs = [];
  22752. const indices = [];
  22753. // create buffer data
  22754. generateBufferData();
  22755. // build geometry
  22756. this.setIndex( indices );
  22757. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22758. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22759. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22760. // functions
  22761. function generateBufferData() {
  22762. for ( let i = 0; i < tubularSegments; i ++ ) {
  22763. generateSegment( i );
  22764. }
  22765. // if the geometry is not closed, generate the last row of vertices and normals
  22766. // at the regular position on the given path
  22767. //
  22768. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  22769. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  22770. // uvs are generated in a separate function.
  22771. // this makes it easy compute correct values for closed geometries
  22772. generateUVs();
  22773. // finally create faces
  22774. generateIndices();
  22775. }
  22776. function generateSegment( i ) {
  22777. // we use getPointAt to sample evenly distributed points from the given path
  22778. P = path.getPointAt( i / tubularSegments, P );
  22779. // retrieve corresponding normal and binormal
  22780. const N = frames.normals[ i ];
  22781. const B = frames.binormals[ i ];
  22782. // generate normals and vertices for the current segment
  22783. for ( let j = 0; j <= radialSegments; j ++ ) {
  22784. const v = j / radialSegments * Math.PI * 2;
  22785. const sin = Math.sin( v );
  22786. const cos = - Math.cos( v );
  22787. // normal
  22788. normal.x = ( cos * N.x + sin * B.x );
  22789. normal.y = ( cos * N.y + sin * B.y );
  22790. normal.z = ( cos * N.z + sin * B.z );
  22791. normal.normalize();
  22792. normals.push( normal.x, normal.y, normal.z );
  22793. // vertex
  22794. vertex.x = P.x + radius * normal.x;
  22795. vertex.y = P.y + radius * normal.y;
  22796. vertex.z = P.z + radius * normal.z;
  22797. vertices.push( vertex.x, vertex.y, vertex.z );
  22798. }
  22799. }
  22800. function generateIndices() {
  22801. for ( let j = 1; j <= tubularSegments; j ++ ) {
  22802. for ( let i = 1; i <= radialSegments; i ++ ) {
  22803. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  22804. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  22805. const c = ( radialSegments + 1 ) * j + i;
  22806. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  22807. // faces
  22808. indices.push( a, b, d );
  22809. indices.push( b, c, d );
  22810. }
  22811. }
  22812. }
  22813. function generateUVs() {
  22814. for ( let i = 0; i <= tubularSegments; i ++ ) {
  22815. for ( let j = 0; j <= radialSegments; j ++ ) {
  22816. uv.x = i / tubularSegments;
  22817. uv.y = j / radialSegments;
  22818. uvs.push( uv.x, uv.y );
  22819. }
  22820. }
  22821. }
  22822. }
  22823. copy( source ) {
  22824. super.copy( source );
  22825. this.parameters = Object.assign( {}, source.parameters );
  22826. return this;
  22827. }
  22828. toJSON() {
  22829. const data = super.toJSON();
  22830. data.path = this.parameters.path.toJSON();
  22831. return data;
  22832. }
  22833. static fromJSON( data ) {
  22834. // This only works for built-in curves (e.g. CatmullRomCurve3).
  22835. // User defined curves or instances of CurvePath will not be deserialized.
  22836. return new TubeGeometry(
  22837. new Curves[ data.path.type ]().fromJSON( data.path ),
  22838. data.tubularSegments,
  22839. data.radius,
  22840. data.radialSegments,
  22841. data.closed
  22842. );
  22843. }
  22844. }
  22845. class WireframeGeometry extends BufferGeometry {
  22846. constructor( geometry = null ) {
  22847. super();
  22848. this.type = 'WireframeGeometry';
  22849. this.parameters = {
  22850. geometry: geometry
  22851. };
  22852. if ( geometry !== null ) {
  22853. // buffer
  22854. const vertices = [];
  22855. const edges = new Set();
  22856. // helper variables
  22857. const start = new Vector3();
  22858. const end = new Vector3();
  22859. if ( geometry.index !== null ) {
  22860. // indexed BufferGeometry
  22861. const position = geometry.attributes.position;
  22862. const indices = geometry.index;
  22863. let groups = geometry.groups;
  22864. if ( groups.length === 0 ) {
  22865. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  22866. }
  22867. // create a data structure that contains all edges without duplicates
  22868. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  22869. const group = groups[ o ];
  22870. const groupStart = group.start;
  22871. const groupCount = group.count;
  22872. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  22873. for ( let j = 0; j < 3; j ++ ) {
  22874. const index1 = indices.getX( i + j );
  22875. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  22876. start.fromBufferAttribute( position, index1 );
  22877. end.fromBufferAttribute( position, index2 );
  22878. if ( isUniqueEdge( start, end, edges ) === true ) {
  22879. vertices.push( start.x, start.y, start.z );
  22880. vertices.push( end.x, end.y, end.z );
  22881. }
  22882. }
  22883. }
  22884. }
  22885. } else {
  22886. // non-indexed BufferGeometry
  22887. const position = geometry.attributes.position;
  22888. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  22889. for ( let j = 0; j < 3; j ++ ) {
  22890. // three edges per triangle, an edge is represented as (index1, index2)
  22891. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  22892. const index1 = 3 * i + j;
  22893. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  22894. start.fromBufferAttribute( position, index1 );
  22895. end.fromBufferAttribute( position, index2 );
  22896. if ( isUniqueEdge( start, end, edges ) === true ) {
  22897. vertices.push( start.x, start.y, start.z );
  22898. vertices.push( end.x, end.y, end.z );
  22899. }
  22900. }
  22901. }
  22902. }
  22903. // build geometry
  22904. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22905. }
  22906. }
  22907. copy( source ) {
  22908. super.copy( source );
  22909. this.parameters = Object.assign( {}, source.parameters );
  22910. return this;
  22911. }
  22912. }
  22913. function isUniqueEdge( start, end, edges ) {
  22914. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  22915. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  22916. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  22917. return false;
  22918. } else {
  22919. edges.add( hash1 );
  22920. edges.add( hash2 );
  22921. return true;
  22922. }
  22923. }
  22924. var Geometries = /*#__PURE__*/Object.freeze({
  22925. __proto__: null,
  22926. BoxGeometry: BoxGeometry,
  22927. CapsuleGeometry: CapsuleGeometry,
  22928. CircleGeometry: CircleGeometry,
  22929. ConeGeometry: ConeGeometry,
  22930. CylinderGeometry: CylinderGeometry,
  22931. DodecahedronGeometry: DodecahedronGeometry,
  22932. EdgesGeometry: EdgesGeometry,
  22933. ExtrudeGeometry: ExtrudeGeometry,
  22934. IcosahedronGeometry: IcosahedronGeometry,
  22935. LatheGeometry: LatheGeometry,
  22936. OctahedronGeometry: OctahedronGeometry,
  22937. PlaneGeometry: PlaneGeometry,
  22938. PolyhedronGeometry: PolyhedronGeometry,
  22939. RingGeometry: RingGeometry,
  22940. ShapeGeometry: ShapeGeometry,
  22941. SphereGeometry: SphereGeometry,
  22942. TetrahedronGeometry: TetrahedronGeometry,
  22943. TorusGeometry: TorusGeometry,
  22944. TorusKnotGeometry: TorusKnotGeometry,
  22945. TubeGeometry: TubeGeometry,
  22946. WireframeGeometry: WireframeGeometry
  22947. });
  22948. class ShadowMaterial extends Material {
  22949. constructor( parameters ) {
  22950. super();
  22951. this.isShadowMaterial = true;
  22952. this.type = 'ShadowMaterial';
  22953. this.color = new Color( 0x000000 );
  22954. this.transparent = true;
  22955. this.fog = true;
  22956. this.setValues( parameters );
  22957. }
  22958. copy( source ) {
  22959. super.copy( source );
  22960. this.color.copy( source.color );
  22961. this.fog = source.fog;
  22962. return this;
  22963. }
  22964. }
  22965. class RawShaderMaterial extends ShaderMaterial {
  22966. constructor( parameters ) {
  22967. super( parameters );
  22968. this.isRawShaderMaterial = true;
  22969. this.type = 'RawShaderMaterial';
  22970. }
  22971. }
  22972. class MeshStandardMaterial extends Material {
  22973. constructor( parameters ) {
  22974. super();
  22975. this.isMeshStandardMaterial = true;
  22976. this.defines = { 'STANDARD': '' };
  22977. this.type = 'MeshStandardMaterial';
  22978. this.color = new Color( 0xffffff ); // diffuse
  22979. this.roughness = 1.0;
  22980. this.metalness = 0.0;
  22981. this.map = null;
  22982. this.lightMap = null;
  22983. this.lightMapIntensity = 1.0;
  22984. this.aoMap = null;
  22985. this.aoMapIntensity = 1.0;
  22986. this.emissive = new Color( 0x000000 );
  22987. this.emissiveIntensity = 1.0;
  22988. this.emissiveMap = null;
  22989. this.bumpMap = null;
  22990. this.bumpScale = 1;
  22991. this.normalMap = null;
  22992. this.normalMapType = TangentSpaceNormalMap;
  22993. this.normalScale = new Vector2( 1, 1 );
  22994. this.displacementMap = null;
  22995. this.displacementScale = 1;
  22996. this.displacementBias = 0;
  22997. this.roughnessMap = null;
  22998. this.metalnessMap = null;
  22999. this.alphaMap = null;
  23000. this.envMap = null;
  23001. this.envMapIntensity = 1.0;
  23002. this.wireframe = false;
  23003. this.wireframeLinewidth = 1;
  23004. this.wireframeLinecap = 'round';
  23005. this.wireframeLinejoin = 'round';
  23006. this.flatShading = false;
  23007. this.fog = true;
  23008. this.setValues( parameters );
  23009. }
  23010. copy( source ) {
  23011. super.copy( source );
  23012. this.defines = { 'STANDARD': '' };
  23013. this.color.copy( source.color );
  23014. this.roughness = source.roughness;
  23015. this.metalness = source.metalness;
  23016. this.map = source.map;
  23017. this.lightMap = source.lightMap;
  23018. this.lightMapIntensity = source.lightMapIntensity;
  23019. this.aoMap = source.aoMap;
  23020. this.aoMapIntensity = source.aoMapIntensity;
  23021. this.emissive.copy( source.emissive );
  23022. this.emissiveMap = source.emissiveMap;
  23023. this.emissiveIntensity = source.emissiveIntensity;
  23024. this.bumpMap = source.bumpMap;
  23025. this.bumpScale = source.bumpScale;
  23026. this.normalMap = source.normalMap;
  23027. this.normalMapType = source.normalMapType;
  23028. this.normalScale.copy( source.normalScale );
  23029. this.displacementMap = source.displacementMap;
  23030. this.displacementScale = source.displacementScale;
  23031. this.displacementBias = source.displacementBias;
  23032. this.roughnessMap = source.roughnessMap;
  23033. this.metalnessMap = source.metalnessMap;
  23034. this.alphaMap = source.alphaMap;
  23035. this.envMap = source.envMap;
  23036. this.envMapIntensity = source.envMapIntensity;
  23037. this.wireframe = source.wireframe;
  23038. this.wireframeLinewidth = source.wireframeLinewidth;
  23039. this.wireframeLinecap = source.wireframeLinecap;
  23040. this.wireframeLinejoin = source.wireframeLinejoin;
  23041. this.flatShading = source.flatShading;
  23042. this.fog = source.fog;
  23043. return this;
  23044. }
  23045. }
  23046. class MeshPhysicalMaterial extends MeshStandardMaterial {
  23047. constructor( parameters ) {
  23048. super();
  23049. this.isMeshPhysicalMaterial = true;
  23050. this.defines = {
  23051. 'STANDARD': '',
  23052. 'PHYSICAL': ''
  23053. };
  23054. this.type = 'MeshPhysicalMaterial';
  23055. this.anisotropyRotation = 0;
  23056. this.anisotropyMap = null;
  23057. this.clearcoatMap = null;
  23058. this.clearcoatRoughness = 0.0;
  23059. this.clearcoatRoughnessMap = null;
  23060. this.clearcoatNormalScale = new Vector2( 1, 1 );
  23061. this.clearcoatNormalMap = null;
  23062. this.ior = 1.5;
  23063. Object.defineProperty( this, 'reflectivity', {
  23064. get: function () {
  23065. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  23066. },
  23067. set: function ( reflectivity ) {
  23068. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  23069. }
  23070. } );
  23071. this.iridescenceMap = null;
  23072. this.iridescenceIOR = 1.3;
  23073. this.iridescenceThicknessRange = [ 100, 400 ];
  23074. this.iridescenceThicknessMap = null;
  23075. this.sheenColor = new Color( 0x000000 );
  23076. this.sheenColorMap = null;
  23077. this.sheenRoughness = 1.0;
  23078. this.sheenRoughnessMap = null;
  23079. this.transmissionMap = null;
  23080. this.thickness = 0;
  23081. this.thicknessMap = null;
  23082. this.attenuationDistance = Infinity;
  23083. this.attenuationColor = new Color( 1, 1, 1 );
  23084. this.specularIntensity = 1.0;
  23085. this.specularIntensityMap = null;
  23086. this.specularColor = new Color( 1, 1, 1 );
  23087. this.specularColorMap = null;
  23088. this._anisotropy = 0;
  23089. this._clearcoat = 0;
  23090. this._iridescence = 0;
  23091. this._sheen = 0.0;
  23092. this._transmission = 0;
  23093. this.setValues( parameters );
  23094. }
  23095. get anisotropy() {
  23096. return this._anisotropy;
  23097. }
  23098. set anisotropy( value ) {
  23099. if ( this._anisotropy > 0 !== value > 0 ) {
  23100. this.version ++;
  23101. }
  23102. this._anisotropy = value;
  23103. }
  23104. get clearcoat() {
  23105. return this._clearcoat;
  23106. }
  23107. set clearcoat( value ) {
  23108. if ( this._clearcoat > 0 !== value > 0 ) {
  23109. this.version ++;
  23110. }
  23111. this._clearcoat = value;
  23112. }
  23113. get iridescence() {
  23114. return this._iridescence;
  23115. }
  23116. set iridescence( value ) {
  23117. if ( this._iridescence > 0 !== value > 0 ) {
  23118. this.version ++;
  23119. }
  23120. this._iridescence = value;
  23121. }
  23122. get sheen() {
  23123. return this._sheen;
  23124. }
  23125. set sheen( value ) {
  23126. if ( this._sheen > 0 !== value > 0 ) {
  23127. this.version ++;
  23128. }
  23129. this._sheen = value;
  23130. }
  23131. get transmission() {
  23132. return this._transmission;
  23133. }
  23134. set transmission( value ) {
  23135. if ( this._transmission > 0 !== value > 0 ) {
  23136. this.version ++;
  23137. }
  23138. this._transmission = value;
  23139. }
  23140. copy( source ) {
  23141. super.copy( source );
  23142. this.defines = {
  23143. 'STANDARD': '',
  23144. 'PHYSICAL': ''
  23145. };
  23146. this.anisotropy = source.anisotropy;
  23147. this.anisotropyRotation = source.anisotropyRotation;
  23148. this.anisotropyMap = source.anisotropyMap;
  23149. this.clearcoat = source.clearcoat;
  23150. this.clearcoatMap = source.clearcoatMap;
  23151. this.clearcoatRoughness = source.clearcoatRoughness;
  23152. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  23153. this.clearcoatNormalMap = source.clearcoatNormalMap;
  23154. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  23155. this.ior = source.ior;
  23156. this.iridescence = source.iridescence;
  23157. this.iridescenceMap = source.iridescenceMap;
  23158. this.iridescenceIOR = source.iridescenceIOR;
  23159. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  23160. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  23161. this.sheen = source.sheen;
  23162. this.sheenColor.copy( source.sheenColor );
  23163. this.sheenColorMap = source.sheenColorMap;
  23164. this.sheenRoughness = source.sheenRoughness;
  23165. this.sheenRoughnessMap = source.sheenRoughnessMap;
  23166. this.transmission = source.transmission;
  23167. this.transmissionMap = source.transmissionMap;
  23168. this.thickness = source.thickness;
  23169. this.thicknessMap = source.thicknessMap;
  23170. this.attenuationDistance = source.attenuationDistance;
  23171. this.attenuationColor.copy( source.attenuationColor );
  23172. this.specularIntensity = source.specularIntensity;
  23173. this.specularIntensityMap = source.specularIntensityMap;
  23174. this.specularColor.copy( source.specularColor );
  23175. this.specularColorMap = source.specularColorMap;
  23176. return this;
  23177. }
  23178. }
  23179. class MeshPhongMaterial extends Material {
  23180. constructor( parameters ) {
  23181. super();
  23182. this.isMeshPhongMaterial = true;
  23183. this.type = 'MeshPhongMaterial';
  23184. this.color = new Color( 0xffffff ); // diffuse
  23185. this.specular = new Color( 0x111111 );
  23186. this.shininess = 30;
  23187. this.map = null;
  23188. this.lightMap = null;
  23189. this.lightMapIntensity = 1.0;
  23190. this.aoMap = null;
  23191. this.aoMapIntensity = 1.0;
  23192. this.emissive = new Color( 0x000000 );
  23193. this.emissiveIntensity = 1.0;
  23194. this.emissiveMap = null;
  23195. this.bumpMap = null;
  23196. this.bumpScale = 1;
  23197. this.normalMap = null;
  23198. this.normalMapType = TangentSpaceNormalMap;
  23199. this.normalScale = new Vector2( 1, 1 );
  23200. this.displacementMap = null;
  23201. this.displacementScale = 1;
  23202. this.displacementBias = 0;
  23203. this.specularMap = null;
  23204. this.alphaMap = null;
  23205. this.envMap = null;
  23206. this.combine = MultiplyOperation;
  23207. this.reflectivity = 1;
  23208. this.refractionRatio = 0.98;
  23209. this.wireframe = false;
  23210. this.wireframeLinewidth = 1;
  23211. this.wireframeLinecap = 'round';
  23212. this.wireframeLinejoin = 'round';
  23213. this.flatShading = false;
  23214. this.fog = true;
  23215. this.setValues( parameters );
  23216. }
  23217. copy( source ) {
  23218. super.copy( source );
  23219. this.color.copy( source.color );
  23220. this.specular.copy( source.specular );
  23221. this.shininess = source.shininess;
  23222. this.map = source.map;
  23223. this.lightMap = source.lightMap;
  23224. this.lightMapIntensity = source.lightMapIntensity;
  23225. this.aoMap = source.aoMap;
  23226. this.aoMapIntensity = source.aoMapIntensity;
  23227. this.emissive.copy( source.emissive );
  23228. this.emissiveMap = source.emissiveMap;
  23229. this.emissiveIntensity = source.emissiveIntensity;
  23230. this.bumpMap = source.bumpMap;
  23231. this.bumpScale = source.bumpScale;
  23232. this.normalMap = source.normalMap;
  23233. this.normalMapType = source.normalMapType;
  23234. this.normalScale.copy( source.normalScale );
  23235. this.displacementMap = source.displacementMap;
  23236. this.displacementScale = source.displacementScale;
  23237. this.displacementBias = source.displacementBias;
  23238. this.specularMap = source.specularMap;
  23239. this.alphaMap = source.alphaMap;
  23240. this.envMap = source.envMap;
  23241. this.combine = source.combine;
  23242. this.reflectivity = source.reflectivity;
  23243. this.refractionRatio = source.refractionRatio;
  23244. this.wireframe = source.wireframe;
  23245. this.wireframeLinewidth = source.wireframeLinewidth;
  23246. this.wireframeLinecap = source.wireframeLinecap;
  23247. this.wireframeLinejoin = source.wireframeLinejoin;
  23248. this.flatShading = source.flatShading;
  23249. this.fog = source.fog;
  23250. return this;
  23251. }
  23252. }
  23253. class MeshToonMaterial extends Material {
  23254. constructor( parameters ) {
  23255. super();
  23256. this.isMeshToonMaterial = true;
  23257. this.defines = { 'TOON': '' };
  23258. this.type = 'MeshToonMaterial';
  23259. this.color = new Color( 0xffffff );
  23260. this.map = null;
  23261. this.gradientMap = null;
  23262. this.lightMap = null;
  23263. this.lightMapIntensity = 1.0;
  23264. this.aoMap = null;
  23265. this.aoMapIntensity = 1.0;
  23266. this.emissive = new Color( 0x000000 );
  23267. this.emissiveIntensity = 1.0;
  23268. this.emissiveMap = null;
  23269. this.bumpMap = null;
  23270. this.bumpScale = 1;
  23271. this.normalMap = null;
  23272. this.normalMapType = TangentSpaceNormalMap;
  23273. this.normalScale = new Vector2( 1, 1 );
  23274. this.displacementMap = null;
  23275. this.displacementScale = 1;
  23276. this.displacementBias = 0;
  23277. this.alphaMap = null;
  23278. this.wireframe = false;
  23279. this.wireframeLinewidth = 1;
  23280. this.wireframeLinecap = 'round';
  23281. this.wireframeLinejoin = 'round';
  23282. this.fog = true;
  23283. this.setValues( parameters );
  23284. }
  23285. copy( source ) {
  23286. super.copy( source );
  23287. this.color.copy( source.color );
  23288. this.map = source.map;
  23289. this.gradientMap = source.gradientMap;
  23290. this.lightMap = source.lightMap;
  23291. this.lightMapIntensity = source.lightMapIntensity;
  23292. this.aoMap = source.aoMap;
  23293. this.aoMapIntensity = source.aoMapIntensity;
  23294. this.emissive.copy( source.emissive );
  23295. this.emissiveMap = source.emissiveMap;
  23296. this.emissiveIntensity = source.emissiveIntensity;
  23297. this.bumpMap = source.bumpMap;
  23298. this.bumpScale = source.bumpScale;
  23299. this.normalMap = source.normalMap;
  23300. this.normalMapType = source.normalMapType;
  23301. this.normalScale.copy( source.normalScale );
  23302. this.displacementMap = source.displacementMap;
  23303. this.displacementScale = source.displacementScale;
  23304. this.displacementBias = source.displacementBias;
  23305. this.alphaMap = source.alphaMap;
  23306. this.wireframe = source.wireframe;
  23307. this.wireframeLinewidth = source.wireframeLinewidth;
  23308. this.wireframeLinecap = source.wireframeLinecap;
  23309. this.wireframeLinejoin = source.wireframeLinejoin;
  23310. this.fog = source.fog;
  23311. return this;
  23312. }
  23313. }
  23314. class MeshNormalMaterial extends Material {
  23315. constructor( parameters ) {
  23316. super();
  23317. this.isMeshNormalMaterial = true;
  23318. this.type = 'MeshNormalMaterial';
  23319. this.bumpMap = null;
  23320. this.bumpScale = 1;
  23321. this.normalMap = null;
  23322. this.normalMapType = TangentSpaceNormalMap;
  23323. this.normalScale = new Vector2( 1, 1 );
  23324. this.displacementMap = null;
  23325. this.displacementScale = 1;
  23326. this.displacementBias = 0;
  23327. this.wireframe = false;
  23328. this.wireframeLinewidth = 1;
  23329. this.flatShading = false;
  23330. this.setValues( parameters );
  23331. }
  23332. copy( source ) {
  23333. super.copy( source );
  23334. this.bumpMap = source.bumpMap;
  23335. this.bumpScale = source.bumpScale;
  23336. this.normalMap = source.normalMap;
  23337. this.normalMapType = source.normalMapType;
  23338. this.normalScale.copy( source.normalScale );
  23339. this.displacementMap = source.displacementMap;
  23340. this.displacementScale = source.displacementScale;
  23341. this.displacementBias = source.displacementBias;
  23342. this.wireframe = source.wireframe;
  23343. this.wireframeLinewidth = source.wireframeLinewidth;
  23344. this.flatShading = source.flatShading;
  23345. return this;
  23346. }
  23347. }
  23348. class MeshLambertMaterial extends Material {
  23349. constructor( parameters ) {
  23350. super();
  23351. this.isMeshLambertMaterial = true;
  23352. this.type = 'MeshLambertMaterial';
  23353. this.color = new Color( 0xffffff ); // diffuse
  23354. this.map = null;
  23355. this.lightMap = null;
  23356. this.lightMapIntensity = 1.0;
  23357. this.aoMap = null;
  23358. this.aoMapIntensity = 1.0;
  23359. this.emissive = new Color( 0x000000 );
  23360. this.emissiveIntensity = 1.0;
  23361. this.emissiveMap = null;
  23362. this.bumpMap = null;
  23363. this.bumpScale = 1;
  23364. this.normalMap = null;
  23365. this.normalMapType = TangentSpaceNormalMap;
  23366. this.normalScale = new Vector2( 1, 1 );
  23367. this.displacementMap = null;
  23368. this.displacementScale = 1;
  23369. this.displacementBias = 0;
  23370. this.specularMap = null;
  23371. this.alphaMap = null;
  23372. this.envMap = null;
  23373. this.combine = MultiplyOperation;
  23374. this.reflectivity = 1;
  23375. this.refractionRatio = 0.98;
  23376. this.wireframe = false;
  23377. this.wireframeLinewidth = 1;
  23378. this.wireframeLinecap = 'round';
  23379. this.wireframeLinejoin = 'round';
  23380. this.flatShading = false;
  23381. this.fog = true;
  23382. this.setValues( parameters );
  23383. }
  23384. copy( source ) {
  23385. super.copy( source );
  23386. this.color.copy( source.color );
  23387. this.map = source.map;
  23388. this.lightMap = source.lightMap;
  23389. this.lightMapIntensity = source.lightMapIntensity;
  23390. this.aoMap = source.aoMap;
  23391. this.aoMapIntensity = source.aoMapIntensity;
  23392. this.emissive.copy( source.emissive );
  23393. this.emissiveMap = source.emissiveMap;
  23394. this.emissiveIntensity = source.emissiveIntensity;
  23395. this.bumpMap = source.bumpMap;
  23396. this.bumpScale = source.bumpScale;
  23397. this.normalMap = source.normalMap;
  23398. this.normalMapType = source.normalMapType;
  23399. this.normalScale.copy( source.normalScale );
  23400. this.displacementMap = source.displacementMap;
  23401. this.displacementScale = source.displacementScale;
  23402. this.displacementBias = source.displacementBias;
  23403. this.specularMap = source.specularMap;
  23404. this.alphaMap = source.alphaMap;
  23405. this.envMap = source.envMap;
  23406. this.combine = source.combine;
  23407. this.reflectivity = source.reflectivity;
  23408. this.refractionRatio = source.refractionRatio;
  23409. this.wireframe = source.wireframe;
  23410. this.wireframeLinewidth = source.wireframeLinewidth;
  23411. this.wireframeLinecap = source.wireframeLinecap;
  23412. this.wireframeLinejoin = source.wireframeLinejoin;
  23413. this.flatShading = source.flatShading;
  23414. this.fog = source.fog;
  23415. return this;
  23416. }
  23417. }
  23418. class MeshMatcapMaterial extends Material {
  23419. constructor( parameters ) {
  23420. super();
  23421. this.isMeshMatcapMaterial = true;
  23422. this.defines = { 'MATCAP': '' };
  23423. this.type = 'MeshMatcapMaterial';
  23424. this.color = new Color( 0xffffff ); // diffuse
  23425. this.matcap = null;
  23426. this.map = null;
  23427. this.bumpMap = null;
  23428. this.bumpScale = 1;
  23429. this.normalMap = null;
  23430. this.normalMapType = TangentSpaceNormalMap;
  23431. this.normalScale = new Vector2( 1, 1 );
  23432. this.displacementMap = null;
  23433. this.displacementScale = 1;
  23434. this.displacementBias = 0;
  23435. this.alphaMap = null;
  23436. this.flatShading = false;
  23437. this.fog = true;
  23438. this.setValues( parameters );
  23439. }
  23440. copy( source ) {
  23441. super.copy( source );
  23442. this.defines = { 'MATCAP': '' };
  23443. this.color.copy( source.color );
  23444. this.matcap = source.matcap;
  23445. this.map = source.map;
  23446. this.bumpMap = source.bumpMap;
  23447. this.bumpScale = source.bumpScale;
  23448. this.normalMap = source.normalMap;
  23449. this.normalMapType = source.normalMapType;
  23450. this.normalScale.copy( source.normalScale );
  23451. this.displacementMap = source.displacementMap;
  23452. this.displacementScale = source.displacementScale;
  23453. this.displacementBias = source.displacementBias;
  23454. this.alphaMap = source.alphaMap;
  23455. this.flatShading = source.flatShading;
  23456. this.fog = source.fog;
  23457. return this;
  23458. }
  23459. }
  23460. class LineDashedMaterial extends LineBasicMaterial {
  23461. constructor( parameters ) {
  23462. super();
  23463. this.isLineDashedMaterial = true;
  23464. this.type = 'LineDashedMaterial';
  23465. this.scale = 1;
  23466. this.dashSize = 3;
  23467. this.gapSize = 1;
  23468. this.setValues( parameters );
  23469. }
  23470. copy( source ) {
  23471. super.copy( source );
  23472. this.scale = source.scale;
  23473. this.dashSize = source.dashSize;
  23474. this.gapSize = source.gapSize;
  23475. return this;
  23476. }
  23477. }
  23478. // same as Array.prototype.slice, but also works on typed arrays
  23479. function arraySlice( array, from, to ) {
  23480. if ( isTypedArray( array ) ) {
  23481. // in ios9 array.subarray(from, undefined) will return empty array
  23482. // but array.subarray(from) or array.subarray(from, len) is correct
  23483. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  23484. }
  23485. return array.slice( from, to );
  23486. }
  23487. // converts an array to a specific type
  23488. function convertArray( array, type, forceClone ) {
  23489. if ( ! array || // let 'undefined' and 'null' pass
  23490. ! forceClone && array.constructor === type ) return array;
  23491. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  23492. return new type( array ); // create typed array
  23493. }
  23494. return Array.prototype.slice.call( array ); // create Array
  23495. }
  23496. function isTypedArray( object ) {
  23497. return ArrayBuffer.isView( object ) &&
  23498. ! ( object instanceof DataView );
  23499. }
  23500. // returns an array by which times and values can be sorted
  23501. function getKeyframeOrder( times ) {
  23502. function compareTime( i, j ) {
  23503. return times[ i ] - times[ j ];
  23504. }
  23505. const n = times.length;
  23506. const result = new Array( n );
  23507. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  23508. result.sort( compareTime );
  23509. return result;
  23510. }
  23511. // uses the array previously returned by 'getKeyframeOrder' to sort data
  23512. function sortedArray( values, stride, order ) {
  23513. const nValues = values.length;
  23514. const result = new values.constructor( nValues );
  23515. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  23516. const srcOffset = order[ i ] * stride;
  23517. for ( let j = 0; j !== stride; ++ j ) {
  23518. result[ dstOffset ++ ] = values[ srcOffset + j ];
  23519. }
  23520. }
  23521. return result;
  23522. }
  23523. // function for parsing AOS keyframe formats
  23524. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  23525. let i = 1, key = jsonKeys[ 0 ];
  23526. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  23527. key = jsonKeys[ i ++ ];
  23528. }
  23529. if ( key === undefined ) return; // no data
  23530. let value = key[ valuePropertyName ];
  23531. if ( value === undefined ) return; // no data
  23532. if ( Array.isArray( value ) ) {
  23533. do {
  23534. value = key[ valuePropertyName ];
  23535. if ( value !== undefined ) {
  23536. times.push( key.time );
  23537. values.push.apply( values, value ); // push all elements
  23538. }
  23539. key = jsonKeys[ i ++ ];
  23540. } while ( key !== undefined );
  23541. } else if ( value.toArray !== undefined ) {
  23542. // ...assume THREE.Math-ish
  23543. do {
  23544. value = key[ valuePropertyName ];
  23545. if ( value !== undefined ) {
  23546. times.push( key.time );
  23547. value.toArray( values, values.length );
  23548. }
  23549. key = jsonKeys[ i ++ ];
  23550. } while ( key !== undefined );
  23551. } else {
  23552. // otherwise push as-is
  23553. do {
  23554. value = key[ valuePropertyName ];
  23555. if ( value !== undefined ) {
  23556. times.push( key.time );
  23557. values.push( value );
  23558. }
  23559. key = jsonKeys[ i ++ ];
  23560. } while ( key !== undefined );
  23561. }
  23562. }
  23563. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  23564. const clip = sourceClip.clone();
  23565. clip.name = name;
  23566. const tracks = [];
  23567. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23568. const track = clip.tracks[ i ];
  23569. const valueSize = track.getValueSize();
  23570. const times = [];
  23571. const values = [];
  23572. for ( let j = 0; j < track.times.length; ++ j ) {
  23573. const frame = track.times[ j ] * fps;
  23574. if ( frame < startFrame || frame >= endFrame ) continue;
  23575. times.push( track.times[ j ] );
  23576. for ( let k = 0; k < valueSize; ++ k ) {
  23577. values.push( track.values[ j * valueSize + k ] );
  23578. }
  23579. }
  23580. if ( times.length === 0 ) continue;
  23581. track.times = convertArray( times, track.times.constructor );
  23582. track.values = convertArray( values, track.values.constructor );
  23583. tracks.push( track );
  23584. }
  23585. clip.tracks = tracks;
  23586. // find minimum .times value across all tracks in the trimmed clip
  23587. let minStartTime = Infinity;
  23588. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23589. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  23590. minStartTime = clip.tracks[ i ].times[ 0 ];
  23591. }
  23592. }
  23593. // shift all tracks such that clip begins at t=0
  23594. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23595. clip.tracks[ i ].shift( - 1 * minStartTime );
  23596. }
  23597. clip.resetDuration();
  23598. return clip;
  23599. }
  23600. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  23601. if ( fps <= 0 ) fps = 30;
  23602. const numTracks = referenceClip.tracks.length;
  23603. const referenceTime = referenceFrame / fps;
  23604. // Make each track's values relative to the values at the reference frame
  23605. for ( let i = 0; i < numTracks; ++ i ) {
  23606. const referenceTrack = referenceClip.tracks[ i ];
  23607. const referenceTrackType = referenceTrack.ValueTypeName;
  23608. // Skip this track if it's non-numeric
  23609. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  23610. // Find the track in the target clip whose name and type matches the reference track
  23611. const targetTrack = targetClip.tracks.find( function ( track ) {
  23612. return track.name === referenceTrack.name
  23613. && track.ValueTypeName === referenceTrackType;
  23614. } );
  23615. if ( targetTrack === undefined ) continue;
  23616. let referenceOffset = 0;
  23617. const referenceValueSize = referenceTrack.getValueSize();
  23618. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  23619. referenceOffset = referenceValueSize / 3;
  23620. }
  23621. let targetOffset = 0;
  23622. const targetValueSize = targetTrack.getValueSize();
  23623. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  23624. targetOffset = targetValueSize / 3;
  23625. }
  23626. const lastIndex = referenceTrack.times.length - 1;
  23627. let referenceValue;
  23628. // Find the value to subtract out of the track
  23629. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  23630. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  23631. const startIndex = referenceOffset;
  23632. const endIndex = referenceValueSize - referenceOffset;
  23633. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  23634. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  23635. // Reference frame is after the last keyframe, so just use the last keyframe
  23636. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  23637. const endIndex = startIndex + referenceValueSize - referenceOffset;
  23638. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  23639. } else {
  23640. // Interpolate to the reference value
  23641. const interpolant = referenceTrack.createInterpolant();
  23642. const startIndex = referenceOffset;
  23643. const endIndex = referenceValueSize - referenceOffset;
  23644. interpolant.evaluate( referenceTime );
  23645. referenceValue = arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  23646. }
  23647. // Conjugate the quaternion
  23648. if ( referenceTrackType === 'quaternion' ) {
  23649. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  23650. referenceQuat.toArray( referenceValue );
  23651. }
  23652. // Subtract the reference value from all of the track values
  23653. const numTimes = targetTrack.times.length;
  23654. for ( let j = 0; j < numTimes; ++ j ) {
  23655. const valueStart = j * targetValueSize + targetOffset;
  23656. if ( referenceTrackType === 'quaternion' ) {
  23657. // Multiply the conjugate for quaternion track types
  23658. Quaternion.multiplyQuaternionsFlat(
  23659. targetTrack.values,
  23660. valueStart,
  23661. referenceValue,
  23662. 0,
  23663. targetTrack.values,
  23664. valueStart
  23665. );
  23666. } else {
  23667. const valueEnd = targetValueSize - targetOffset * 2;
  23668. // Subtract each value for all other numeric track types
  23669. for ( let k = 0; k < valueEnd; ++ k ) {
  23670. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  23671. }
  23672. }
  23673. }
  23674. }
  23675. targetClip.blendMode = AdditiveAnimationBlendMode;
  23676. return targetClip;
  23677. }
  23678. const AnimationUtils = {
  23679. arraySlice: arraySlice,
  23680. convertArray: convertArray,
  23681. isTypedArray: isTypedArray,
  23682. getKeyframeOrder: getKeyframeOrder,
  23683. sortedArray: sortedArray,
  23684. flattenJSON: flattenJSON,
  23685. subclip: subclip,
  23686. makeClipAdditive: makeClipAdditive
  23687. };
  23688. /**
  23689. * Abstract base class of interpolants over parametric samples.
  23690. *
  23691. * The parameter domain is one dimensional, typically the time or a path
  23692. * along a curve defined by the data.
  23693. *
  23694. * The sample values can have any dimensionality and derived classes may
  23695. * apply special interpretations to the data.
  23696. *
  23697. * This class provides the interval seek in a Template Method, deferring
  23698. * the actual interpolation to derived classes.
  23699. *
  23700. * Time complexity is O(1) for linear access crossing at most two points
  23701. * and O(log N) for random access, where N is the number of positions.
  23702. *
  23703. * References:
  23704. *
  23705. * http://www.oodesign.com/template-method-pattern.html
  23706. *
  23707. */
  23708. class Interpolant {
  23709. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23710. this.parameterPositions = parameterPositions;
  23711. this._cachedIndex = 0;
  23712. this.resultBuffer = resultBuffer !== undefined ?
  23713. resultBuffer : new sampleValues.constructor( sampleSize );
  23714. this.sampleValues = sampleValues;
  23715. this.valueSize = sampleSize;
  23716. this.settings = null;
  23717. this.DefaultSettings_ = {};
  23718. }
  23719. evaluate( t ) {
  23720. const pp = this.parameterPositions;
  23721. let i1 = this._cachedIndex,
  23722. t1 = pp[ i1 ],
  23723. t0 = pp[ i1 - 1 ];
  23724. validate_interval: {
  23725. seek: {
  23726. let right;
  23727. linear_scan: {
  23728. //- See http://jsperf.com/comparison-to-undefined/3
  23729. //- slower code:
  23730. //-
  23731. //- if ( t >= t1 || t1 === undefined ) {
  23732. forward_scan: if ( ! ( t < t1 ) ) {
  23733. for ( let giveUpAt = i1 + 2; ; ) {
  23734. if ( t1 === undefined ) {
  23735. if ( t < t0 ) break forward_scan;
  23736. // after end
  23737. i1 = pp.length;
  23738. this._cachedIndex = i1;
  23739. return this.copySampleValue_( i1 - 1 );
  23740. }
  23741. if ( i1 === giveUpAt ) break; // this loop
  23742. t0 = t1;
  23743. t1 = pp[ ++ i1 ];
  23744. if ( t < t1 ) {
  23745. // we have arrived at the sought interval
  23746. break seek;
  23747. }
  23748. }
  23749. // prepare binary search on the right side of the index
  23750. right = pp.length;
  23751. break linear_scan;
  23752. }
  23753. //- slower code:
  23754. //- if ( t < t0 || t0 === undefined ) {
  23755. if ( ! ( t >= t0 ) ) {
  23756. // looping?
  23757. const t1global = pp[ 1 ];
  23758. if ( t < t1global ) {
  23759. i1 = 2; // + 1, using the scan for the details
  23760. t0 = t1global;
  23761. }
  23762. // linear reverse scan
  23763. for ( let giveUpAt = i1 - 2; ; ) {
  23764. if ( t0 === undefined ) {
  23765. // before start
  23766. this._cachedIndex = 0;
  23767. return this.copySampleValue_( 0 );
  23768. }
  23769. if ( i1 === giveUpAt ) break; // this loop
  23770. t1 = t0;
  23771. t0 = pp[ -- i1 - 1 ];
  23772. if ( t >= t0 ) {
  23773. // we have arrived at the sought interval
  23774. break seek;
  23775. }
  23776. }
  23777. // prepare binary search on the left side of the index
  23778. right = i1;
  23779. i1 = 0;
  23780. break linear_scan;
  23781. }
  23782. // the interval is valid
  23783. break validate_interval;
  23784. } // linear scan
  23785. // binary search
  23786. while ( i1 < right ) {
  23787. const mid = ( i1 + right ) >>> 1;
  23788. if ( t < pp[ mid ] ) {
  23789. right = mid;
  23790. } else {
  23791. i1 = mid + 1;
  23792. }
  23793. }
  23794. t1 = pp[ i1 ];
  23795. t0 = pp[ i1 - 1 ];
  23796. // check boundary cases, again
  23797. if ( t0 === undefined ) {
  23798. this._cachedIndex = 0;
  23799. return this.copySampleValue_( 0 );
  23800. }
  23801. if ( t1 === undefined ) {
  23802. i1 = pp.length;
  23803. this._cachedIndex = i1;
  23804. return this.copySampleValue_( i1 - 1 );
  23805. }
  23806. } // seek
  23807. this._cachedIndex = i1;
  23808. this.intervalChanged_( i1, t0, t1 );
  23809. } // validate_interval
  23810. return this.interpolate_( i1, t0, t, t1 );
  23811. }
  23812. getSettings_() {
  23813. return this.settings || this.DefaultSettings_;
  23814. }
  23815. copySampleValue_( index ) {
  23816. // copies a sample value to the result buffer
  23817. const result = this.resultBuffer,
  23818. values = this.sampleValues,
  23819. stride = this.valueSize,
  23820. offset = index * stride;
  23821. for ( let i = 0; i !== stride; ++ i ) {
  23822. result[ i ] = values[ offset + i ];
  23823. }
  23824. return result;
  23825. }
  23826. // Template methods for derived classes:
  23827. interpolate_( /* i1, t0, t, t1 */ ) {
  23828. throw new Error( 'call to abstract method' );
  23829. // implementations shall return this.resultBuffer
  23830. }
  23831. intervalChanged_( /* i1, t0, t1 */ ) {
  23832. // empty
  23833. }
  23834. }
  23835. /**
  23836. * Fast and simple cubic spline interpolant.
  23837. *
  23838. * It was derived from a Hermitian construction setting the first derivative
  23839. * at each sample position to the linear slope between neighboring positions
  23840. * over their parameter interval.
  23841. */
  23842. class CubicInterpolant extends Interpolant {
  23843. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23844. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23845. this._weightPrev = - 0;
  23846. this._offsetPrev = - 0;
  23847. this._weightNext = - 0;
  23848. this._offsetNext = - 0;
  23849. this.DefaultSettings_ = {
  23850. endingStart: ZeroCurvatureEnding,
  23851. endingEnd: ZeroCurvatureEnding
  23852. };
  23853. }
  23854. intervalChanged_( i1, t0, t1 ) {
  23855. const pp = this.parameterPositions;
  23856. let iPrev = i1 - 2,
  23857. iNext = i1 + 1,
  23858. tPrev = pp[ iPrev ],
  23859. tNext = pp[ iNext ];
  23860. if ( tPrev === undefined ) {
  23861. switch ( this.getSettings_().endingStart ) {
  23862. case ZeroSlopeEnding:
  23863. // f'(t0) = 0
  23864. iPrev = i1;
  23865. tPrev = 2 * t0 - t1;
  23866. break;
  23867. case WrapAroundEnding:
  23868. // use the other end of the curve
  23869. iPrev = pp.length - 2;
  23870. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  23871. break;
  23872. default: // ZeroCurvatureEnding
  23873. // f''(t0) = 0 a.k.a. Natural Spline
  23874. iPrev = i1;
  23875. tPrev = t1;
  23876. }
  23877. }
  23878. if ( tNext === undefined ) {
  23879. switch ( this.getSettings_().endingEnd ) {
  23880. case ZeroSlopeEnding:
  23881. // f'(tN) = 0
  23882. iNext = i1;
  23883. tNext = 2 * t1 - t0;
  23884. break;
  23885. case WrapAroundEnding:
  23886. // use the other end of the curve
  23887. iNext = 1;
  23888. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  23889. break;
  23890. default: // ZeroCurvatureEnding
  23891. // f''(tN) = 0, a.k.a. Natural Spline
  23892. iNext = i1 - 1;
  23893. tNext = t0;
  23894. }
  23895. }
  23896. const halfDt = ( t1 - t0 ) * 0.5,
  23897. stride = this.valueSize;
  23898. this._weightPrev = halfDt / ( t0 - tPrev );
  23899. this._weightNext = halfDt / ( tNext - t1 );
  23900. this._offsetPrev = iPrev * stride;
  23901. this._offsetNext = iNext * stride;
  23902. }
  23903. interpolate_( i1, t0, t, t1 ) {
  23904. const result = this.resultBuffer,
  23905. values = this.sampleValues,
  23906. stride = this.valueSize,
  23907. o1 = i1 * stride, o0 = o1 - stride,
  23908. oP = this._offsetPrev, oN = this._offsetNext,
  23909. wP = this._weightPrev, wN = this._weightNext,
  23910. p = ( t - t0 ) / ( t1 - t0 ),
  23911. pp = p * p,
  23912. ppp = pp * p;
  23913. // evaluate polynomials
  23914. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  23915. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  23916. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  23917. const sN = wN * ppp - wN * pp;
  23918. // combine data linearly
  23919. for ( let i = 0; i !== stride; ++ i ) {
  23920. result[ i ] =
  23921. sP * values[ oP + i ] +
  23922. s0 * values[ o0 + i ] +
  23923. s1 * values[ o1 + i ] +
  23924. sN * values[ oN + i ];
  23925. }
  23926. return result;
  23927. }
  23928. }
  23929. class LinearInterpolant extends Interpolant {
  23930. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23931. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23932. }
  23933. interpolate_( i1, t0, t, t1 ) {
  23934. const result = this.resultBuffer,
  23935. values = this.sampleValues,
  23936. stride = this.valueSize,
  23937. offset1 = i1 * stride,
  23938. offset0 = offset1 - stride,
  23939. weight1 = ( t - t0 ) / ( t1 - t0 ),
  23940. weight0 = 1 - weight1;
  23941. for ( let i = 0; i !== stride; ++ i ) {
  23942. result[ i ] =
  23943. values[ offset0 + i ] * weight0 +
  23944. values[ offset1 + i ] * weight1;
  23945. }
  23946. return result;
  23947. }
  23948. }
  23949. /**
  23950. *
  23951. * Interpolant that evaluates to the sample value at the position preceding
  23952. * the parameter.
  23953. */
  23954. class DiscreteInterpolant extends Interpolant {
  23955. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23956. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23957. }
  23958. interpolate_( i1 /*, t0, t, t1 */ ) {
  23959. return this.copySampleValue_( i1 - 1 );
  23960. }
  23961. }
  23962. class KeyframeTrack {
  23963. constructor( name, times, values, interpolation ) {
  23964. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  23965. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  23966. this.name = name;
  23967. this.times = convertArray( times, this.TimeBufferType );
  23968. this.values = convertArray( values, this.ValueBufferType );
  23969. this.setInterpolation( interpolation || this.DefaultInterpolation );
  23970. }
  23971. // Serialization (in static context, because of constructor invocation
  23972. // and automatic invocation of .toJSON):
  23973. static toJSON( track ) {
  23974. const trackType = track.constructor;
  23975. let json;
  23976. // derived classes can define a static toJSON method
  23977. if ( trackType.toJSON !== this.toJSON ) {
  23978. json = trackType.toJSON( track );
  23979. } else {
  23980. // by default, we assume the data can be serialized as-is
  23981. json = {
  23982. 'name': track.name,
  23983. 'times': convertArray( track.times, Array ),
  23984. 'values': convertArray( track.values, Array )
  23985. };
  23986. const interpolation = track.getInterpolation();
  23987. if ( interpolation !== track.DefaultInterpolation ) {
  23988. json.interpolation = interpolation;
  23989. }
  23990. }
  23991. json.type = track.ValueTypeName; // mandatory
  23992. return json;
  23993. }
  23994. InterpolantFactoryMethodDiscrete( result ) {
  23995. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  23996. }
  23997. InterpolantFactoryMethodLinear( result ) {
  23998. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23999. }
  24000. InterpolantFactoryMethodSmooth( result ) {
  24001. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  24002. }
  24003. setInterpolation( interpolation ) {
  24004. let factoryMethod;
  24005. switch ( interpolation ) {
  24006. case InterpolateDiscrete:
  24007. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  24008. break;
  24009. case InterpolateLinear:
  24010. factoryMethod = this.InterpolantFactoryMethodLinear;
  24011. break;
  24012. case InterpolateSmooth:
  24013. factoryMethod = this.InterpolantFactoryMethodSmooth;
  24014. break;
  24015. }
  24016. if ( factoryMethod === undefined ) {
  24017. const message = 'unsupported interpolation for ' +
  24018. this.ValueTypeName + ' keyframe track named ' + this.name;
  24019. if ( this.createInterpolant === undefined ) {
  24020. // fall back to default, unless the default itself is messed up
  24021. if ( interpolation !== this.DefaultInterpolation ) {
  24022. this.setInterpolation( this.DefaultInterpolation );
  24023. } else {
  24024. throw new Error( message ); // fatal, in this case
  24025. }
  24026. }
  24027. console.warn( 'THREE.KeyframeTrack:', message );
  24028. return this;
  24029. }
  24030. this.createInterpolant = factoryMethod;
  24031. return this;
  24032. }
  24033. getInterpolation() {
  24034. switch ( this.createInterpolant ) {
  24035. case this.InterpolantFactoryMethodDiscrete:
  24036. return InterpolateDiscrete;
  24037. case this.InterpolantFactoryMethodLinear:
  24038. return InterpolateLinear;
  24039. case this.InterpolantFactoryMethodSmooth:
  24040. return InterpolateSmooth;
  24041. }
  24042. }
  24043. getValueSize() {
  24044. return this.values.length / this.times.length;
  24045. }
  24046. // move all keyframes either forwards or backwards in time
  24047. shift( timeOffset ) {
  24048. if ( timeOffset !== 0.0 ) {
  24049. const times = this.times;
  24050. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  24051. times[ i ] += timeOffset;
  24052. }
  24053. }
  24054. return this;
  24055. }
  24056. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  24057. scale( timeScale ) {
  24058. if ( timeScale !== 1.0 ) {
  24059. const times = this.times;
  24060. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  24061. times[ i ] *= timeScale;
  24062. }
  24063. }
  24064. return this;
  24065. }
  24066. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  24067. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  24068. trim( startTime, endTime ) {
  24069. const times = this.times,
  24070. nKeys = times.length;
  24071. let from = 0,
  24072. to = nKeys - 1;
  24073. while ( from !== nKeys && times[ from ] < startTime ) {
  24074. ++ from;
  24075. }
  24076. while ( to !== - 1 && times[ to ] > endTime ) {
  24077. -- to;
  24078. }
  24079. ++ to; // inclusive -> exclusive bound
  24080. if ( from !== 0 || to !== nKeys ) {
  24081. // empty tracks are forbidden, so keep at least one keyframe
  24082. if ( from >= to ) {
  24083. to = Math.max( to, 1 );
  24084. from = to - 1;
  24085. }
  24086. const stride = this.getValueSize();
  24087. this.times = arraySlice( times, from, to );
  24088. this.values = arraySlice( this.values, from * stride, to * stride );
  24089. }
  24090. return this;
  24091. }
  24092. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  24093. validate() {
  24094. let valid = true;
  24095. const valueSize = this.getValueSize();
  24096. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  24097. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  24098. valid = false;
  24099. }
  24100. const times = this.times,
  24101. values = this.values,
  24102. nKeys = times.length;
  24103. if ( nKeys === 0 ) {
  24104. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  24105. valid = false;
  24106. }
  24107. let prevTime = null;
  24108. for ( let i = 0; i !== nKeys; i ++ ) {
  24109. const currTime = times[ i ];
  24110. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  24111. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  24112. valid = false;
  24113. break;
  24114. }
  24115. if ( prevTime !== null && prevTime > currTime ) {
  24116. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  24117. valid = false;
  24118. break;
  24119. }
  24120. prevTime = currTime;
  24121. }
  24122. if ( values !== undefined ) {
  24123. if ( isTypedArray( values ) ) {
  24124. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  24125. const value = values[ i ];
  24126. if ( isNaN( value ) ) {
  24127. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  24128. valid = false;
  24129. break;
  24130. }
  24131. }
  24132. }
  24133. }
  24134. return valid;
  24135. }
  24136. // removes equivalent sequential keys as common in morph target sequences
  24137. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  24138. optimize() {
  24139. // times or values may be shared with other tracks, so overwriting is unsafe
  24140. const times = arraySlice( this.times ),
  24141. values = arraySlice( this.values ),
  24142. stride = this.getValueSize(),
  24143. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  24144. lastIndex = times.length - 1;
  24145. let writeIndex = 1;
  24146. for ( let i = 1; i < lastIndex; ++ i ) {
  24147. let keep = false;
  24148. const time = times[ i ];
  24149. const timeNext = times[ i + 1 ];
  24150. // remove adjacent keyframes scheduled at the same time
  24151. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  24152. if ( ! smoothInterpolation ) {
  24153. // remove unnecessary keyframes same as their neighbors
  24154. const offset = i * stride,
  24155. offsetP = offset - stride,
  24156. offsetN = offset + stride;
  24157. for ( let j = 0; j !== stride; ++ j ) {
  24158. const value = values[ offset + j ];
  24159. if ( value !== values[ offsetP + j ] ||
  24160. value !== values[ offsetN + j ] ) {
  24161. keep = true;
  24162. break;
  24163. }
  24164. }
  24165. } else {
  24166. keep = true;
  24167. }
  24168. }
  24169. // in-place compaction
  24170. if ( keep ) {
  24171. if ( i !== writeIndex ) {
  24172. times[ writeIndex ] = times[ i ];
  24173. const readOffset = i * stride,
  24174. writeOffset = writeIndex * stride;
  24175. for ( let j = 0; j !== stride; ++ j ) {
  24176. values[ writeOffset + j ] = values[ readOffset + j ];
  24177. }
  24178. }
  24179. ++ writeIndex;
  24180. }
  24181. }
  24182. // flush last keyframe (compaction looks ahead)
  24183. if ( lastIndex > 0 ) {
  24184. times[ writeIndex ] = times[ lastIndex ];
  24185. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  24186. values[ writeOffset + j ] = values[ readOffset + j ];
  24187. }
  24188. ++ writeIndex;
  24189. }
  24190. if ( writeIndex !== times.length ) {
  24191. this.times = arraySlice( times, 0, writeIndex );
  24192. this.values = arraySlice( values, 0, writeIndex * stride );
  24193. } else {
  24194. this.times = times;
  24195. this.values = values;
  24196. }
  24197. return this;
  24198. }
  24199. clone() {
  24200. const times = arraySlice( this.times, 0 );
  24201. const values = arraySlice( this.values, 0 );
  24202. const TypedKeyframeTrack = this.constructor;
  24203. const track = new TypedKeyframeTrack( this.name, times, values );
  24204. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  24205. track.createInterpolant = this.createInterpolant;
  24206. return track;
  24207. }
  24208. }
  24209. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  24210. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  24211. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  24212. /**
  24213. * A Track of Boolean keyframe values.
  24214. */
  24215. class BooleanKeyframeTrack extends KeyframeTrack {}
  24216. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  24217. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  24218. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  24219. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  24220. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  24221. /**
  24222. * A Track of keyframe values that represent color.
  24223. */
  24224. class ColorKeyframeTrack extends KeyframeTrack {}
  24225. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  24226. /**
  24227. * A Track of numeric keyframe values.
  24228. */
  24229. class NumberKeyframeTrack extends KeyframeTrack {}
  24230. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  24231. /**
  24232. * Spherical linear unit quaternion interpolant.
  24233. */
  24234. class QuaternionLinearInterpolant extends Interpolant {
  24235. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24236. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  24237. }
  24238. interpolate_( i1, t0, t, t1 ) {
  24239. const result = this.resultBuffer,
  24240. values = this.sampleValues,
  24241. stride = this.valueSize,
  24242. alpha = ( t - t0 ) / ( t1 - t0 );
  24243. let offset = i1 * stride;
  24244. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  24245. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  24246. }
  24247. return result;
  24248. }
  24249. }
  24250. /**
  24251. * A Track of quaternion keyframe values.
  24252. */
  24253. class QuaternionKeyframeTrack extends KeyframeTrack {
  24254. InterpolantFactoryMethodLinear( result ) {
  24255. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  24256. }
  24257. }
  24258. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  24259. // ValueBufferType is inherited
  24260. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  24261. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  24262. /**
  24263. * A Track that interpolates Strings
  24264. */
  24265. class StringKeyframeTrack extends KeyframeTrack {}
  24266. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  24267. StringKeyframeTrack.prototype.ValueBufferType = Array;
  24268. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  24269. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  24270. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  24271. /**
  24272. * A Track of vectored keyframe values.
  24273. */
  24274. class VectorKeyframeTrack extends KeyframeTrack {}
  24275. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  24276. class AnimationClip {
  24277. constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  24278. this.name = name;
  24279. this.tracks = tracks;
  24280. this.duration = duration;
  24281. this.blendMode = blendMode;
  24282. this.uuid = generateUUID();
  24283. // this means it should figure out its duration by scanning the tracks
  24284. if ( this.duration < 0 ) {
  24285. this.resetDuration();
  24286. }
  24287. }
  24288. static parse( json ) {
  24289. const tracks = [],
  24290. jsonTracks = json.tracks,
  24291. frameTime = 1.0 / ( json.fps || 1.0 );
  24292. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  24293. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  24294. }
  24295. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  24296. clip.uuid = json.uuid;
  24297. return clip;
  24298. }
  24299. static toJSON( clip ) {
  24300. const tracks = [],
  24301. clipTracks = clip.tracks;
  24302. const json = {
  24303. 'name': clip.name,
  24304. 'duration': clip.duration,
  24305. 'tracks': tracks,
  24306. 'uuid': clip.uuid,
  24307. 'blendMode': clip.blendMode
  24308. };
  24309. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  24310. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  24311. }
  24312. return json;
  24313. }
  24314. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  24315. const numMorphTargets = morphTargetSequence.length;
  24316. const tracks = [];
  24317. for ( let i = 0; i < numMorphTargets; i ++ ) {
  24318. let times = [];
  24319. let values = [];
  24320. times.push(
  24321. ( i + numMorphTargets - 1 ) % numMorphTargets,
  24322. i,
  24323. ( i + 1 ) % numMorphTargets );
  24324. values.push( 0, 1, 0 );
  24325. const order = getKeyframeOrder( times );
  24326. times = sortedArray( times, 1, order );
  24327. values = sortedArray( values, 1, order );
  24328. // if there is a key at the first frame, duplicate it as the
  24329. // last frame as well for perfect loop.
  24330. if ( ! noLoop && times[ 0 ] === 0 ) {
  24331. times.push( numMorphTargets );
  24332. values.push( values[ 0 ] );
  24333. }
  24334. tracks.push(
  24335. new NumberKeyframeTrack(
  24336. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  24337. times, values
  24338. ).scale( 1.0 / fps ) );
  24339. }
  24340. return new this( name, - 1, tracks );
  24341. }
  24342. static findByName( objectOrClipArray, name ) {
  24343. let clipArray = objectOrClipArray;
  24344. if ( ! Array.isArray( objectOrClipArray ) ) {
  24345. const o = objectOrClipArray;
  24346. clipArray = o.geometry && o.geometry.animations || o.animations;
  24347. }
  24348. for ( let i = 0; i < clipArray.length; i ++ ) {
  24349. if ( clipArray[ i ].name === name ) {
  24350. return clipArray[ i ];
  24351. }
  24352. }
  24353. return null;
  24354. }
  24355. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  24356. const animationToMorphTargets = {};
  24357. // tested with https://regex101.com/ on trick sequences
  24358. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  24359. const pattern = /^([\w-]*?)([\d]+)$/;
  24360. // sort morph target names into animation groups based
  24361. // patterns like Walk_001, Walk_002, Run_001, Run_002
  24362. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  24363. const morphTarget = morphTargets[ i ];
  24364. const parts = morphTarget.name.match( pattern );
  24365. if ( parts && parts.length > 1 ) {
  24366. const name = parts[ 1 ];
  24367. let animationMorphTargets = animationToMorphTargets[ name ];
  24368. if ( ! animationMorphTargets ) {
  24369. animationToMorphTargets[ name ] = animationMorphTargets = [];
  24370. }
  24371. animationMorphTargets.push( morphTarget );
  24372. }
  24373. }
  24374. const clips = [];
  24375. for ( const name in animationToMorphTargets ) {
  24376. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  24377. }
  24378. return clips;
  24379. }
  24380. // parse the animation.hierarchy format
  24381. static parseAnimation( animation, bones ) {
  24382. if ( ! animation ) {
  24383. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  24384. return null;
  24385. }
  24386. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  24387. // only return track if there are actually keys.
  24388. if ( animationKeys.length !== 0 ) {
  24389. const times = [];
  24390. const values = [];
  24391. flattenJSON( animationKeys, times, values, propertyName );
  24392. // empty keys are filtered out, so check again
  24393. if ( times.length !== 0 ) {
  24394. destTracks.push( new trackType( trackName, times, values ) );
  24395. }
  24396. }
  24397. };
  24398. const tracks = [];
  24399. const clipName = animation.name || 'default';
  24400. const fps = animation.fps || 30;
  24401. const blendMode = animation.blendMode;
  24402. // automatic length determination in AnimationClip.
  24403. let duration = animation.length || - 1;
  24404. const hierarchyTracks = animation.hierarchy || [];
  24405. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  24406. const animationKeys = hierarchyTracks[ h ].keys;
  24407. // skip empty tracks
  24408. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  24409. // process morph targets
  24410. if ( animationKeys[ 0 ].morphTargets ) {
  24411. // figure out all morph targets used in this track
  24412. const morphTargetNames = {};
  24413. let k;
  24414. for ( k = 0; k < animationKeys.length; k ++ ) {
  24415. if ( animationKeys[ k ].morphTargets ) {
  24416. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  24417. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  24418. }
  24419. }
  24420. }
  24421. // create a track for each morph target with all zero
  24422. // morphTargetInfluences except for the keys in which
  24423. // the morphTarget is named.
  24424. for ( const morphTargetName in morphTargetNames ) {
  24425. const times = [];
  24426. const values = [];
  24427. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  24428. const animationKey = animationKeys[ k ];
  24429. times.push( animationKey.time );
  24430. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  24431. }
  24432. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  24433. }
  24434. duration = morphTargetNames.length * fps;
  24435. } else {
  24436. // ...assume skeletal animation
  24437. const boneName = '.bones[' + bones[ h ].name + ']';
  24438. addNonemptyTrack(
  24439. VectorKeyframeTrack, boneName + '.position',
  24440. animationKeys, 'pos', tracks );
  24441. addNonemptyTrack(
  24442. QuaternionKeyframeTrack, boneName + '.quaternion',
  24443. animationKeys, 'rot', tracks );
  24444. addNonemptyTrack(
  24445. VectorKeyframeTrack, boneName + '.scale',
  24446. animationKeys, 'scl', tracks );
  24447. }
  24448. }
  24449. if ( tracks.length === 0 ) {
  24450. return null;
  24451. }
  24452. const clip = new this( clipName, duration, tracks, blendMode );
  24453. return clip;
  24454. }
  24455. resetDuration() {
  24456. const tracks = this.tracks;
  24457. let duration = 0;
  24458. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  24459. const track = this.tracks[ i ];
  24460. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  24461. }
  24462. this.duration = duration;
  24463. return this;
  24464. }
  24465. trim() {
  24466. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24467. this.tracks[ i ].trim( 0, this.duration );
  24468. }
  24469. return this;
  24470. }
  24471. validate() {
  24472. let valid = true;
  24473. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24474. valid = valid && this.tracks[ i ].validate();
  24475. }
  24476. return valid;
  24477. }
  24478. optimize() {
  24479. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24480. this.tracks[ i ].optimize();
  24481. }
  24482. return this;
  24483. }
  24484. clone() {
  24485. const tracks = [];
  24486. for ( let i = 0; i < this.tracks.length; i ++ ) {
  24487. tracks.push( this.tracks[ i ].clone() );
  24488. }
  24489. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  24490. }
  24491. toJSON() {
  24492. return this.constructor.toJSON( this );
  24493. }
  24494. }
  24495. function getTrackTypeForValueTypeName( typeName ) {
  24496. switch ( typeName.toLowerCase() ) {
  24497. case 'scalar':
  24498. case 'double':
  24499. case 'float':
  24500. case 'number':
  24501. case 'integer':
  24502. return NumberKeyframeTrack;
  24503. case 'vector':
  24504. case 'vector2':
  24505. case 'vector3':
  24506. case 'vector4':
  24507. return VectorKeyframeTrack;
  24508. case 'color':
  24509. return ColorKeyframeTrack;
  24510. case 'quaternion':
  24511. return QuaternionKeyframeTrack;
  24512. case 'bool':
  24513. case 'boolean':
  24514. return BooleanKeyframeTrack;
  24515. case 'string':
  24516. return StringKeyframeTrack;
  24517. }
  24518. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  24519. }
  24520. function parseKeyframeTrack( json ) {
  24521. if ( json.type === undefined ) {
  24522. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  24523. }
  24524. const trackType = getTrackTypeForValueTypeName( json.type );
  24525. if ( json.times === undefined ) {
  24526. const times = [], values = [];
  24527. flattenJSON( json.keys, times, values, 'value' );
  24528. json.times = times;
  24529. json.values = values;
  24530. }
  24531. // derived classes can define a static parse method
  24532. if ( trackType.parse !== undefined ) {
  24533. return trackType.parse( json );
  24534. } else {
  24535. // by default, we assume a constructor compatible with the base
  24536. return new trackType( json.name, json.times, json.values, json.interpolation );
  24537. }
  24538. }
  24539. const Cache = {
  24540. enabled: false,
  24541. files: {},
  24542. add: function ( key, file ) {
  24543. if ( this.enabled === false ) return;
  24544. // console.log( 'THREE.Cache', 'Adding key:', key );
  24545. this.files[ key ] = file;
  24546. },
  24547. get: function ( key ) {
  24548. if ( this.enabled === false ) return;
  24549. // console.log( 'THREE.Cache', 'Checking key:', key );
  24550. return this.files[ key ];
  24551. },
  24552. remove: function ( key ) {
  24553. delete this.files[ key ];
  24554. },
  24555. clear: function () {
  24556. this.files = {};
  24557. }
  24558. };
  24559. class LoadingManager {
  24560. constructor( onLoad, onProgress, onError ) {
  24561. const scope = this;
  24562. let isLoading = false;
  24563. let itemsLoaded = 0;
  24564. let itemsTotal = 0;
  24565. let urlModifier = undefined;
  24566. const handlers = [];
  24567. // Refer to #5689 for the reason why we don't set .onStart
  24568. // in the constructor
  24569. this.onStart = undefined;
  24570. this.onLoad = onLoad;
  24571. this.onProgress = onProgress;
  24572. this.onError = onError;
  24573. this.itemStart = function ( url ) {
  24574. itemsTotal ++;
  24575. if ( isLoading === false ) {
  24576. if ( scope.onStart !== undefined ) {
  24577. scope.onStart( url, itemsLoaded, itemsTotal );
  24578. }
  24579. }
  24580. isLoading = true;
  24581. };
  24582. this.itemEnd = function ( url ) {
  24583. itemsLoaded ++;
  24584. if ( scope.onProgress !== undefined ) {
  24585. scope.onProgress( url, itemsLoaded, itemsTotal );
  24586. }
  24587. if ( itemsLoaded === itemsTotal ) {
  24588. isLoading = false;
  24589. if ( scope.onLoad !== undefined ) {
  24590. scope.onLoad();
  24591. }
  24592. }
  24593. };
  24594. this.itemError = function ( url ) {
  24595. if ( scope.onError !== undefined ) {
  24596. scope.onError( url );
  24597. }
  24598. };
  24599. this.resolveURL = function ( url ) {
  24600. if ( urlModifier ) {
  24601. return urlModifier( url );
  24602. }
  24603. return url;
  24604. };
  24605. this.setURLModifier = function ( transform ) {
  24606. urlModifier = transform;
  24607. return this;
  24608. };
  24609. this.addHandler = function ( regex, loader ) {
  24610. handlers.push( regex, loader );
  24611. return this;
  24612. };
  24613. this.removeHandler = function ( regex ) {
  24614. const index = handlers.indexOf( regex );
  24615. if ( index !== - 1 ) {
  24616. handlers.splice( index, 2 );
  24617. }
  24618. return this;
  24619. };
  24620. this.getHandler = function ( file ) {
  24621. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  24622. const regex = handlers[ i ];
  24623. const loader = handlers[ i + 1 ];
  24624. if ( regex.global ) regex.lastIndex = 0; // see #17920
  24625. if ( regex.test( file ) ) {
  24626. return loader;
  24627. }
  24628. }
  24629. return null;
  24630. };
  24631. }
  24632. }
  24633. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  24634. class Loader {
  24635. constructor( manager ) {
  24636. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  24637. this.crossOrigin = 'anonymous';
  24638. this.withCredentials = false;
  24639. this.path = '';
  24640. this.resourcePath = '';
  24641. this.requestHeader = {};
  24642. }
  24643. load( /* url, onLoad, onProgress, onError */ ) {}
  24644. loadAsync( url, onProgress ) {
  24645. const scope = this;
  24646. return new Promise( function ( resolve, reject ) {
  24647. scope.load( url, resolve, onProgress, reject );
  24648. } );
  24649. }
  24650. parse( /* data */ ) {}
  24651. setCrossOrigin( crossOrigin ) {
  24652. this.crossOrigin = crossOrigin;
  24653. return this;
  24654. }
  24655. setWithCredentials( value ) {
  24656. this.withCredentials = value;
  24657. return this;
  24658. }
  24659. setPath( path ) {
  24660. this.path = path;
  24661. return this;
  24662. }
  24663. setResourcePath( resourcePath ) {
  24664. this.resourcePath = resourcePath;
  24665. return this;
  24666. }
  24667. setRequestHeader( requestHeader ) {
  24668. this.requestHeader = requestHeader;
  24669. return this;
  24670. }
  24671. }
  24672. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  24673. const loading = {};
  24674. class HttpError extends Error {
  24675. constructor( message, response ) {
  24676. super( message );
  24677. this.response = response;
  24678. }
  24679. }
  24680. class FileLoader extends Loader {
  24681. constructor( manager ) {
  24682. super( manager );
  24683. }
  24684. load( url, onLoad, onProgress, onError ) {
  24685. if ( url === undefined ) url = '';
  24686. if ( this.path !== undefined ) url = this.path + url;
  24687. url = this.manager.resolveURL( url );
  24688. const cached = Cache.get( url );
  24689. if ( cached !== undefined ) {
  24690. this.manager.itemStart( url );
  24691. setTimeout( () => {
  24692. if ( onLoad ) onLoad( cached );
  24693. this.manager.itemEnd( url );
  24694. }, 0 );
  24695. return cached;
  24696. }
  24697. // Check if request is duplicate
  24698. if ( loading[ url ] !== undefined ) {
  24699. loading[ url ].push( {
  24700. onLoad: onLoad,
  24701. onProgress: onProgress,
  24702. onError: onError
  24703. } );
  24704. return;
  24705. }
  24706. // Initialise array for duplicate requests
  24707. loading[ url ] = [];
  24708. loading[ url ].push( {
  24709. onLoad: onLoad,
  24710. onProgress: onProgress,
  24711. onError: onError,
  24712. } );
  24713. // create request
  24714. const req = new Request( url, {
  24715. headers: new Headers( this.requestHeader ),
  24716. credentials: this.withCredentials ? 'include' : 'same-origin',
  24717. // An abort controller could be added within a future PR
  24718. } );
  24719. // record states ( avoid data race )
  24720. const mimeType = this.mimeType;
  24721. const responseType = this.responseType;
  24722. // start the fetch
  24723. fetch( req )
  24724. .then( response => {
  24725. if ( response.status === 200 || response.status === 0 ) {
  24726. // Some browsers return HTTP Status 0 when using non-http protocol
  24727. // e.g. 'file://' or 'data://'. Handle as success.
  24728. if ( response.status === 0 ) {
  24729. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  24730. }
  24731. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  24732. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  24733. return response;
  24734. }
  24735. const callbacks = loading[ url ];
  24736. const reader = response.body.getReader();
  24737. // Nginx needs X-File-Size check
  24738. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  24739. const contentLength = response.headers.get( 'Content-Length' ) || response.headers.get( 'X-File-Size' );
  24740. const total = contentLength ? parseInt( contentLength ) : 0;
  24741. const lengthComputable = total !== 0;
  24742. let loaded = 0;
  24743. // periodically read data into the new stream tracking while download progress
  24744. const stream = new ReadableStream( {
  24745. start( controller ) {
  24746. readData();
  24747. function readData() {
  24748. reader.read().then( ( { done, value } ) => {
  24749. if ( done ) {
  24750. controller.close();
  24751. } else {
  24752. loaded += value.byteLength;
  24753. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  24754. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24755. const callback = callbacks[ i ];
  24756. if ( callback.onProgress ) callback.onProgress( event );
  24757. }
  24758. controller.enqueue( value );
  24759. readData();
  24760. }
  24761. } );
  24762. }
  24763. }
  24764. } );
  24765. return new Response( stream );
  24766. } else {
  24767. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  24768. }
  24769. } )
  24770. .then( response => {
  24771. switch ( responseType ) {
  24772. case 'arraybuffer':
  24773. return response.arrayBuffer();
  24774. case 'blob':
  24775. return response.blob();
  24776. case 'document':
  24777. return response.text()
  24778. .then( text => {
  24779. const parser = new DOMParser();
  24780. return parser.parseFromString( text, mimeType );
  24781. } );
  24782. case 'json':
  24783. return response.json();
  24784. default:
  24785. if ( mimeType === undefined ) {
  24786. return response.text();
  24787. } else {
  24788. // sniff encoding
  24789. const re = /charset="?([^;"\s]*)"?/i;
  24790. const exec = re.exec( mimeType );
  24791. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  24792. const decoder = new TextDecoder( label );
  24793. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  24794. }
  24795. }
  24796. } )
  24797. .then( data => {
  24798. // Add to cache only on HTTP success, so that we do not cache
  24799. // error response bodies as proper responses to requests.
  24800. Cache.add( url, data );
  24801. const callbacks = loading[ url ];
  24802. delete loading[ url ];
  24803. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24804. const callback = callbacks[ i ];
  24805. if ( callback.onLoad ) callback.onLoad( data );
  24806. }
  24807. } )
  24808. .catch( err => {
  24809. // Abort errors and other errors are handled the same
  24810. const callbacks = loading[ url ];
  24811. if ( callbacks === undefined ) {
  24812. // When onLoad was called and url was deleted in `loading`
  24813. this.manager.itemError( url );
  24814. throw err;
  24815. }
  24816. delete loading[ url ];
  24817. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24818. const callback = callbacks[ i ];
  24819. if ( callback.onError ) callback.onError( err );
  24820. }
  24821. this.manager.itemError( url );
  24822. } )
  24823. .finally( () => {
  24824. this.manager.itemEnd( url );
  24825. } );
  24826. this.manager.itemStart( url );
  24827. }
  24828. setResponseType( value ) {
  24829. this.responseType = value;
  24830. return this;
  24831. }
  24832. setMimeType( value ) {
  24833. this.mimeType = value;
  24834. return this;
  24835. }
  24836. }
  24837. class AnimationLoader extends Loader {
  24838. constructor( manager ) {
  24839. super( manager );
  24840. }
  24841. load( url, onLoad, onProgress, onError ) {
  24842. const scope = this;
  24843. const loader = new FileLoader( this.manager );
  24844. loader.setPath( this.path );
  24845. loader.setRequestHeader( this.requestHeader );
  24846. loader.setWithCredentials( this.withCredentials );
  24847. loader.load( url, function ( text ) {
  24848. try {
  24849. onLoad( scope.parse( JSON.parse( text ) ) );
  24850. } catch ( e ) {
  24851. if ( onError ) {
  24852. onError( e );
  24853. } else {
  24854. console.error( e );
  24855. }
  24856. scope.manager.itemError( url );
  24857. }
  24858. }, onProgress, onError );
  24859. }
  24860. parse( json ) {
  24861. const animations = [];
  24862. for ( let i = 0; i < json.length; i ++ ) {
  24863. const clip = AnimationClip.parse( json[ i ] );
  24864. animations.push( clip );
  24865. }
  24866. return animations;
  24867. }
  24868. }
  24869. /**
  24870. * Abstract Base class to block based textures loader (dds, pvr, ...)
  24871. *
  24872. * Sub classes have to implement the parse() method which will be used in load().
  24873. */
  24874. class CompressedTextureLoader extends Loader {
  24875. constructor( manager ) {
  24876. super( manager );
  24877. }
  24878. load( url, onLoad, onProgress, onError ) {
  24879. const scope = this;
  24880. const images = [];
  24881. const texture = new CompressedTexture();
  24882. const loader = new FileLoader( this.manager );
  24883. loader.setPath( this.path );
  24884. loader.setResponseType( 'arraybuffer' );
  24885. loader.setRequestHeader( this.requestHeader );
  24886. loader.setWithCredentials( scope.withCredentials );
  24887. let loaded = 0;
  24888. function loadTexture( i ) {
  24889. loader.load( url[ i ], function ( buffer ) {
  24890. const texDatas = scope.parse( buffer, true );
  24891. images[ i ] = {
  24892. width: texDatas.width,
  24893. height: texDatas.height,
  24894. format: texDatas.format,
  24895. mipmaps: texDatas.mipmaps
  24896. };
  24897. loaded += 1;
  24898. if ( loaded === 6 ) {
  24899. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  24900. texture.image = images;
  24901. texture.format = texDatas.format;
  24902. texture.needsUpdate = true;
  24903. if ( onLoad ) onLoad( texture );
  24904. }
  24905. }, onProgress, onError );
  24906. }
  24907. if ( Array.isArray( url ) ) {
  24908. for ( let i = 0, il = url.length; i < il; ++ i ) {
  24909. loadTexture( i );
  24910. }
  24911. } else {
  24912. // compressed cubemap texture stored in a single DDS file
  24913. loader.load( url, function ( buffer ) {
  24914. const texDatas = scope.parse( buffer, true );
  24915. if ( texDatas.isCubemap ) {
  24916. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  24917. for ( let f = 0; f < faces; f ++ ) {
  24918. images[ f ] = { mipmaps: [] };
  24919. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  24920. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  24921. images[ f ].format = texDatas.format;
  24922. images[ f ].width = texDatas.width;
  24923. images[ f ].height = texDatas.height;
  24924. }
  24925. }
  24926. texture.image = images;
  24927. } else {
  24928. texture.image.width = texDatas.width;
  24929. texture.image.height = texDatas.height;
  24930. texture.mipmaps = texDatas.mipmaps;
  24931. }
  24932. if ( texDatas.mipmapCount === 1 ) {
  24933. texture.minFilter = LinearFilter;
  24934. }
  24935. texture.format = texDatas.format;
  24936. texture.needsUpdate = true;
  24937. if ( onLoad ) onLoad( texture );
  24938. }, onProgress, onError );
  24939. }
  24940. return texture;
  24941. }
  24942. }
  24943. class ImageLoader extends Loader {
  24944. constructor( manager ) {
  24945. super( manager );
  24946. }
  24947. load( url, onLoad, onProgress, onError ) {
  24948. if ( this.path !== undefined ) url = this.path + url;
  24949. url = this.manager.resolveURL( url );
  24950. const scope = this;
  24951. const cached = Cache.get( url );
  24952. if ( cached !== undefined ) {
  24953. scope.manager.itemStart( url );
  24954. setTimeout( function () {
  24955. if ( onLoad ) onLoad( cached );
  24956. scope.manager.itemEnd( url );
  24957. }, 0 );
  24958. return cached;
  24959. }
  24960. const image = createElementNS( 'img' );
  24961. function onImageLoad() {
  24962. removeEventListeners();
  24963. Cache.add( url, this );
  24964. if ( onLoad ) onLoad( this );
  24965. scope.manager.itemEnd( url );
  24966. }
  24967. function onImageError( event ) {
  24968. removeEventListeners();
  24969. if ( onError ) onError( event );
  24970. scope.manager.itemError( url );
  24971. scope.manager.itemEnd( url );
  24972. }
  24973. function removeEventListeners() {
  24974. image.removeEventListener( 'load', onImageLoad, false );
  24975. image.removeEventListener( 'error', onImageError, false );
  24976. }
  24977. image.addEventListener( 'load', onImageLoad, false );
  24978. image.addEventListener( 'error', onImageError, false );
  24979. if ( url.slice( 0, 5 ) !== 'data:' ) {
  24980. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  24981. }
  24982. scope.manager.itemStart( url );
  24983. image.src = url;
  24984. return image;
  24985. }
  24986. }
  24987. class CubeTextureLoader extends Loader {
  24988. constructor( manager ) {
  24989. super( manager );
  24990. }
  24991. load( urls, onLoad, onProgress, onError ) {
  24992. const texture = new CubeTexture();
  24993. texture.colorSpace = SRGBColorSpace;
  24994. const loader = new ImageLoader( this.manager );
  24995. loader.setCrossOrigin( this.crossOrigin );
  24996. loader.setPath( this.path );
  24997. let loaded = 0;
  24998. function loadTexture( i ) {
  24999. loader.load( urls[ i ], function ( image ) {
  25000. texture.images[ i ] = image;
  25001. loaded ++;
  25002. if ( loaded === 6 ) {
  25003. texture.needsUpdate = true;
  25004. if ( onLoad ) onLoad( texture );
  25005. }
  25006. }, undefined, onError );
  25007. }
  25008. for ( let i = 0; i < urls.length; ++ i ) {
  25009. loadTexture( i );
  25010. }
  25011. return texture;
  25012. }
  25013. }
  25014. /**
  25015. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  25016. *
  25017. * Sub classes have to implement the parse() method which will be used in load().
  25018. */
  25019. class DataTextureLoader extends Loader {
  25020. constructor( manager ) {
  25021. super( manager );
  25022. }
  25023. load( url, onLoad, onProgress, onError ) {
  25024. const scope = this;
  25025. const texture = new DataTexture();
  25026. const loader = new FileLoader( this.manager );
  25027. loader.setResponseType( 'arraybuffer' );
  25028. loader.setRequestHeader( this.requestHeader );
  25029. loader.setPath( this.path );
  25030. loader.setWithCredentials( scope.withCredentials );
  25031. loader.load( url, function ( buffer ) {
  25032. const texData = scope.parse( buffer );
  25033. if ( ! texData ) return;
  25034. if ( texData.image !== undefined ) {
  25035. texture.image = texData.image;
  25036. } else if ( texData.data !== undefined ) {
  25037. texture.image.width = texData.width;
  25038. texture.image.height = texData.height;
  25039. texture.image.data = texData.data;
  25040. }
  25041. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  25042. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  25043. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  25044. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  25045. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  25046. if ( texData.colorSpace !== undefined ) {
  25047. texture.colorSpace = texData.colorSpace;
  25048. } else if ( texData.encoding !== undefined ) { // @deprecated, r152
  25049. texture.encoding = texData.encoding;
  25050. }
  25051. if ( texData.flipY !== undefined ) {
  25052. texture.flipY = texData.flipY;
  25053. }
  25054. if ( texData.format !== undefined ) {
  25055. texture.format = texData.format;
  25056. }
  25057. if ( texData.type !== undefined ) {
  25058. texture.type = texData.type;
  25059. }
  25060. if ( texData.mipmaps !== undefined ) {
  25061. texture.mipmaps = texData.mipmaps;
  25062. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  25063. }
  25064. if ( texData.mipmapCount === 1 ) {
  25065. texture.minFilter = LinearFilter;
  25066. }
  25067. if ( texData.generateMipmaps !== undefined ) {
  25068. texture.generateMipmaps = texData.generateMipmaps;
  25069. }
  25070. texture.needsUpdate = true;
  25071. if ( onLoad ) onLoad( texture, texData );
  25072. }, onProgress, onError );
  25073. return texture;
  25074. }
  25075. }
  25076. class TextureLoader extends Loader {
  25077. constructor( manager ) {
  25078. super( manager );
  25079. }
  25080. load( url, onLoad, onProgress, onError ) {
  25081. const texture = new Texture();
  25082. const loader = new ImageLoader( this.manager );
  25083. loader.setCrossOrigin( this.crossOrigin );
  25084. loader.setPath( this.path );
  25085. loader.load( url, function ( image ) {
  25086. texture.image = image;
  25087. texture.needsUpdate = true;
  25088. if ( onLoad !== undefined ) {
  25089. onLoad( texture );
  25090. }
  25091. }, onProgress, onError );
  25092. return texture;
  25093. }
  25094. }
  25095. class Light extends Object3D {
  25096. constructor( color, intensity = 1 ) {
  25097. super();
  25098. this.isLight = true;
  25099. this.type = 'Light';
  25100. this.color = new Color( color );
  25101. this.intensity = intensity;
  25102. }
  25103. dispose() {
  25104. // Empty here in base class; some subclasses override.
  25105. }
  25106. copy( source, recursive ) {
  25107. super.copy( source, recursive );
  25108. this.color.copy( source.color );
  25109. this.intensity = source.intensity;
  25110. return this;
  25111. }
  25112. toJSON( meta ) {
  25113. const data = super.toJSON( meta );
  25114. data.object.color = this.color.getHex();
  25115. data.object.intensity = this.intensity;
  25116. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  25117. if ( this.distance !== undefined ) data.object.distance = this.distance;
  25118. if ( this.angle !== undefined ) data.object.angle = this.angle;
  25119. if ( this.decay !== undefined ) data.object.decay = this.decay;
  25120. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  25121. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  25122. return data;
  25123. }
  25124. }
  25125. class HemisphereLight extends Light {
  25126. constructor( skyColor, groundColor, intensity ) {
  25127. super( skyColor, intensity );
  25128. this.isHemisphereLight = true;
  25129. this.type = 'HemisphereLight';
  25130. this.position.copy( Object3D.DEFAULT_UP );
  25131. this.updateMatrix();
  25132. this.groundColor = new Color( groundColor );
  25133. }
  25134. copy( source, recursive ) {
  25135. super.copy( source, recursive );
  25136. this.groundColor.copy( source.groundColor );
  25137. return this;
  25138. }
  25139. }
  25140. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  25141. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  25142. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  25143. class LightShadow {
  25144. constructor( camera ) {
  25145. this.camera = camera;
  25146. this.bias = 0;
  25147. this.normalBias = 0;
  25148. this.radius = 1;
  25149. this.blurSamples = 8;
  25150. this.mapSize = new Vector2( 512, 512 );
  25151. this.map = null;
  25152. this.mapPass = null;
  25153. this.matrix = new Matrix4();
  25154. this.autoUpdate = true;
  25155. this.needsUpdate = false;
  25156. this._frustum = new Frustum();
  25157. this._frameExtents = new Vector2( 1, 1 );
  25158. this._viewportCount = 1;
  25159. this._viewports = [
  25160. new Vector4( 0, 0, 1, 1 )
  25161. ];
  25162. }
  25163. getViewportCount() {
  25164. return this._viewportCount;
  25165. }
  25166. getFrustum() {
  25167. return this._frustum;
  25168. }
  25169. updateMatrices( light ) {
  25170. const shadowCamera = this.camera;
  25171. const shadowMatrix = this.matrix;
  25172. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  25173. shadowCamera.position.copy( _lightPositionWorld$1 );
  25174. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  25175. shadowCamera.lookAt( _lookTarget$1 );
  25176. shadowCamera.updateMatrixWorld();
  25177. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  25178. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  25179. shadowMatrix.set(
  25180. 0.5, 0.0, 0.0, 0.5,
  25181. 0.0, 0.5, 0.0, 0.5,
  25182. 0.0, 0.0, 0.5, 0.5,
  25183. 0.0, 0.0, 0.0, 1.0
  25184. );
  25185. shadowMatrix.multiply( _projScreenMatrix$1 );
  25186. }
  25187. getViewport( viewportIndex ) {
  25188. return this._viewports[ viewportIndex ];
  25189. }
  25190. getFrameExtents() {
  25191. return this._frameExtents;
  25192. }
  25193. dispose() {
  25194. if ( this.map ) {
  25195. this.map.dispose();
  25196. }
  25197. if ( this.mapPass ) {
  25198. this.mapPass.dispose();
  25199. }
  25200. }
  25201. copy( source ) {
  25202. this.camera = source.camera.clone();
  25203. this.bias = source.bias;
  25204. this.radius = source.radius;
  25205. this.mapSize.copy( source.mapSize );
  25206. return this;
  25207. }
  25208. clone() {
  25209. return new this.constructor().copy( this );
  25210. }
  25211. toJSON() {
  25212. const object = {};
  25213. if ( this.bias !== 0 ) object.bias = this.bias;
  25214. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  25215. if ( this.radius !== 1 ) object.radius = this.radius;
  25216. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  25217. object.camera = this.camera.toJSON( false ).object;
  25218. delete object.camera.matrix;
  25219. return object;
  25220. }
  25221. }
  25222. class SpotLightShadow extends LightShadow {
  25223. constructor() {
  25224. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  25225. this.isSpotLightShadow = true;
  25226. this.focus = 1;
  25227. }
  25228. updateMatrices( light ) {
  25229. const camera = this.camera;
  25230. const fov = RAD2DEG * 2 * light.angle * this.focus;
  25231. const aspect = this.mapSize.width / this.mapSize.height;
  25232. const far = light.distance || camera.far;
  25233. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  25234. camera.fov = fov;
  25235. camera.aspect = aspect;
  25236. camera.far = far;
  25237. camera.updateProjectionMatrix();
  25238. }
  25239. super.updateMatrices( light );
  25240. }
  25241. copy( source ) {
  25242. super.copy( source );
  25243. this.focus = source.focus;
  25244. return this;
  25245. }
  25246. }
  25247. class SpotLight extends Light {
  25248. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  25249. super( color, intensity );
  25250. this.isSpotLight = true;
  25251. this.type = 'SpotLight';
  25252. this.position.copy( Object3D.DEFAULT_UP );
  25253. this.updateMatrix();
  25254. this.target = new Object3D();
  25255. this.distance = distance;
  25256. this.angle = angle;
  25257. this.penumbra = penumbra;
  25258. this.decay = decay;
  25259. this.map = null;
  25260. this.shadow = new SpotLightShadow();
  25261. }
  25262. get power() {
  25263. // compute the light's luminous power (in lumens) from its intensity (in candela)
  25264. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  25265. return this.intensity * Math.PI;
  25266. }
  25267. set power( power ) {
  25268. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  25269. this.intensity = power / Math.PI;
  25270. }
  25271. dispose() {
  25272. this.shadow.dispose();
  25273. }
  25274. copy( source, recursive ) {
  25275. super.copy( source, recursive );
  25276. this.distance = source.distance;
  25277. this.angle = source.angle;
  25278. this.penumbra = source.penumbra;
  25279. this.decay = source.decay;
  25280. this.target = source.target.clone();
  25281. this.shadow = source.shadow.clone();
  25282. return this;
  25283. }
  25284. }
  25285. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  25286. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  25287. const _lookTarget = /*@__PURE__*/ new Vector3();
  25288. class PointLightShadow extends LightShadow {
  25289. constructor() {
  25290. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  25291. this.isPointLightShadow = true;
  25292. this._frameExtents = new Vector2( 4, 2 );
  25293. this._viewportCount = 6;
  25294. this._viewports = [
  25295. // These viewports map a cube-map onto a 2D texture with the
  25296. // following orientation:
  25297. //
  25298. // xzXZ
  25299. // y Y
  25300. //
  25301. // X - Positive x direction
  25302. // x - Negative x direction
  25303. // Y - Positive y direction
  25304. // y - Negative y direction
  25305. // Z - Positive z direction
  25306. // z - Negative z direction
  25307. // positive X
  25308. new Vector4( 2, 1, 1, 1 ),
  25309. // negative X
  25310. new Vector4( 0, 1, 1, 1 ),
  25311. // positive Z
  25312. new Vector4( 3, 1, 1, 1 ),
  25313. // negative Z
  25314. new Vector4( 1, 1, 1, 1 ),
  25315. // positive Y
  25316. new Vector4( 3, 0, 1, 1 ),
  25317. // negative Y
  25318. new Vector4( 1, 0, 1, 1 )
  25319. ];
  25320. this._cubeDirections = [
  25321. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  25322. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  25323. ];
  25324. this._cubeUps = [
  25325. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  25326. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  25327. ];
  25328. }
  25329. updateMatrices( light, viewportIndex = 0 ) {
  25330. const camera = this.camera;
  25331. const shadowMatrix = this.matrix;
  25332. const far = light.distance || camera.far;
  25333. if ( far !== camera.far ) {
  25334. camera.far = far;
  25335. camera.updateProjectionMatrix();
  25336. }
  25337. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  25338. camera.position.copy( _lightPositionWorld );
  25339. _lookTarget.copy( camera.position );
  25340. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  25341. camera.up.copy( this._cubeUps[ viewportIndex ] );
  25342. camera.lookAt( _lookTarget );
  25343. camera.updateMatrixWorld();
  25344. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  25345. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  25346. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  25347. }
  25348. }
  25349. class PointLight extends Light {
  25350. constructor( color, intensity, distance = 0, decay = 2 ) {
  25351. super( color, intensity );
  25352. this.isPointLight = true;
  25353. this.type = 'PointLight';
  25354. this.distance = distance;
  25355. this.decay = decay;
  25356. this.shadow = new PointLightShadow();
  25357. }
  25358. get power() {
  25359. // compute the light's luminous power (in lumens) from its intensity (in candela)
  25360. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  25361. return this.intensity * 4 * Math.PI;
  25362. }
  25363. set power( power ) {
  25364. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  25365. this.intensity = power / ( 4 * Math.PI );
  25366. }
  25367. dispose() {
  25368. this.shadow.dispose();
  25369. }
  25370. copy( source, recursive ) {
  25371. super.copy( source, recursive );
  25372. this.distance = source.distance;
  25373. this.decay = source.decay;
  25374. this.shadow = source.shadow.clone();
  25375. return this;
  25376. }
  25377. }
  25378. class DirectionalLightShadow extends LightShadow {
  25379. constructor() {
  25380. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  25381. this.isDirectionalLightShadow = true;
  25382. }
  25383. }
  25384. class DirectionalLight extends Light {
  25385. constructor( color, intensity ) {
  25386. super( color, intensity );
  25387. this.isDirectionalLight = true;
  25388. this.type = 'DirectionalLight';
  25389. this.position.copy( Object3D.DEFAULT_UP );
  25390. this.updateMatrix();
  25391. this.target = new Object3D();
  25392. this.shadow = new DirectionalLightShadow();
  25393. }
  25394. dispose() {
  25395. this.shadow.dispose();
  25396. }
  25397. copy( source ) {
  25398. super.copy( source );
  25399. this.target = source.target.clone();
  25400. this.shadow = source.shadow.clone();
  25401. return this;
  25402. }
  25403. }
  25404. class AmbientLight extends Light {
  25405. constructor( color, intensity ) {
  25406. super( color, intensity );
  25407. this.isAmbientLight = true;
  25408. this.type = 'AmbientLight';
  25409. }
  25410. }
  25411. class RectAreaLight extends Light {
  25412. constructor( color, intensity, width = 10, height = 10 ) {
  25413. super( color, intensity );
  25414. this.isRectAreaLight = true;
  25415. this.type = 'RectAreaLight';
  25416. this.width = width;
  25417. this.height = height;
  25418. }
  25419. get power() {
  25420. // compute the light's luminous power (in lumens) from its intensity (in nits)
  25421. return this.intensity * this.width * this.height * Math.PI;
  25422. }
  25423. set power( power ) {
  25424. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  25425. this.intensity = power / ( this.width * this.height * Math.PI );
  25426. }
  25427. copy( source ) {
  25428. super.copy( source );
  25429. this.width = source.width;
  25430. this.height = source.height;
  25431. return this;
  25432. }
  25433. toJSON( meta ) {
  25434. const data = super.toJSON( meta );
  25435. data.object.width = this.width;
  25436. data.object.height = this.height;
  25437. return data;
  25438. }
  25439. }
  25440. /**
  25441. * Primary reference:
  25442. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  25443. *
  25444. * Secondary reference:
  25445. * https://www.ppsloan.org/publications/StupidSH36.pdf
  25446. */
  25447. // 3-band SH defined by 9 coefficients
  25448. class SphericalHarmonics3 {
  25449. constructor() {
  25450. this.isSphericalHarmonics3 = true;
  25451. this.coefficients = [];
  25452. for ( let i = 0; i < 9; i ++ ) {
  25453. this.coefficients.push( new Vector3() );
  25454. }
  25455. }
  25456. set( coefficients ) {
  25457. for ( let i = 0; i < 9; i ++ ) {
  25458. this.coefficients[ i ].copy( coefficients[ i ] );
  25459. }
  25460. return this;
  25461. }
  25462. zero() {
  25463. for ( let i = 0; i < 9; i ++ ) {
  25464. this.coefficients[ i ].set( 0, 0, 0 );
  25465. }
  25466. return this;
  25467. }
  25468. // get the radiance in the direction of the normal
  25469. // target is a Vector3
  25470. getAt( normal, target ) {
  25471. // normal is assumed to be unit length
  25472. const x = normal.x, y = normal.y, z = normal.z;
  25473. const coeff = this.coefficients;
  25474. // band 0
  25475. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  25476. // band 1
  25477. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  25478. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  25479. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  25480. // band 2
  25481. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  25482. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  25483. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  25484. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  25485. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  25486. return target;
  25487. }
  25488. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  25489. // target is a Vector3
  25490. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  25491. getIrradianceAt( normal, target ) {
  25492. // normal is assumed to be unit length
  25493. const x = normal.x, y = normal.y, z = normal.z;
  25494. const coeff = this.coefficients;
  25495. // band 0
  25496. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  25497. // band 1
  25498. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  25499. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  25500. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  25501. // band 2
  25502. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  25503. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  25504. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  25505. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  25506. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  25507. return target;
  25508. }
  25509. add( sh ) {
  25510. for ( let i = 0; i < 9; i ++ ) {
  25511. this.coefficients[ i ].add( sh.coefficients[ i ] );
  25512. }
  25513. return this;
  25514. }
  25515. addScaledSH( sh, s ) {
  25516. for ( let i = 0; i < 9; i ++ ) {
  25517. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  25518. }
  25519. return this;
  25520. }
  25521. scale( s ) {
  25522. for ( let i = 0; i < 9; i ++ ) {
  25523. this.coefficients[ i ].multiplyScalar( s );
  25524. }
  25525. return this;
  25526. }
  25527. lerp( sh, alpha ) {
  25528. for ( let i = 0; i < 9; i ++ ) {
  25529. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  25530. }
  25531. return this;
  25532. }
  25533. equals( sh ) {
  25534. for ( let i = 0; i < 9; i ++ ) {
  25535. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  25536. return false;
  25537. }
  25538. }
  25539. return true;
  25540. }
  25541. copy( sh ) {
  25542. return this.set( sh.coefficients );
  25543. }
  25544. clone() {
  25545. return new this.constructor().copy( this );
  25546. }
  25547. fromArray( array, offset = 0 ) {
  25548. const coefficients = this.coefficients;
  25549. for ( let i = 0; i < 9; i ++ ) {
  25550. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  25551. }
  25552. return this;
  25553. }
  25554. toArray( array = [], offset = 0 ) {
  25555. const coefficients = this.coefficients;
  25556. for ( let i = 0; i < 9; i ++ ) {
  25557. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  25558. }
  25559. return array;
  25560. }
  25561. // evaluate the basis functions
  25562. // shBasis is an Array[ 9 ]
  25563. static getBasisAt( normal, shBasis ) {
  25564. // normal is assumed to be unit length
  25565. const x = normal.x, y = normal.y, z = normal.z;
  25566. // band 0
  25567. shBasis[ 0 ] = 0.282095;
  25568. // band 1
  25569. shBasis[ 1 ] = 0.488603 * y;
  25570. shBasis[ 2 ] = 0.488603 * z;
  25571. shBasis[ 3 ] = 0.488603 * x;
  25572. // band 2
  25573. shBasis[ 4 ] = 1.092548 * x * y;
  25574. shBasis[ 5 ] = 1.092548 * y * z;
  25575. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  25576. shBasis[ 7 ] = 1.092548 * x * z;
  25577. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  25578. }
  25579. }
  25580. class LightProbe extends Light {
  25581. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  25582. super( undefined, intensity );
  25583. this.isLightProbe = true;
  25584. this.sh = sh;
  25585. }
  25586. copy( source ) {
  25587. super.copy( source );
  25588. this.sh.copy( source.sh );
  25589. return this;
  25590. }
  25591. fromJSON( json ) {
  25592. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  25593. this.sh.fromArray( json.sh );
  25594. return this;
  25595. }
  25596. toJSON( meta ) {
  25597. const data = super.toJSON( meta );
  25598. data.object.sh = this.sh.toArray();
  25599. return data;
  25600. }
  25601. }
  25602. class MaterialLoader extends Loader {
  25603. constructor( manager ) {
  25604. super( manager );
  25605. this.textures = {};
  25606. }
  25607. load( url, onLoad, onProgress, onError ) {
  25608. const scope = this;
  25609. const loader = new FileLoader( scope.manager );
  25610. loader.setPath( scope.path );
  25611. loader.setRequestHeader( scope.requestHeader );
  25612. loader.setWithCredentials( scope.withCredentials );
  25613. loader.load( url, function ( text ) {
  25614. try {
  25615. onLoad( scope.parse( JSON.parse( text ) ) );
  25616. } catch ( e ) {
  25617. if ( onError ) {
  25618. onError( e );
  25619. } else {
  25620. console.error( e );
  25621. }
  25622. scope.manager.itemError( url );
  25623. }
  25624. }, onProgress, onError );
  25625. }
  25626. parse( json ) {
  25627. const textures = this.textures;
  25628. function getTexture( name ) {
  25629. if ( textures[ name ] === undefined ) {
  25630. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  25631. }
  25632. return textures[ name ];
  25633. }
  25634. const material = MaterialLoader.createMaterialFromType( json.type );
  25635. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  25636. if ( json.name !== undefined ) material.name = json.name;
  25637. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  25638. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  25639. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  25640. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  25641. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  25642. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  25643. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  25644. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  25645. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  25646. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  25647. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  25648. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  25649. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  25650. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  25651. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  25652. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  25653. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  25654. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  25655. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  25656. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  25657. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  25658. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  25659. if ( json.fog !== undefined ) material.fog = json.fog;
  25660. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  25661. if ( json.blending !== undefined ) material.blending = json.blending;
  25662. if ( json.combine !== undefined ) material.combine = json.combine;
  25663. if ( json.side !== undefined ) material.side = json.side;
  25664. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  25665. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  25666. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  25667. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  25668. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  25669. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  25670. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  25671. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  25672. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  25673. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  25674. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  25675. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  25676. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  25677. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  25678. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  25679. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  25680. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  25681. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  25682. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  25683. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  25684. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  25685. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  25686. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  25687. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  25688. if ( json.scale !== undefined ) material.scale = json.scale;
  25689. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  25690. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  25691. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  25692. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  25693. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  25694. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  25695. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  25696. if ( json.visible !== undefined ) material.visible = json.visible;
  25697. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  25698. if ( json.userData !== undefined ) material.userData = json.userData;
  25699. if ( json.vertexColors !== undefined ) {
  25700. if ( typeof json.vertexColors === 'number' ) {
  25701. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  25702. } else {
  25703. material.vertexColors = json.vertexColors;
  25704. }
  25705. }
  25706. // Shader Material
  25707. if ( json.uniforms !== undefined ) {
  25708. for ( const name in json.uniforms ) {
  25709. const uniform = json.uniforms[ name ];
  25710. material.uniforms[ name ] = {};
  25711. switch ( uniform.type ) {
  25712. case 't':
  25713. material.uniforms[ name ].value = getTexture( uniform.value );
  25714. break;
  25715. case 'c':
  25716. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  25717. break;
  25718. case 'v2':
  25719. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  25720. break;
  25721. case 'v3':
  25722. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  25723. break;
  25724. case 'v4':
  25725. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  25726. break;
  25727. case 'm3':
  25728. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  25729. break;
  25730. case 'm4':
  25731. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  25732. break;
  25733. default:
  25734. material.uniforms[ name ].value = uniform.value;
  25735. }
  25736. }
  25737. }
  25738. if ( json.defines !== undefined ) material.defines = json.defines;
  25739. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  25740. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  25741. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  25742. if ( json.extensions !== undefined ) {
  25743. for ( const key in json.extensions ) {
  25744. material.extensions[ key ] = json.extensions[ key ];
  25745. }
  25746. }
  25747. if ( json.lights !== undefined ) material.lights = json.lights;
  25748. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  25749. // for PointsMaterial
  25750. if ( json.size !== undefined ) material.size = json.size;
  25751. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  25752. // maps
  25753. if ( json.map !== undefined ) material.map = getTexture( json.map );
  25754. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  25755. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  25756. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  25757. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  25758. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  25759. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  25760. if ( json.normalScale !== undefined ) {
  25761. let normalScale = json.normalScale;
  25762. if ( Array.isArray( normalScale ) === false ) {
  25763. // Blender exporter used to export a scalar. See #7459
  25764. normalScale = [ normalScale, normalScale ];
  25765. }
  25766. material.normalScale = new Vector2().fromArray( normalScale );
  25767. }
  25768. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  25769. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  25770. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  25771. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  25772. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  25773. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  25774. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  25775. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  25776. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  25777. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  25778. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  25779. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  25780. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  25781. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  25782. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  25783. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  25784. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  25785. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  25786. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  25787. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  25788. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  25789. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  25790. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  25791. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  25792. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  25793. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  25794. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  25795. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  25796. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  25797. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  25798. return material;
  25799. }
  25800. setTextures( value ) {
  25801. this.textures = value;
  25802. return this;
  25803. }
  25804. static createMaterialFromType( type ) {
  25805. const materialLib = {
  25806. ShadowMaterial,
  25807. SpriteMaterial,
  25808. RawShaderMaterial,
  25809. ShaderMaterial,
  25810. PointsMaterial,
  25811. MeshPhysicalMaterial,
  25812. MeshStandardMaterial,
  25813. MeshPhongMaterial,
  25814. MeshToonMaterial,
  25815. MeshNormalMaterial,
  25816. MeshLambertMaterial,
  25817. MeshDepthMaterial,
  25818. MeshDistanceMaterial,
  25819. MeshBasicMaterial,
  25820. MeshMatcapMaterial,
  25821. LineDashedMaterial,
  25822. LineBasicMaterial,
  25823. Material
  25824. };
  25825. return new materialLib[ type ]();
  25826. }
  25827. }
  25828. class LoaderUtils {
  25829. static decodeText( array ) {
  25830. if ( typeof TextDecoder !== 'undefined' ) {
  25831. return new TextDecoder().decode( array );
  25832. }
  25833. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  25834. // throws a "maximum call stack size exceeded" error for large arrays.
  25835. let s = '';
  25836. for ( let i = 0, il = array.length; i < il; i ++ ) {
  25837. // Implicitly assumes little-endian.
  25838. s += String.fromCharCode( array[ i ] );
  25839. }
  25840. try {
  25841. // merges multi-byte utf-8 characters.
  25842. return decodeURIComponent( escape( s ) );
  25843. } catch ( e ) { // see #16358
  25844. return s;
  25845. }
  25846. }
  25847. static extractUrlBase( url ) {
  25848. const index = url.lastIndexOf( '/' );
  25849. if ( index === - 1 ) return './';
  25850. return url.slice( 0, index + 1 );
  25851. }
  25852. static resolveURL( url, path ) {
  25853. // Invalid URL
  25854. if ( typeof url !== 'string' || url === '' ) return '';
  25855. // Host Relative URL
  25856. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  25857. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  25858. }
  25859. // Absolute URL http://,https://,//
  25860. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  25861. // Data URI
  25862. if ( /^data:.*,.*$/i.test( url ) ) return url;
  25863. // Blob URL
  25864. if ( /^blob:.*$/i.test( url ) ) return url;
  25865. // Relative URL
  25866. return path + url;
  25867. }
  25868. }
  25869. class InstancedBufferGeometry extends BufferGeometry {
  25870. constructor() {
  25871. super();
  25872. this.isInstancedBufferGeometry = true;
  25873. this.type = 'InstancedBufferGeometry';
  25874. this.instanceCount = Infinity;
  25875. }
  25876. copy( source ) {
  25877. super.copy( source );
  25878. this.instanceCount = source.instanceCount;
  25879. return this;
  25880. }
  25881. toJSON() {
  25882. const data = super.toJSON();
  25883. data.instanceCount = this.instanceCount;
  25884. data.isInstancedBufferGeometry = true;
  25885. return data;
  25886. }
  25887. }
  25888. class BufferGeometryLoader extends Loader {
  25889. constructor( manager ) {
  25890. super( manager );
  25891. }
  25892. load( url, onLoad, onProgress, onError ) {
  25893. const scope = this;
  25894. const loader = new FileLoader( scope.manager );
  25895. loader.setPath( scope.path );
  25896. loader.setRequestHeader( scope.requestHeader );
  25897. loader.setWithCredentials( scope.withCredentials );
  25898. loader.load( url, function ( text ) {
  25899. try {
  25900. onLoad( scope.parse( JSON.parse( text ) ) );
  25901. } catch ( e ) {
  25902. if ( onError ) {
  25903. onError( e );
  25904. } else {
  25905. console.error( e );
  25906. }
  25907. scope.manager.itemError( url );
  25908. }
  25909. }, onProgress, onError );
  25910. }
  25911. parse( json ) {
  25912. const interleavedBufferMap = {};
  25913. const arrayBufferMap = {};
  25914. function getInterleavedBuffer( json, uuid ) {
  25915. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  25916. const interleavedBuffers = json.interleavedBuffers;
  25917. const interleavedBuffer = interleavedBuffers[ uuid ];
  25918. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  25919. const array = getTypedArray( interleavedBuffer.type, buffer );
  25920. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  25921. ib.uuid = interleavedBuffer.uuid;
  25922. interleavedBufferMap[ uuid ] = ib;
  25923. return ib;
  25924. }
  25925. function getArrayBuffer( json, uuid ) {
  25926. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  25927. const arrayBuffers = json.arrayBuffers;
  25928. const arrayBuffer = arrayBuffers[ uuid ];
  25929. const ab = new Uint32Array( arrayBuffer ).buffer;
  25930. arrayBufferMap[ uuid ] = ab;
  25931. return ab;
  25932. }
  25933. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  25934. const index = json.data.index;
  25935. if ( index !== undefined ) {
  25936. const typedArray = getTypedArray( index.type, index.array );
  25937. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  25938. }
  25939. const attributes = json.data.attributes;
  25940. for ( const key in attributes ) {
  25941. const attribute = attributes[ key ];
  25942. let bufferAttribute;
  25943. if ( attribute.isInterleavedBufferAttribute ) {
  25944. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25945. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25946. } else {
  25947. const typedArray = getTypedArray( attribute.type, attribute.array );
  25948. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  25949. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  25950. }
  25951. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25952. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  25953. if ( attribute.updateRange !== undefined ) {
  25954. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  25955. bufferAttribute.updateRange.count = attribute.updateRange.count;
  25956. }
  25957. geometry.setAttribute( key, bufferAttribute );
  25958. }
  25959. const morphAttributes = json.data.morphAttributes;
  25960. if ( morphAttributes ) {
  25961. for ( const key in morphAttributes ) {
  25962. const attributeArray = morphAttributes[ key ];
  25963. const array = [];
  25964. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  25965. const attribute = attributeArray[ i ];
  25966. let bufferAttribute;
  25967. if ( attribute.isInterleavedBufferAttribute ) {
  25968. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25969. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25970. } else {
  25971. const typedArray = getTypedArray( attribute.type, attribute.array );
  25972. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  25973. }
  25974. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25975. array.push( bufferAttribute );
  25976. }
  25977. geometry.morphAttributes[ key ] = array;
  25978. }
  25979. }
  25980. const morphTargetsRelative = json.data.morphTargetsRelative;
  25981. if ( morphTargetsRelative ) {
  25982. geometry.morphTargetsRelative = true;
  25983. }
  25984. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  25985. if ( groups !== undefined ) {
  25986. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  25987. const group = groups[ i ];
  25988. geometry.addGroup( group.start, group.count, group.materialIndex );
  25989. }
  25990. }
  25991. const boundingSphere = json.data.boundingSphere;
  25992. if ( boundingSphere !== undefined ) {
  25993. const center = new Vector3();
  25994. if ( boundingSphere.center !== undefined ) {
  25995. center.fromArray( boundingSphere.center );
  25996. }
  25997. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  25998. }
  25999. if ( json.name ) geometry.name = json.name;
  26000. if ( json.userData ) geometry.userData = json.userData;
  26001. return geometry;
  26002. }
  26003. }
  26004. class ObjectLoader extends Loader {
  26005. constructor( manager ) {
  26006. super( manager );
  26007. }
  26008. load( url, onLoad, onProgress, onError ) {
  26009. const scope = this;
  26010. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  26011. this.resourcePath = this.resourcePath || path;
  26012. const loader = new FileLoader( this.manager );
  26013. loader.setPath( this.path );
  26014. loader.setRequestHeader( this.requestHeader );
  26015. loader.setWithCredentials( this.withCredentials );
  26016. loader.load( url, function ( text ) {
  26017. let json = null;
  26018. try {
  26019. json = JSON.parse( text );
  26020. } catch ( error ) {
  26021. if ( onError !== undefined ) onError( error );
  26022. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  26023. return;
  26024. }
  26025. const metadata = json.metadata;
  26026. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  26027. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  26028. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  26029. return;
  26030. }
  26031. scope.parse( json, onLoad );
  26032. }, onProgress, onError );
  26033. }
  26034. async loadAsync( url, onProgress ) {
  26035. const scope = this;
  26036. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  26037. this.resourcePath = this.resourcePath || path;
  26038. const loader = new FileLoader( this.manager );
  26039. loader.setPath( this.path );
  26040. loader.setRequestHeader( this.requestHeader );
  26041. loader.setWithCredentials( this.withCredentials );
  26042. const text = await loader.loadAsync( url, onProgress );
  26043. const json = JSON.parse( text );
  26044. const metadata = json.metadata;
  26045. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  26046. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  26047. }
  26048. return await scope.parseAsync( json );
  26049. }
  26050. parse( json, onLoad ) {
  26051. const animations = this.parseAnimations( json.animations );
  26052. const shapes = this.parseShapes( json.shapes );
  26053. const geometries = this.parseGeometries( json.geometries, shapes );
  26054. const images = this.parseImages( json.images, function () {
  26055. if ( onLoad !== undefined ) onLoad( object );
  26056. } );
  26057. const textures = this.parseTextures( json.textures, images );
  26058. const materials = this.parseMaterials( json.materials, textures );
  26059. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  26060. const skeletons = this.parseSkeletons( json.skeletons, object );
  26061. this.bindSkeletons( object, skeletons );
  26062. //
  26063. if ( onLoad !== undefined ) {
  26064. let hasImages = false;
  26065. for ( const uuid in images ) {
  26066. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  26067. hasImages = true;
  26068. break;
  26069. }
  26070. }
  26071. if ( hasImages === false ) onLoad( object );
  26072. }
  26073. return object;
  26074. }
  26075. async parseAsync( json ) {
  26076. const animations = this.parseAnimations( json.animations );
  26077. const shapes = this.parseShapes( json.shapes );
  26078. const geometries = this.parseGeometries( json.geometries, shapes );
  26079. const images = await this.parseImagesAsync( json.images );
  26080. const textures = this.parseTextures( json.textures, images );
  26081. const materials = this.parseMaterials( json.materials, textures );
  26082. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  26083. const skeletons = this.parseSkeletons( json.skeletons, object );
  26084. this.bindSkeletons( object, skeletons );
  26085. return object;
  26086. }
  26087. parseShapes( json ) {
  26088. const shapes = {};
  26089. if ( json !== undefined ) {
  26090. for ( let i = 0, l = json.length; i < l; i ++ ) {
  26091. const shape = new Shape().fromJSON( json[ i ] );
  26092. shapes[ shape.uuid ] = shape;
  26093. }
  26094. }
  26095. return shapes;
  26096. }
  26097. parseSkeletons( json, object ) {
  26098. const skeletons = {};
  26099. const bones = {};
  26100. // generate bone lookup table
  26101. object.traverse( function ( child ) {
  26102. if ( child.isBone ) bones[ child.uuid ] = child;
  26103. } );
  26104. // create skeletons
  26105. if ( json !== undefined ) {
  26106. for ( let i = 0, l = json.length; i < l; i ++ ) {
  26107. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  26108. skeletons[ skeleton.uuid ] = skeleton;
  26109. }
  26110. }
  26111. return skeletons;
  26112. }
  26113. parseGeometries( json, shapes ) {
  26114. const geometries = {};
  26115. if ( json !== undefined ) {
  26116. const bufferGeometryLoader = new BufferGeometryLoader();
  26117. for ( let i = 0, l = json.length; i < l; i ++ ) {
  26118. let geometry;
  26119. const data = json[ i ];
  26120. switch ( data.type ) {
  26121. case 'BufferGeometry':
  26122. case 'InstancedBufferGeometry':
  26123. geometry = bufferGeometryLoader.parse( data );
  26124. break;
  26125. default:
  26126. if ( data.type in Geometries ) {
  26127. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  26128. } else {
  26129. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  26130. }
  26131. }
  26132. geometry.uuid = data.uuid;
  26133. if ( data.name !== undefined ) geometry.name = data.name;
  26134. if ( data.userData !== undefined ) geometry.userData = data.userData;
  26135. geometries[ data.uuid ] = geometry;
  26136. }
  26137. }
  26138. return geometries;
  26139. }
  26140. parseMaterials( json, textures ) {
  26141. const cache = {}; // MultiMaterial
  26142. const materials = {};
  26143. if ( json !== undefined ) {
  26144. const loader = new MaterialLoader();
  26145. loader.setTextures( textures );
  26146. for ( let i = 0, l = json.length; i < l; i ++ ) {
  26147. const data = json[ i ];
  26148. if ( cache[ data.uuid ] === undefined ) {
  26149. cache[ data.uuid ] = loader.parse( data );
  26150. }
  26151. materials[ data.uuid ] = cache[ data.uuid ];
  26152. }
  26153. }
  26154. return materials;
  26155. }
  26156. parseAnimations( json ) {
  26157. const animations = {};
  26158. if ( json !== undefined ) {
  26159. for ( let i = 0; i < json.length; i ++ ) {
  26160. const data = json[ i ];
  26161. const clip = AnimationClip.parse( data );
  26162. animations[ clip.uuid ] = clip;
  26163. }
  26164. }
  26165. return animations;
  26166. }
  26167. parseImages( json, onLoad ) {
  26168. const scope = this;
  26169. const images = {};
  26170. let loader;
  26171. function loadImage( url ) {
  26172. scope.manager.itemStart( url );
  26173. return loader.load( url, function () {
  26174. scope.manager.itemEnd( url );
  26175. }, undefined, function () {
  26176. scope.manager.itemError( url );
  26177. scope.manager.itemEnd( url );
  26178. } );
  26179. }
  26180. function deserializeImage( image ) {
  26181. if ( typeof image === 'string' ) {
  26182. const url = image;
  26183. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  26184. return loadImage( path );
  26185. } else {
  26186. if ( image.data ) {
  26187. return {
  26188. data: getTypedArray( image.type, image.data ),
  26189. width: image.width,
  26190. height: image.height
  26191. };
  26192. } else {
  26193. return null;
  26194. }
  26195. }
  26196. }
  26197. if ( json !== undefined && json.length > 0 ) {
  26198. const manager = new LoadingManager( onLoad );
  26199. loader = new ImageLoader( manager );
  26200. loader.setCrossOrigin( this.crossOrigin );
  26201. for ( let i = 0, il = json.length; i < il; i ++ ) {
  26202. const image = json[ i ];
  26203. const url = image.url;
  26204. if ( Array.isArray( url ) ) {
  26205. // load array of images e.g CubeTexture
  26206. const imageArray = [];
  26207. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  26208. const currentUrl = url[ j ];
  26209. const deserializedImage = deserializeImage( currentUrl );
  26210. if ( deserializedImage !== null ) {
  26211. if ( deserializedImage instanceof HTMLImageElement ) {
  26212. imageArray.push( deserializedImage );
  26213. } else {
  26214. // special case: handle array of data textures for cube textures
  26215. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  26216. }
  26217. }
  26218. }
  26219. images[ image.uuid ] = new Source( imageArray );
  26220. } else {
  26221. // load single image
  26222. const deserializedImage = deserializeImage( image.url );
  26223. images[ image.uuid ] = new Source( deserializedImage );
  26224. }
  26225. }
  26226. }
  26227. return images;
  26228. }
  26229. async parseImagesAsync( json ) {
  26230. const scope = this;
  26231. const images = {};
  26232. let loader;
  26233. async function deserializeImage( image ) {
  26234. if ( typeof image === 'string' ) {
  26235. const url = image;
  26236. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  26237. return await loader.loadAsync( path );
  26238. } else {
  26239. if ( image.data ) {
  26240. return {
  26241. data: getTypedArray( image.type, image.data ),
  26242. width: image.width,
  26243. height: image.height
  26244. };
  26245. } else {
  26246. return null;
  26247. }
  26248. }
  26249. }
  26250. if ( json !== undefined && json.length > 0 ) {
  26251. loader = new ImageLoader( this.manager );
  26252. loader.setCrossOrigin( this.crossOrigin );
  26253. for ( let i = 0, il = json.length; i < il; i ++ ) {
  26254. const image = json[ i ];
  26255. const url = image.url;
  26256. if ( Array.isArray( url ) ) {
  26257. // load array of images e.g CubeTexture
  26258. const imageArray = [];
  26259. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  26260. const currentUrl = url[ j ];
  26261. const deserializedImage = await deserializeImage( currentUrl );
  26262. if ( deserializedImage !== null ) {
  26263. if ( deserializedImage instanceof HTMLImageElement ) {
  26264. imageArray.push( deserializedImage );
  26265. } else {
  26266. // special case: handle array of data textures for cube textures
  26267. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  26268. }
  26269. }
  26270. }
  26271. images[ image.uuid ] = new Source( imageArray );
  26272. } else {
  26273. // load single image
  26274. const deserializedImage = await deserializeImage( image.url );
  26275. images[ image.uuid ] = new Source( deserializedImage );
  26276. }
  26277. }
  26278. }
  26279. return images;
  26280. }
  26281. parseTextures( json, images ) {
  26282. function parseConstant( value, type ) {
  26283. if ( typeof value === 'number' ) return value;
  26284. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  26285. return type[ value ];
  26286. }
  26287. const textures = {};
  26288. if ( json !== undefined ) {
  26289. for ( let i = 0, l = json.length; i < l; i ++ ) {
  26290. const data = json[ i ];
  26291. if ( data.image === undefined ) {
  26292. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  26293. }
  26294. if ( images[ data.image ] === undefined ) {
  26295. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  26296. }
  26297. const source = images[ data.image ];
  26298. const image = source.data;
  26299. let texture;
  26300. if ( Array.isArray( image ) ) {
  26301. texture = new CubeTexture();
  26302. if ( image.length === 6 ) texture.needsUpdate = true;
  26303. } else {
  26304. if ( image && image.data ) {
  26305. texture = new DataTexture();
  26306. } else {
  26307. texture = new Texture();
  26308. }
  26309. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  26310. }
  26311. texture.source = source;
  26312. texture.uuid = data.uuid;
  26313. if ( data.name !== undefined ) texture.name = data.name;
  26314. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  26315. if ( data.channel !== undefined ) texture.channel = data.channel;
  26316. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  26317. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  26318. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  26319. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  26320. if ( data.wrap !== undefined ) {
  26321. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  26322. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  26323. }
  26324. if ( data.format !== undefined ) texture.format = data.format;
  26325. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  26326. if ( data.type !== undefined ) texture.type = data.type;
  26327. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  26328. if ( data.encoding !== undefined ) texture.encoding = data.encoding; // @deprecated, r152
  26329. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  26330. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  26331. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  26332. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  26333. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  26334. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  26335. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  26336. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  26337. if ( data.userData !== undefined ) texture.userData = data.userData;
  26338. textures[ data.uuid ] = texture;
  26339. }
  26340. }
  26341. return textures;
  26342. }
  26343. parseObject( data, geometries, materials, textures, animations ) {
  26344. let object;
  26345. function getGeometry( name ) {
  26346. if ( geometries[ name ] === undefined ) {
  26347. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  26348. }
  26349. return geometries[ name ];
  26350. }
  26351. function getMaterial( name ) {
  26352. if ( name === undefined ) return undefined;
  26353. if ( Array.isArray( name ) ) {
  26354. const array = [];
  26355. for ( let i = 0, l = name.length; i < l; i ++ ) {
  26356. const uuid = name[ i ];
  26357. if ( materials[ uuid ] === undefined ) {
  26358. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  26359. }
  26360. array.push( materials[ uuid ] );
  26361. }
  26362. return array;
  26363. }
  26364. if ( materials[ name ] === undefined ) {
  26365. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  26366. }
  26367. return materials[ name ];
  26368. }
  26369. function getTexture( uuid ) {
  26370. if ( textures[ uuid ] === undefined ) {
  26371. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  26372. }
  26373. return textures[ uuid ];
  26374. }
  26375. let geometry, material;
  26376. switch ( data.type ) {
  26377. case 'Scene':
  26378. object = new Scene();
  26379. if ( data.background !== undefined ) {
  26380. if ( Number.isInteger( data.background ) ) {
  26381. object.background = new Color( data.background );
  26382. } else {
  26383. object.background = getTexture( data.background );
  26384. }
  26385. }
  26386. if ( data.environment !== undefined ) {
  26387. object.environment = getTexture( data.environment );
  26388. }
  26389. if ( data.fog !== undefined ) {
  26390. if ( data.fog.type === 'Fog' ) {
  26391. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  26392. } else if ( data.fog.type === 'FogExp2' ) {
  26393. object.fog = new FogExp2( data.fog.color, data.fog.density );
  26394. }
  26395. }
  26396. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  26397. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  26398. break;
  26399. case 'PerspectiveCamera':
  26400. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  26401. if ( data.focus !== undefined ) object.focus = data.focus;
  26402. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  26403. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  26404. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  26405. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  26406. break;
  26407. case 'OrthographicCamera':
  26408. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  26409. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  26410. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  26411. break;
  26412. case 'AmbientLight':
  26413. object = new AmbientLight( data.color, data.intensity );
  26414. break;
  26415. case 'DirectionalLight':
  26416. object = new DirectionalLight( data.color, data.intensity );
  26417. break;
  26418. case 'PointLight':
  26419. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  26420. break;
  26421. case 'RectAreaLight':
  26422. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  26423. break;
  26424. case 'SpotLight':
  26425. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  26426. break;
  26427. case 'HemisphereLight':
  26428. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  26429. break;
  26430. case 'LightProbe':
  26431. object = new LightProbe().fromJSON( data );
  26432. break;
  26433. case 'SkinnedMesh':
  26434. geometry = getGeometry( data.geometry );
  26435. material = getMaterial( data.material );
  26436. object = new SkinnedMesh( geometry, material );
  26437. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  26438. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  26439. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  26440. break;
  26441. case 'Mesh':
  26442. geometry = getGeometry( data.geometry );
  26443. material = getMaterial( data.material );
  26444. object = new Mesh( geometry, material );
  26445. break;
  26446. case 'InstancedMesh':
  26447. geometry = getGeometry( data.geometry );
  26448. material = getMaterial( data.material );
  26449. const count = data.count;
  26450. const instanceMatrix = data.instanceMatrix;
  26451. const instanceColor = data.instanceColor;
  26452. object = new InstancedMesh( geometry, material, count );
  26453. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  26454. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  26455. break;
  26456. case 'LOD':
  26457. object = new LOD();
  26458. break;
  26459. case 'Line':
  26460. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  26461. break;
  26462. case 'LineLoop':
  26463. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  26464. break;
  26465. case 'LineSegments':
  26466. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  26467. break;
  26468. case 'PointCloud':
  26469. case 'Points':
  26470. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  26471. break;
  26472. case 'Sprite':
  26473. object = new Sprite( getMaterial( data.material ) );
  26474. break;
  26475. case 'Group':
  26476. object = new Group();
  26477. break;
  26478. case 'Bone':
  26479. object = new Bone();
  26480. break;
  26481. default:
  26482. object = new Object3D();
  26483. }
  26484. object.uuid = data.uuid;
  26485. if ( data.name !== undefined ) object.name = data.name;
  26486. if ( data.matrix !== undefined ) {
  26487. object.matrix.fromArray( data.matrix );
  26488. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  26489. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  26490. } else {
  26491. if ( data.position !== undefined ) object.position.fromArray( data.position );
  26492. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  26493. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  26494. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  26495. }
  26496. if ( data.up !== undefined ) object.up.fromArray( data.up );
  26497. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  26498. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  26499. if ( data.shadow ) {
  26500. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  26501. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  26502. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  26503. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  26504. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  26505. }
  26506. if ( data.visible !== undefined ) object.visible = data.visible;
  26507. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  26508. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  26509. if ( data.userData !== undefined ) object.userData = data.userData;
  26510. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  26511. if ( data.children !== undefined ) {
  26512. const children = data.children;
  26513. for ( let i = 0; i < children.length; i ++ ) {
  26514. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  26515. }
  26516. }
  26517. if ( data.animations !== undefined ) {
  26518. const objectAnimations = data.animations;
  26519. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  26520. const uuid = objectAnimations[ i ];
  26521. object.animations.push( animations[ uuid ] );
  26522. }
  26523. }
  26524. if ( data.type === 'LOD' ) {
  26525. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  26526. const levels = data.levels;
  26527. for ( let l = 0; l < levels.length; l ++ ) {
  26528. const level = levels[ l ];
  26529. const child = object.getObjectByProperty( 'uuid', level.object );
  26530. if ( child !== undefined ) {
  26531. object.addLevel( child, level.distance, level.hysteresis );
  26532. }
  26533. }
  26534. }
  26535. return object;
  26536. }
  26537. bindSkeletons( object, skeletons ) {
  26538. if ( Object.keys( skeletons ).length === 0 ) return;
  26539. object.traverse( function ( child ) {
  26540. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  26541. const skeleton = skeletons[ child.skeleton ];
  26542. if ( skeleton === undefined ) {
  26543. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  26544. } else {
  26545. child.bind( skeleton, child.bindMatrix );
  26546. }
  26547. }
  26548. } );
  26549. }
  26550. }
  26551. const TEXTURE_MAPPING = {
  26552. UVMapping: UVMapping,
  26553. CubeReflectionMapping: CubeReflectionMapping,
  26554. CubeRefractionMapping: CubeRefractionMapping,
  26555. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  26556. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  26557. CubeUVReflectionMapping: CubeUVReflectionMapping
  26558. };
  26559. const TEXTURE_WRAPPING = {
  26560. RepeatWrapping: RepeatWrapping,
  26561. ClampToEdgeWrapping: ClampToEdgeWrapping,
  26562. MirroredRepeatWrapping: MirroredRepeatWrapping
  26563. };
  26564. const TEXTURE_FILTER = {
  26565. NearestFilter: NearestFilter,
  26566. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  26567. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  26568. LinearFilter: LinearFilter,
  26569. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  26570. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  26571. };
  26572. class ImageBitmapLoader extends Loader {
  26573. constructor( manager ) {
  26574. super( manager );
  26575. this.isImageBitmapLoader = true;
  26576. if ( typeof createImageBitmap === 'undefined' ) {
  26577. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  26578. }
  26579. if ( typeof fetch === 'undefined' ) {
  26580. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  26581. }
  26582. this.options = { premultiplyAlpha: 'none' };
  26583. }
  26584. setOptions( options ) {
  26585. this.options = options;
  26586. return this;
  26587. }
  26588. load( url, onLoad, onProgress, onError ) {
  26589. if ( url === undefined ) url = '';
  26590. if ( this.path !== undefined ) url = this.path + url;
  26591. url = this.manager.resolveURL( url );
  26592. const scope = this;
  26593. const cached = Cache.get( url );
  26594. if ( cached !== undefined ) {
  26595. scope.manager.itemStart( url );
  26596. setTimeout( function () {
  26597. if ( onLoad ) onLoad( cached );
  26598. scope.manager.itemEnd( url );
  26599. }, 0 );
  26600. return cached;
  26601. }
  26602. const fetchOptions = {};
  26603. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  26604. fetchOptions.headers = this.requestHeader;
  26605. fetch( url, fetchOptions ).then( function ( res ) {
  26606. return res.blob();
  26607. } ).then( function ( blob ) {
  26608. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  26609. } ).then( function ( imageBitmap ) {
  26610. Cache.add( url, imageBitmap );
  26611. if ( onLoad ) onLoad( imageBitmap );
  26612. scope.manager.itemEnd( url );
  26613. } ).catch( function ( e ) {
  26614. if ( onError ) onError( e );
  26615. scope.manager.itemError( url );
  26616. scope.manager.itemEnd( url );
  26617. } );
  26618. scope.manager.itemStart( url );
  26619. }
  26620. }
  26621. let _context;
  26622. class AudioContext {
  26623. static getContext() {
  26624. if ( _context === undefined ) {
  26625. _context = new ( window.AudioContext || window.webkitAudioContext )();
  26626. }
  26627. return _context;
  26628. }
  26629. static setContext( value ) {
  26630. _context = value;
  26631. }
  26632. }
  26633. class AudioLoader extends Loader {
  26634. constructor( manager ) {
  26635. super( manager );
  26636. }
  26637. load( url, onLoad, onProgress, onError ) {
  26638. const scope = this;
  26639. const loader = new FileLoader( this.manager );
  26640. loader.setResponseType( 'arraybuffer' );
  26641. loader.setPath( this.path );
  26642. loader.setRequestHeader( this.requestHeader );
  26643. loader.setWithCredentials( this.withCredentials );
  26644. loader.load( url, function ( buffer ) {
  26645. try {
  26646. // Create a copy of the buffer. The `decodeAudioData` method
  26647. // detaches the buffer when complete, preventing reuse.
  26648. const bufferCopy = buffer.slice( 0 );
  26649. const context = AudioContext.getContext();
  26650. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  26651. onLoad( audioBuffer );
  26652. }, handleError );
  26653. } catch ( e ) {
  26654. handleError( e );
  26655. }
  26656. }, onProgress, onError );
  26657. function handleError( e ) {
  26658. if ( onError ) {
  26659. onError( e );
  26660. } else {
  26661. console.error( e );
  26662. }
  26663. scope.manager.itemError( url );
  26664. }
  26665. }
  26666. }
  26667. class HemisphereLightProbe extends LightProbe {
  26668. constructor( skyColor, groundColor, intensity = 1 ) {
  26669. super( undefined, intensity );
  26670. this.isHemisphereLightProbe = true;
  26671. const color1 = new Color().set( skyColor );
  26672. const color2 = new Color().set( groundColor );
  26673. const sky = new Vector3( color1.r, color1.g, color1.b );
  26674. const ground = new Vector3( color2.r, color2.g, color2.b );
  26675. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  26676. const c0 = Math.sqrt( Math.PI );
  26677. const c1 = c0 * Math.sqrt( 0.75 );
  26678. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  26679. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  26680. }
  26681. }
  26682. class AmbientLightProbe extends LightProbe {
  26683. constructor( color, intensity = 1 ) {
  26684. super( undefined, intensity );
  26685. this.isAmbientLightProbe = true;
  26686. const color1 = new Color().set( color );
  26687. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  26688. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  26689. }
  26690. }
  26691. const _eyeRight = /*@__PURE__*/ new Matrix4();
  26692. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  26693. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  26694. class StereoCamera {
  26695. constructor() {
  26696. this.type = 'StereoCamera';
  26697. this.aspect = 1;
  26698. this.eyeSep = 0.064;
  26699. this.cameraL = new PerspectiveCamera();
  26700. this.cameraL.layers.enable( 1 );
  26701. this.cameraL.matrixAutoUpdate = false;
  26702. this.cameraR = new PerspectiveCamera();
  26703. this.cameraR.layers.enable( 2 );
  26704. this.cameraR.matrixAutoUpdate = false;
  26705. this._cache = {
  26706. focus: null,
  26707. fov: null,
  26708. aspect: null,
  26709. near: null,
  26710. far: null,
  26711. zoom: null,
  26712. eyeSep: null
  26713. };
  26714. }
  26715. update( camera ) {
  26716. const cache = this._cache;
  26717. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  26718. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  26719. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  26720. if ( needsUpdate ) {
  26721. cache.focus = camera.focus;
  26722. cache.fov = camera.fov;
  26723. cache.aspect = camera.aspect * this.aspect;
  26724. cache.near = camera.near;
  26725. cache.far = camera.far;
  26726. cache.zoom = camera.zoom;
  26727. cache.eyeSep = this.eyeSep;
  26728. // Off-axis stereoscopic effect based on
  26729. // http://paulbourke.net/stereographics/stereorender/
  26730. _projectionMatrix.copy( camera.projectionMatrix );
  26731. const eyeSepHalf = cache.eyeSep / 2;
  26732. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  26733. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  26734. let xmin, xmax;
  26735. // translate xOffset
  26736. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  26737. _eyeRight.elements[ 12 ] = eyeSepHalf;
  26738. // for left eye
  26739. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  26740. xmax = ymax * cache.aspect + eyeSepOnProjection;
  26741. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26742. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26743. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  26744. // for right eye
  26745. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  26746. xmax = ymax * cache.aspect - eyeSepOnProjection;
  26747. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26748. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26749. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  26750. }
  26751. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  26752. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  26753. }
  26754. }
  26755. class Clock {
  26756. constructor( autoStart = true ) {
  26757. this.autoStart = autoStart;
  26758. this.startTime = 0;
  26759. this.oldTime = 0;
  26760. this.elapsedTime = 0;
  26761. this.running = false;
  26762. }
  26763. start() {
  26764. this.startTime = now();
  26765. this.oldTime = this.startTime;
  26766. this.elapsedTime = 0;
  26767. this.running = true;
  26768. }
  26769. stop() {
  26770. this.getElapsedTime();
  26771. this.running = false;
  26772. this.autoStart = false;
  26773. }
  26774. getElapsedTime() {
  26775. this.getDelta();
  26776. return this.elapsedTime;
  26777. }
  26778. getDelta() {
  26779. let diff = 0;
  26780. if ( this.autoStart && ! this.running ) {
  26781. this.start();
  26782. return 0;
  26783. }
  26784. if ( this.running ) {
  26785. const newTime = now();
  26786. diff = ( newTime - this.oldTime ) / 1000;
  26787. this.oldTime = newTime;
  26788. this.elapsedTime += diff;
  26789. }
  26790. return diff;
  26791. }
  26792. }
  26793. function now() {
  26794. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  26795. }
  26796. const _position$1 = /*@__PURE__*/ new Vector3();
  26797. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  26798. const _scale$1 = /*@__PURE__*/ new Vector3();
  26799. const _orientation$1 = /*@__PURE__*/ new Vector3();
  26800. class AudioListener extends Object3D {
  26801. constructor() {
  26802. super();
  26803. this.type = 'AudioListener';
  26804. this.context = AudioContext.getContext();
  26805. this.gain = this.context.createGain();
  26806. this.gain.connect( this.context.destination );
  26807. this.filter = null;
  26808. this.timeDelta = 0;
  26809. // private
  26810. this._clock = new Clock();
  26811. }
  26812. getInput() {
  26813. return this.gain;
  26814. }
  26815. removeFilter() {
  26816. if ( this.filter !== null ) {
  26817. this.gain.disconnect( this.filter );
  26818. this.filter.disconnect( this.context.destination );
  26819. this.gain.connect( this.context.destination );
  26820. this.filter = null;
  26821. }
  26822. return this;
  26823. }
  26824. getFilter() {
  26825. return this.filter;
  26826. }
  26827. setFilter( value ) {
  26828. if ( this.filter !== null ) {
  26829. this.gain.disconnect( this.filter );
  26830. this.filter.disconnect( this.context.destination );
  26831. } else {
  26832. this.gain.disconnect( this.context.destination );
  26833. }
  26834. this.filter = value;
  26835. this.gain.connect( this.filter );
  26836. this.filter.connect( this.context.destination );
  26837. return this;
  26838. }
  26839. getMasterVolume() {
  26840. return this.gain.gain.value;
  26841. }
  26842. setMasterVolume( value ) {
  26843. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26844. return this;
  26845. }
  26846. updateMatrixWorld( force ) {
  26847. super.updateMatrixWorld( force );
  26848. const listener = this.context.listener;
  26849. const up = this.up;
  26850. this.timeDelta = this._clock.getDelta();
  26851. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  26852. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  26853. if ( listener.positionX ) {
  26854. // code path for Chrome (see #14393)
  26855. const endTime = this.context.currentTime + this.timeDelta;
  26856. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  26857. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  26858. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  26859. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  26860. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  26861. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  26862. listener.upX.linearRampToValueAtTime( up.x, endTime );
  26863. listener.upY.linearRampToValueAtTime( up.y, endTime );
  26864. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  26865. } else {
  26866. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  26867. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  26868. }
  26869. }
  26870. }
  26871. class Audio extends Object3D {
  26872. constructor( listener ) {
  26873. super();
  26874. this.type = 'Audio';
  26875. this.listener = listener;
  26876. this.context = listener.context;
  26877. this.gain = this.context.createGain();
  26878. this.gain.connect( listener.getInput() );
  26879. this.autoplay = false;
  26880. this.buffer = null;
  26881. this.detune = 0;
  26882. this.loop = false;
  26883. this.loopStart = 0;
  26884. this.loopEnd = 0;
  26885. this.offset = 0;
  26886. this.duration = undefined;
  26887. this.playbackRate = 1;
  26888. this.isPlaying = false;
  26889. this.hasPlaybackControl = true;
  26890. this.source = null;
  26891. this.sourceType = 'empty';
  26892. this._startedAt = 0;
  26893. this._progress = 0;
  26894. this._connected = false;
  26895. this.filters = [];
  26896. }
  26897. getOutput() {
  26898. return this.gain;
  26899. }
  26900. setNodeSource( audioNode ) {
  26901. this.hasPlaybackControl = false;
  26902. this.sourceType = 'audioNode';
  26903. this.source = audioNode;
  26904. this.connect();
  26905. return this;
  26906. }
  26907. setMediaElementSource( mediaElement ) {
  26908. this.hasPlaybackControl = false;
  26909. this.sourceType = 'mediaNode';
  26910. this.source = this.context.createMediaElementSource( mediaElement );
  26911. this.connect();
  26912. return this;
  26913. }
  26914. setMediaStreamSource( mediaStream ) {
  26915. this.hasPlaybackControl = false;
  26916. this.sourceType = 'mediaStreamNode';
  26917. this.source = this.context.createMediaStreamSource( mediaStream );
  26918. this.connect();
  26919. return this;
  26920. }
  26921. setBuffer( audioBuffer ) {
  26922. this.buffer = audioBuffer;
  26923. this.sourceType = 'buffer';
  26924. if ( this.autoplay ) this.play();
  26925. return this;
  26926. }
  26927. play( delay = 0 ) {
  26928. if ( this.isPlaying === true ) {
  26929. console.warn( 'THREE.Audio: Audio is already playing.' );
  26930. return;
  26931. }
  26932. if ( this.hasPlaybackControl === false ) {
  26933. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26934. return;
  26935. }
  26936. this._startedAt = this.context.currentTime + delay;
  26937. const source = this.context.createBufferSource();
  26938. source.buffer = this.buffer;
  26939. source.loop = this.loop;
  26940. source.loopStart = this.loopStart;
  26941. source.loopEnd = this.loopEnd;
  26942. source.onended = this.onEnded.bind( this );
  26943. source.start( this._startedAt, this._progress + this.offset, this.duration );
  26944. this.isPlaying = true;
  26945. this.source = source;
  26946. this.setDetune( this.detune );
  26947. this.setPlaybackRate( this.playbackRate );
  26948. return this.connect();
  26949. }
  26950. pause() {
  26951. if ( this.hasPlaybackControl === false ) {
  26952. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26953. return;
  26954. }
  26955. if ( this.isPlaying === true ) {
  26956. // update current progress
  26957. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  26958. if ( this.loop === true ) {
  26959. // ensure _progress does not exceed duration with looped audios
  26960. this._progress = this._progress % ( this.duration || this.buffer.duration );
  26961. }
  26962. this.source.stop();
  26963. this.source.onended = null;
  26964. this.isPlaying = false;
  26965. }
  26966. return this;
  26967. }
  26968. stop() {
  26969. if ( this.hasPlaybackControl === false ) {
  26970. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26971. return;
  26972. }
  26973. this._progress = 0;
  26974. if ( this.source !== null ) {
  26975. this.source.stop();
  26976. this.source.onended = null;
  26977. }
  26978. this.isPlaying = false;
  26979. return this;
  26980. }
  26981. connect() {
  26982. if ( this.filters.length > 0 ) {
  26983. this.source.connect( this.filters[ 0 ] );
  26984. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26985. this.filters[ i - 1 ].connect( this.filters[ i ] );
  26986. }
  26987. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  26988. } else {
  26989. this.source.connect( this.getOutput() );
  26990. }
  26991. this._connected = true;
  26992. return this;
  26993. }
  26994. disconnect() {
  26995. if ( this.filters.length > 0 ) {
  26996. this.source.disconnect( this.filters[ 0 ] );
  26997. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26998. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  26999. }
  27000. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  27001. } else {
  27002. this.source.disconnect( this.getOutput() );
  27003. }
  27004. this._connected = false;
  27005. return this;
  27006. }
  27007. getFilters() {
  27008. return this.filters;
  27009. }
  27010. setFilters( value ) {
  27011. if ( ! value ) value = [];
  27012. if ( this._connected === true ) {
  27013. this.disconnect();
  27014. this.filters = value.slice();
  27015. this.connect();
  27016. } else {
  27017. this.filters = value.slice();
  27018. }
  27019. return this;
  27020. }
  27021. setDetune( value ) {
  27022. this.detune = value;
  27023. if ( this.source.detune === undefined ) return; // only set detune when available
  27024. if ( this.isPlaying === true ) {
  27025. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  27026. }
  27027. return this;
  27028. }
  27029. getDetune() {
  27030. return this.detune;
  27031. }
  27032. getFilter() {
  27033. return this.getFilters()[ 0 ];
  27034. }
  27035. setFilter( filter ) {
  27036. return this.setFilters( filter ? [ filter ] : [] );
  27037. }
  27038. setPlaybackRate( value ) {
  27039. if ( this.hasPlaybackControl === false ) {
  27040. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27041. return;
  27042. }
  27043. this.playbackRate = value;
  27044. if ( this.isPlaying === true ) {
  27045. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  27046. }
  27047. return this;
  27048. }
  27049. getPlaybackRate() {
  27050. return this.playbackRate;
  27051. }
  27052. onEnded() {
  27053. this.isPlaying = false;
  27054. }
  27055. getLoop() {
  27056. if ( this.hasPlaybackControl === false ) {
  27057. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27058. return false;
  27059. }
  27060. return this.loop;
  27061. }
  27062. setLoop( value ) {
  27063. if ( this.hasPlaybackControl === false ) {
  27064. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27065. return;
  27066. }
  27067. this.loop = value;
  27068. if ( this.isPlaying === true ) {
  27069. this.source.loop = this.loop;
  27070. }
  27071. return this;
  27072. }
  27073. setLoopStart( value ) {
  27074. this.loopStart = value;
  27075. return this;
  27076. }
  27077. setLoopEnd( value ) {
  27078. this.loopEnd = value;
  27079. return this;
  27080. }
  27081. getVolume() {
  27082. return this.gain.gain.value;
  27083. }
  27084. setVolume( value ) {
  27085. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  27086. return this;
  27087. }
  27088. }
  27089. const _position = /*@__PURE__*/ new Vector3();
  27090. const _quaternion = /*@__PURE__*/ new Quaternion();
  27091. const _scale = /*@__PURE__*/ new Vector3();
  27092. const _orientation = /*@__PURE__*/ new Vector3();
  27093. class PositionalAudio extends Audio {
  27094. constructor( listener ) {
  27095. super( listener );
  27096. this.panner = this.context.createPanner();
  27097. this.panner.panningModel = 'HRTF';
  27098. this.panner.connect( this.gain );
  27099. }
  27100. connect() {
  27101. super.connect();
  27102. this.panner.connect( this.gain );
  27103. }
  27104. disconnect() {
  27105. super.disconnect();
  27106. this.panner.disconnect( this.gain );
  27107. }
  27108. getOutput() {
  27109. return this.panner;
  27110. }
  27111. getRefDistance() {
  27112. return this.panner.refDistance;
  27113. }
  27114. setRefDistance( value ) {
  27115. this.panner.refDistance = value;
  27116. return this;
  27117. }
  27118. getRolloffFactor() {
  27119. return this.panner.rolloffFactor;
  27120. }
  27121. setRolloffFactor( value ) {
  27122. this.panner.rolloffFactor = value;
  27123. return this;
  27124. }
  27125. getDistanceModel() {
  27126. return this.panner.distanceModel;
  27127. }
  27128. setDistanceModel( value ) {
  27129. this.panner.distanceModel = value;
  27130. return this;
  27131. }
  27132. getMaxDistance() {
  27133. return this.panner.maxDistance;
  27134. }
  27135. setMaxDistance( value ) {
  27136. this.panner.maxDistance = value;
  27137. return this;
  27138. }
  27139. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  27140. this.panner.coneInnerAngle = coneInnerAngle;
  27141. this.panner.coneOuterAngle = coneOuterAngle;
  27142. this.panner.coneOuterGain = coneOuterGain;
  27143. return this;
  27144. }
  27145. updateMatrixWorld( force ) {
  27146. super.updateMatrixWorld( force );
  27147. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  27148. this.matrixWorld.decompose( _position, _quaternion, _scale );
  27149. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  27150. const panner = this.panner;
  27151. if ( panner.positionX ) {
  27152. // code path for Chrome and Firefox (see #14393)
  27153. const endTime = this.context.currentTime + this.listener.timeDelta;
  27154. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  27155. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  27156. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  27157. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  27158. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  27159. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  27160. } else {
  27161. panner.setPosition( _position.x, _position.y, _position.z );
  27162. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  27163. }
  27164. }
  27165. }
  27166. class AudioAnalyser {
  27167. constructor( audio, fftSize = 2048 ) {
  27168. this.analyser = audio.context.createAnalyser();
  27169. this.analyser.fftSize = fftSize;
  27170. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  27171. audio.getOutput().connect( this.analyser );
  27172. }
  27173. getFrequencyData() {
  27174. this.analyser.getByteFrequencyData( this.data );
  27175. return this.data;
  27176. }
  27177. getAverageFrequency() {
  27178. let value = 0;
  27179. const data = this.getFrequencyData();
  27180. for ( let i = 0; i < data.length; i ++ ) {
  27181. value += data[ i ];
  27182. }
  27183. return value / data.length;
  27184. }
  27185. }
  27186. class PropertyMixer {
  27187. constructor( binding, typeName, valueSize ) {
  27188. this.binding = binding;
  27189. this.valueSize = valueSize;
  27190. let mixFunction,
  27191. mixFunctionAdditive,
  27192. setIdentity;
  27193. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  27194. //
  27195. // interpolators can use .buffer as their .result
  27196. // the data then goes to 'incoming'
  27197. //
  27198. // 'accu0' and 'accu1' are used frame-interleaved for
  27199. // the cumulative result and are compared to detect
  27200. // changes
  27201. //
  27202. // 'orig' stores the original state of the property
  27203. //
  27204. // 'add' is used for additive cumulative results
  27205. //
  27206. // 'work' is optional and is only present for quaternion types. It is used
  27207. // to store intermediate quaternion multiplication results
  27208. switch ( typeName ) {
  27209. case 'quaternion':
  27210. mixFunction = this._slerp;
  27211. mixFunctionAdditive = this._slerpAdditive;
  27212. setIdentity = this._setAdditiveIdentityQuaternion;
  27213. this.buffer = new Float64Array( valueSize * 6 );
  27214. this._workIndex = 5;
  27215. break;
  27216. case 'string':
  27217. case 'bool':
  27218. mixFunction = this._select;
  27219. // Use the regular mix function and for additive on these types,
  27220. // additive is not relevant for non-numeric types
  27221. mixFunctionAdditive = this._select;
  27222. setIdentity = this._setAdditiveIdentityOther;
  27223. this.buffer = new Array( valueSize * 5 );
  27224. break;
  27225. default:
  27226. mixFunction = this._lerp;
  27227. mixFunctionAdditive = this._lerpAdditive;
  27228. setIdentity = this._setAdditiveIdentityNumeric;
  27229. this.buffer = new Float64Array( valueSize * 5 );
  27230. }
  27231. this._mixBufferRegion = mixFunction;
  27232. this._mixBufferRegionAdditive = mixFunctionAdditive;
  27233. this._setIdentity = setIdentity;
  27234. this._origIndex = 3;
  27235. this._addIndex = 4;
  27236. this.cumulativeWeight = 0;
  27237. this.cumulativeWeightAdditive = 0;
  27238. this.useCount = 0;
  27239. this.referenceCount = 0;
  27240. }
  27241. // accumulate data in the 'incoming' region into 'accu<i>'
  27242. accumulate( accuIndex, weight ) {
  27243. // note: happily accumulating nothing when weight = 0, the caller knows
  27244. // the weight and shouldn't have made the call in the first place
  27245. const buffer = this.buffer,
  27246. stride = this.valueSize,
  27247. offset = accuIndex * stride + stride;
  27248. let currentWeight = this.cumulativeWeight;
  27249. if ( currentWeight === 0 ) {
  27250. // accuN := incoming * weight
  27251. for ( let i = 0; i !== stride; ++ i ) {
  27252. buffer[ offset + i ] = buffer[ i ];
  27253. }
  27254. currentWeight = weight;
  27255. } else {
  27256. // accuN := accuN + incoming * weight
  27257. currentWeight += weight;
  27258. const mix = weight / currentWeight;
  27259. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  27260. }
  27261. this.cumulativeWeight = currentWeight;
  27262. }
  27263. // accumulate data in the 'incoming' region into 'add'
  27264. accumulateAdditive( weight ) {
  27265. const buffer = this.buffer,
  27266. stride = this.valueSize,
  27267. offset = stride * this._addIndex;
  27268. if ( this.cumulativeWeightAdditive === 0 ) {
  27269. // add = identity
  27270. this._setIdentity();
  27271. }
  27272. // add := add + incoming * weight
  27273. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  27274. this.cumulativeWeightAdditive += weight;
  27275. }
  27276. // apply the state of 'accu<i>' to the binding when accus differ
  27277. apply( accuIndex ) {
  27278. const stride = this.valueSize,
  27279. buffer = this.buffer,
  27280. offset = accuIndex * stride + stride,
  27281. weight = this.cumulativeWeight,
  27282. weightAdditive = this.cumulativeWeightAdditive,
  27283. binding = this.binding;
  27284. this.cumulativeWeight = 0;
  27285. this.cumulativeWeightAdditive = 0;
  27286. if ( weight < 1 ) {
  27287. // accuN := accuN + original * ( 1 - cumulativeWeight )
  27288. const originalValueOffset = stride * this._origIndex;
  27289. this._mixBufferRegion(
  27290. buffer, offset, originalValueOffset, 1 - weight, stride );
  27291. }
  27292. if ( weightAdditive > 0 ) {
  27293. // accuN := accuN + additive accuN
  27294. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  27295. }
  27296. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  27297. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  27298. // value has changed -> update scene graph
  27299. binding.setValue( buffer, offset );
  27300. break;
  27301. }
  27302. }
  27303. }
  27304. // remember the state of the bound property and copy it to both accus
  27305. saveOriginalState() {
  27306. const binding = this.binding;
  27307. const buffer = this.buffer,
  27308. stride = this.valueSize,
  27309. originalValueOffset = stride * this._origIndex;
  27310. binding.getValue( buffer, originalValueOffset );
  27311. // accu[0..1] := orig -- initially detect changes against the original
  27312. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  27313. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  27314. }
  27315. // Add to identity for additive
  27316. this._setIdentity();
  27317. this.cumulativeWeight = 0;
  27318. this.cumulativeWeightAdditive = 0;
  27319. }
  27320. // apply the state previously taken via 'saveOriginalState' to the binding
  27321. restoreOriginalState() {
  27322. const originalValueOffset = this.valueSize * 3;
  27323. this.binding.setValue( this.buffer, originalValueOffset );
  27324. }
  27325. _setAdditiveIdentityNumeric() {
  27326. const startIndex = this._addIndex * this.valueSize;
  27327. const endIndex = startIndex + this.valueSize;
  27328. for ( let i = startIndex; i < endIndex; i ++ ) {
  27329. this.buffer[ i ] = 0;
  27330. }
  27331. }
  27332. _setAdditiveIdentityQuaternion() {
  27333. this._setAdditiveIdentityNumeric();
  27334. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  27335. }
  27336. _setAdditiveIdentityOther() {
  27337. const startIndex = this._origIndex * this.valueSize;
  27338. const targetIndex = this._addIndex * this.valueSize;
  27339. for ( let i = 0; i < this.valueSize; i ++ ) {
  27340. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  27341. }
  27342. }
  27343. // mix functions
  27344. _select( buffer, dstOffset, srcOffset, t, stride ) {
  27345. if ( t >= 0.5 ) {
  27346. for ( let i = 0; i !== stride; ++ i ) {
  27347. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  27348. }
  27349. }
  27350. }
  27351. _slerp( buffer, dstOffset, srcOffset, t ) {
  27352. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  27353. }
  27354. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  27355. const workOffset = this._workIndex * stride;
  27356. // Store result in intermediate buffer offset
  27357. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  27358. // Slerp to the intermediate result
  27359. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  27360. }
  27361. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  27362. const s = 1 - t;
  27363. for ( let i = 0; i !== stride; ++ i ) {
  27364. const j = dstOffset + i;
  27365. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  27366. }
  27367. }
  27368. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  27369. for ( let i = 0; i !== stride; ++ i ) {
  27370. const j = dstOffset + i;
  27371. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  27372. }
  27373. }
  27374. }
  27375. // Characters [].:/ are reserved for track binding syntax.
  27376. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  27377. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  27378. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  27379. // only latin characters, and the unicode \p{L} is not yet supported. So
  27380. // instead, we exclude reserved characters and match everything else.
  27381. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  27382. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  27383. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  27384. // be matched to parse the rest of the track name.
  27385. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  27386. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  27387. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  27388. // Object on target node, and accessor. May not contain reserved
  27389. // characters. Accessor may contain any character except closing bracket.
  27390. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  27391. // Property and accessor. May not contain reserved characters. Accessor may
  27392. // contain any non-bracket characters.
  27393. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  27394. const _trackRe = new RegExp( ''
  27395. + '^'
  27396. + _directoryRe
  27397. + _nodeRe
  27398. + _objectRe
  27399. + _propertyRe
  27400. + '$'
  27401. );
  27402. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  27403. class Composite {
  27404. constructor( targetGroup, path, optionalParsedPath ) {
  27405. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  27406. this._targetGroup = targetGroup;
  27407. this._bindings = targetGroup.subscribe_( path, parsedPath );
  27408. }
  27409. getValue( array, offset ) {
  27410. this.bind(); // bind all binding
  27411. const firstValidIndex = this._targetGroup.nCachedObjects_,
  27412. binding = this._bindings[ firstValidIndex ];
  27413. // and only call .getValue on the first
  27414. if ( binding !== undefined ) binding.getValue( array, offset );
  27415. }
  27416. setValue( array, offset ) {
  27417. const bindings = this._bindings;
  27418. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  27419. bindings[ i ].setValue( array, offset );
  27420. }
  27421. }
  27422. bind() {
  27423. const bindings = this._bindings;
  27424. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  27425. bindings[ i ].bind();
  27426. }
  27427. }
  27428. unbind() {
  27429. const bindings = this._bindings;
  27430. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  27431. bindings[ i ].unbind();
  27432. }
  27433. }
  27434. }
  27435. // Note: This class uses a State pattern on a per-method basis:
  27436. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  27437. // prototype version of these methods with one that represents
  27438. // the bound state. When the property is not found, the methods
  27439. // become no-ops.
  27440. class PropertyBinding {
  27441. constructor( rootNode, path, parsedPath ) {
  27442. this.path = path;
  27443. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  27444. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  27445. this.rootNode = rootNode;
  27446. // initial state of these methods that calls 'bind'
  27447. this.getValue = this._getValue_unbound;
  27448. this.setValue = this._setValue_unbound;
  27449. }
  27450. static create( root, path, parsedPath ) {
  27451. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  27452. return new PropertyBinding( root, path, parsedPath );
  27453. } else {
  27454. return new PropertyBinding.Composite( root, path, parsedPath );
  27455. }
  27456. }
  27457. /**
  27458. * Replaces spaces with underscores and removes unsupported characters from
  27459. * node names, to ensure compatibility with parseTrackName().
  27460. *
  27461. * @param {string} name Node name to be sanitized.
  27462. * @return {string}
  27463. */
  27464. static sanitizeNodeName( name ) {
  27465. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  27466. }
  27467. static parseTrackName( trackName ) {
  27468. const matches = _trackRe.exec( trackName );
  27469. if ( matches === null ) {
  27470. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  27471. }
  27472. const results = {
  27473. // directoryName: matches[ 1 ], // (tschw) currently unused
  27474. nodeName: matches[ 2 ],
  27475. objectName: matches[ 3 ],
  27476. objectIndex: matches[ 4 ],
  27477. propertyName: matches[ 5 ], // required
  27478. propertyIndex: matches[ 6 ]
  27479. };
  27480. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  27481. if ( lastDot !== undefined && lastDot !== - 1 ) {
  27482. const objectName = results.nodeName.substring( lastDot + 1 );
  27483. // Object names must be checked against an allowlist. Otherwise, there
  27484. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  27485. // 'bar' could be the objectName, or part of a nodeName (which can
  27486. // include '.' characters).
  27487. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  27488. results.nodeName = results.nodeName.substring( 0, lastDot );
  27489. results.objectName = objectName;
  27490. }
  27491. }
  27492. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  27493. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  27494. }
  27495. return results;
  27496. }
  27497. static findNode( root, nodeName ) {
  27498. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  27499. return root;
  27500. }
  27501. // search into skeleton bones.
  27502. if ( root.skeleton ) {
  27503. const bone = root.skeleton.getBoneByName( nodeName );
  27504. if ( bone !== undefined ) {
  27505. return bone;
  27506. }
  27507. }
  27508. // search into node subtree.
  27509. if ( root.children ) {
  27510. const searchNodeSubtree = function ( children ) {
  27511. for ( let i = 0; i < children.length; i ++ ) {
  27512. const childNode = children[ i ];
  27513. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  27514. return childNode;
  27515. }
  27516. const result = searchNodeSubtree( childNode.children );
  27517. if ( result ) return result;
  27518. }
  27519. return null;
  27520. };
  27521. const subTreeNode = searchNodeSubtree( root.children );
  27522. if ( subTreeNode ) {
  27523. return subTreeNode;
  27524. }
  27525. }
  27526. return null;
  27527. }
  27528. // these are used to "bind" a nonexistent property
  27529. _getValue_unavailable() {}
  27530. _setValue_unavailable() {}
  27531. // Getters
  27532. _getValue_direct( buffer, offset ) {
  27533. buffer[ offset ] = this.targetObject[ this.propertyName ];
  27534. }
  27535. _getValue_array( buffer, offset ) {
  27536. const source = this.resolvedProperty;
  27537. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  27538. buffer[ offset ++ ] = source[ i ];
  27539. }
  27540. }
  27541. _getValue_arrayElement( buffer, offset ) {
  27542. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  27543. }
  27544. _getValue_toArray( buffer, offset ) {
  27545. this.resolvedProperty.toArray( buffer, offset );
  27546. }
  27547. // Direct
  27548. _setValue_direct( buffer, offset ) {
  27549. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27550. }
  27551. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  27552. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27553. this.targetObject.needsUpdate = true;
  27554. }
  27555. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27556. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27557. this.targetObject.matrixWorldNeedsUpdate = true;
  27558. }
  27559. // EntireArray
  27560. _setValue_array( buffer, offset ) {
  27561. const dest = this.resolvedProperty;
  27562. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27563. dest[ i ] = buffer[ offset ++ ];
  27564. }
  27565. }
  27566. _setValue_array_setNeedsUpdate( buffer, offset ) {
  27567. const dest = this.resolvedProperty;
  27568. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27569. dest[ i ] = buffer[ offset ++ ];
  27570. }
  27571. this.targetObject.needsUpdate = true;
  27572. }
  27573. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27574. const dest = this.resolvedProperty;
  27575. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27576. dest[ i ] = buffer[ offset ++ ];
  27577. }
  27578. this.targetObject.matrixWorldNeedsUpdate = true;
  27579. }
  27580. // ArrayElement
  27581. _setValue_arrayElement( buffer, offset ) {
  27582. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27583. }
  27584. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  27585. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27586. this.targetObject.needsUpdate = true;
  27587. }
  27588. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27589. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27590. this.targetObject.matrixWorldNeedsUpdate = true;
  27591. }
  27592. // HasToFromArray
  27593. _setValue_fromArray( buffer, offset ) {
  27594. this.resolvedProperty.fromArray( buffer, offset );
  27595. }
  27596. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  27597. this.resolvedProperty.fromArray( buffer, offset );
  27598. this.targetObject.needsUpdate = true;
  27599. }
  27600. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27601. this.resolvedProperty.fromArray( buffer, offset );
  27602. this.targetObject.matrixWorldNeedsUpdate = true;
  27603. }
  27604. _getValue_unbound( targetArray, offset ) {
  27605. this.bind();
  27606. this.getValue( targetArray, offset );
  27607. }
  27608. _setValue_unbound( sourceArray, offset ) {
  27609. this.bind();
  27610. this.setValue( sourceArray, offset );
  27611. }
  27612. // create getter / setter pair for a property in the scene graph
  27613. bind() {
  27614. let targetObject = this.node;
  27615. const parsedPath = this.parsedPath;
  27616. const objectName = parsedPath.objectName;
  27617. const propertyName = parsedPath.propertyName;
  27618. let propertyIndex = parsedPath.propertyIndex;
  27619. if ( ! targetObject ) {
  27620. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  27621. this.node = targetObject;
  27622. }
  27623. // set fail state so we can just 'return' on error
  27624. this.getValue = this._getValue_unavailable;
  27625. this.setValue = this._setValue_unavailable;
  27626. // ensure there is a value node
  27627. if ( ! targetObject ) {
  27628. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  27629. return;
  27630. }
  27631. if ( objectName ) {
  27632. let objectIndex = parsedPath.objectIndex;
  27633. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  27634. switch ( objectName ) {
  27635. case 'materials':
  27636. if ( ! targetObject.material ) {
  27637. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  27638. return;
  27639. }
  27640. if ( ! targetObject.material.materials ) {
  27641. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  27642. return;
  27643. }
  27644. targetObject = targetObject.material.materials;
  27645. break;
  27646. case 'bones':
  27647. if ( ! targetObject.skeleton ) {
  27648. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  27649. return;
  27650. }
  27651. // potential future optimization: skip this if propertyIndex is already an integer
  27652. // and convert the integer string to a true integer.
  27653. targetObject = targetObject.skeleton.bones;
  27654. // support resolving morphTarget names into indices.
  27655. for ( let i = 0; i < targetObject.length; i ++ ) {
  27656. if ( targetObject[ i ].name === objectIndex ) {
  27657. objectIndex = i;
  27658. break;
  27659. }
  27660. }
  27661. break;
  27662. case 'map':
  27663. if ( 'map' in targetObject ) {
  27664. targetObject = targetObject.map;
  27665. break;
  27666. }
  27667. if ( ! targetObject.material ) {
  27668. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  27669. return;
  27670. }
  27671. if ( ! targetObject.material.map ) {
  27672. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  27673. return;
  27674. }
  27675. targetObject = targetObject.material.map;
  27676. break;
  27677. default:
  27678. if ( targetObject[ objectName ] === undefined ) {
  27679. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  27680. return;
  27681. }
  27682. targetObject = targetObject[ objectName ];
  27683. }
  27684. if ( objectIndex !== undefined ) {
  27685. if ( targetObject[ objectIndex ] === undefined ) {
  27686. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  27687. return;
  27688. }
  27689. targetObject = targetObject[ objectIndex ];
  27690. }
  27691. }
  27692. // resolve property
  27693. const nodeProperty = targetObject[ propertyName ];
  27694. if ( nodeProperty === undefined ) {
  27695. const nodeName = parsedPath.nodeName;
  27696. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  27697. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  27698. return;
  27699. }
  27700. // determine versioning scheme
  27701. let versioning = this.Versioning.None;
  27702. this.targetObject = targetObject;
  27703. if ( targetObject.needsUpdate !== undefined ) { // material
  27704. versioning = this.Versioning.NeedsUpdate;
  27705. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  27706. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  27707. }
  27708. // determine how the property gets bound
  27709. let bindingType = this.BindingType.Direct;
  27710. if ( propertyIndex !== undefined ) {
  27711. // access a sub element of the property array (only primitives are supported right now)
  27712. if ( propertyName === 'morphTargetInfluences' ) {
  27713. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  27714. // support resolving morphTarget names into indices.
  27715. if ( ! targetObject.geometry ) {
  27716. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  27717. return;
  27718. }
  27719. if ( ! targetObject.geometry.morphAttributes ) {
  27720. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  27721. return;
  27722. }
  27723. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  27724. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  27725. }
  27726. }
  27727. bindingType = this.BindingType.ArrayElement;
  27728. this.resolvedProperty = nodeProperty;
  27729. this.propertyIndex = propertyIndex;
  27730. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  27731. // must use copy for Object3D.Euler/Quaternion
  27732. bindingType = this.BindingType.HasFromToArray;
  27733. this.resolvedProperty = nodeProperty;
  27734. } else if ( Array.isArray( nodeProperty ) ) {
  27735. bindingType = this.BindingType.EntireArray;
  27736. this.resolvedProperty = nodeProperty;
  27737. } else {
  27738. this.propertyName = propertyName;
  27739. }
  27740. // select getter / setter
  27741. this.getValue = this.GetterByBindingType[ bindingType ];
  27742. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  27743. }
  27744. unbind() {
  27745. this.node = null;
  27746. // back to the prototype version of getValue / setValue
  27747. // note: avoiding to mutate the shape of 'this' via 'delete'
  27748. this.getValue = this._getValue_unbound;
  27749. this.setValue = this._setValue_unbound;
  27750. }
  27751. }
  27752. PropertyBinding.Composite = Composite;
  27753. PropertyBinding.prototype.BindingType = {
  27754. Direct: 0,
  27755. EntireArray: 1,
  27756. ArrayElement: 2,
  27757. HasFromToArray: 3
  27758. };
  27759. PropertyBinding.prototype.Versioning = {
  27760. None: 0,
  27761. NeedsUpdate: 1,
  27762. MatrixWorldNeedsUpdate: 2
  27763. };
  27764. PropertyBinding.prototype.GetterByBindingType = [
  27765. PropertyBinding.prototype._getValue_direct,
  27766. PropertyBinding.prototype._getValue_array,
  27767. PropertyBinding.prototype._getValue_arrayElement,
  27768. PropertyBinding.prototype._getValue_toArray,
  27769. ];
  27770. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  27771. [
  27772. // Direct
  27773. PropertyBinding.prototype._setValue_direct,
  27774. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  27775. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  27776. ], [
  27777. // EntireArray
  27778. PropertyBinding.prototype._setValue_array,
  27779. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  27780. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  27781. ], [
  27782. // ArrayElement
  27783. PropertyBinding.prototype._setValue_arrayElement,
  27784. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  27785. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  27786. ], [
  27787. // HasToFromArray
  27788. PropertyBinding.prototype._setValue_fromArray,
  27789. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  27790. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  27791. ]
  27792. ];
  27793. /**
  27794. *
  27795. * A group of objects that receives a shared animation state.
  27796. *
  27797. * Usage:
  27798. *
  27799. * - Add objects you would otherwise pass as 'root' to the
  27800. * constructor or the .clipAction method of AnimationMixer.
  27801. *
  27802. * - Instead pass this object as 'root'.
  27803. *
  27804. * - You can also add and remove objects later when the mixer
  27805. * is running.
  27806. *
  27807. * Note:
  27808. *
  27809. * Objects of this class appear as one object to the mixer,
  27810. * so cache control of the individual objects must be done
  27811. * on the group.
  27812. *
  27813. * Limitation:
  27814. *
  27815. * - The animated properties must be compatible among the
  27816. * all objects in the group.
  27817. *
  27818. * - A single property can either be controlled through a
  27819. * target group or directly, but not both.
  27820. */
  27821. class AnimationObjectGroup {
  27822. constructor() {
  27823. this.isAnimationObjectGroup = true;
  27824. this.uuid = generateUUID();
  27825. // cached objects followed by the active ones
  27826. this._objects = Array.prototype.slice.call( arguments );
  27827. this.nCachedObjects_ = 0; // threshold
  27828. // note: read by PropertyBinding.Composite
  27829. const indices = {};
  27830. this._indicesByUUID = indices; // for bookkeeping
  27831. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27832. indices[ arguments[ i ].uuid ] = i;
  27833. }
  27834. this._paths = []; // inside: string
  27835. this._parsedPaths = []; // inside: { we don't care, here }
  27836. this._bindings = []; // inside: Array< PropertyBinding >
  27837. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  27838. const scope = this;
  27839. this.stats = {
  27840. objects: {
  27841. get total() {
  27842. return scope._objects.length;
  27843. },
  27844. get inUse() {
  27845. return this.total - scope.nCachedObjects_;
  27846. }
  27847. },
  27848. get bindingsPerObject() {
  27849. return scope._bindings.length;
  27850. }
  27851. };
  27852. }
  27853. add() {
  27854. const objects = this._objects,
  27855. indicesByUUID = this._indicesByUUID,
  27856. paths = this._paths,
  27857. parsedPaths = this._parsedPaths,
  27858. bindings = this._bindings,
  27859. nBindings = bindings.length;
  27860. let knownObject = undefined,
  27861. nObjects = objects.length,
  27862. nCachedObjects = this.nCachedObjects_;
  27863. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27864. const object = arguments[ i ],
  27865. uuid = object.uuid;
  27866. let index = indicesByUUID[ uuid ];
  27867. if ( index === undefined ) {
  27868. // unknown object -> add it to the ACTIVE region
  27869. index = nObjects ++;
  27870. indicesByUUID[ uuid ] = index;
  27871. objects.push( object );
  27872. // accounting is done, now do the same for all bindings
  27873. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27874. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  27875. }
  27876. } else if ( index < nCachedObjects ) {
  27877. knownObject = objects[ index ];
  27878. // move existing object to the ACTIVE region
  27879. const firstActiveIndex = -- nCachedObjects,
  27880. lastCachedObject = objects[ firstActiveIndex ];
  27881. indicesByUUID[ lastCachedObject.uuid ] = index;
  27882. objects[ index ] = lastCachedObject;
  27883. indicesByUUID[ uuid ] = firstActiveIndex;
  27884. objects[ firstActiveIndex ] = object;
  27885. // accounting is done, now do the same for all bindings
  27886. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27887. const bindingsForPath = bindings[ j ],
  27888. lastCached = bindingsForPath[ firstActiveIndex ];
  27889. let binding = bindingsForPath[ index ];
  27890. bindingsForPath[ index ] = lastCached;
  27891. if ( binding === undefined ) {
  27892. // since we do not bother to create new bindings
  27893. // for objects that are cached, the binding may
  27894. // or may not exist
  27895. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  27896. }
  27897. bindingsForPath[ firstActiveIndex ] = binding;
  27898. }
  27899. } else if ( objects[ index ] !== knownObject ) {
  27900. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  27901. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  27902. } // else the object is already where we want it to be
  27903. } // for arguments
  27904. this.nCachedObjects_ = nCachedObjects;
  27905. }
  27906. remove() {
  27907. const objects = this._objects,
  27908. indicesByUUID = this._indicesByUUID,
  27909. bindings = this._bindings,
  27910. nBindings = bindings.length;
  27911. let nCachedObjects = this.nCachedObjects_;
  27912. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27913. const object = arguments[ i ],
  27914. uuid = object.uuid,
  27915. index = indicesByUUID[ uuid ];
  27916. if ( index !== undefined && index >= nCachedObjects ) {
  27917. // move existing object into the CACHED region
  27918. const lastCachedIndex = nCachedObjects ++,
  27919. firstActiveObject = objects[ lastCachedIndex ];
  27920. indicesByUUID[ firstActiveObject.uuid ] = index;
  27921. objects[ index ] = firstActiveObject;
  27922. indicesByUUID[ uuid ] = lastCachedIndex;
  27923. objects[ lastCachedIndex ] = object;
  27924. // accounting is done, now do the same for all bindings
  27925. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27926. const bindingsForPath = bindings[ j ],
  27927. firstActive = bindingsForPath[ lastCachedIndex ],
  27928. binding = bindingsForPath[ index ];
  27929. bindingsForPath[ index ] = firstActive;
  27930. bindingsForPath[ lastCachedIndex ] = binding;
  27931. }
  27932. }
  27933. } // for arguments
  27934. this.nCachedObjects_ = nCachedObjects;
  27935. }
  27936. // remove & forget
  27937. uncache() {
  27938. const objects = this._objects,
  27939. indicesByUUID = this._indicesByUUID,
  27940. bindings = this._bindings,
  27941. nBindings = bindings.length;
  27942. let nCachedObjects = this.nCachedObjects_,
  27943. nObjects = objects.length;
  27944. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27945. const object = arguments[ i ],
  27946. uuid = object.uuid,
  27947. index = indicesByUUID[ uuid ];
  27948. if ( index !== undefined ) {
  27949. delete indicesByUUID[ uuid ];
  27950. if ( index < nCachedObjects ) {
  27951. // object is cached, shrink the CACHED region
  27952. const firstActiveIndex = -- nCachedObjects,
  27953. lastCachedObject = objects[ firstActiveIndex ],
  27954. lastIndex = -- nObjects,
  27955. lastObject = objects[ lastIndex ];
  27956. // last cached object takes this object's place
  27957. indicesByUUID[ lastCachedObject.uuid ] = index;
  27958. objects[ index ] = lastCachedObject;
  27959. // last object goes to the activated slot and pop
  27960. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  27961. objects[ firstActiveIndex ] = lastObject;
  27962. objects.pop();
  27963. // accounting is done, now do the same for all bindings
  27964. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27965. const bindingsForPath = bindings[ j ],
  27966. lastCached = bindingsForPath[ firstActiveIndex ],
  27967. last = bindingsForPath[ lastIndex ];
  27968. bindingsForPath[ index ] = lastCached;
  27969. bindingsForPath[ firstActiveIndex ] = last;
  27970. bindingsForPath.pop();
  27971. }
  27972. } else {
  27973. // object is active, just swap with the last and pop
  27974. const lastIndex = -- nObjects,
  27975. lastObject = objects[ lastIndex ];
  27976. if ( lastIndex > 0 ) {
  27977. indicesByUUID[ lastObject.uuid ] = index;
  27978. }
  27979. objects[ index ] = lastObject;
  27980. objects.pop();
  27981. // accounting is done, now do the same for all bindings
  27982. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27983. const bindingsForPath = bindings[ j ];
  27984. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  27985. bindingsForPath.pop();
  27986. }
  27987. } // cached or active
  27988. } // if object is known
  27989. } // for arguments
  27990. this.nCachedObjects_ = nCachedObjects;
  27991. }
  27992. // Internal interface used by befriended PropertyBinding.Composite:
  27993. subscribe_( path, parsedPath ) {
  27994. // returns an array of bindings for the given path that is changed
  27995. // according to the contained objects in the group
  27996. const indicesByPath = this._bindingsIndicesByPath;
  27997. let index = indicesByPath[ path ];
  27998. const bindings = this._bindings;
  27999. if ( index !== undefined ) return bindings[ index ];
  28000. const paths = this._paths,
  28001. parsedPaths = this._parsedPaths,
  28002. objects = this._objects,
  28003. nObjects = objects.length,
  28004. nCachedObjects = this.nCachedObjects_,
  28005. bindingsForPath = new Array( nObjects );
  28006. index = bindings.length;
  28007. indicesByPath[ path ] = index;
  28008. paths.push( path );
  28009. parsedPaths.push( parsedPath );
  28010. bindings.push( bindingsForPath );
  28011. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  28012. const object = objects[ i ];
  28013. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  28014. }
  28015. return bindingsForPath;
  28016. }
  28017. unsubscribe_( path ) {
  28018. // tells the group to forget about a property path and no longer
  28019. // update the array previously obtained with 'subscribe_'
  28020. const indicesByPath = this._bindingsIndicesByPath,
  28021. index = indicesByPath[ path ];
  28022. if ( index !== undefined ) {
  28023. const paths = this._paths,
  28024. parsedPaths = this._parsedPaths,
  28025. bindings = this._bindings,
  28026. lastBindingsIndex = bindings.length - 1,
  28027. lastBindings = bindings[ lastBindingsIndex ],
  28028. lastBindingsPath = path[ lastBindingsIndex ];
  28029. indicesByPath[ lastBindingsPath ] = index;
  28030. bindings[ index ] = lastBindings;
  28031. bindings.pop();
  28032. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  28033. parsedPaths.pop();
  28034. paths[ index ] = paths[ lastBindingsIndex ];
  28035. paths.pop();
  28036. }
  28037. }
  28038. }
  28039. class AnimationAction {
  28040. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  28041. this._mixer = mixer;
  28042. this._clip = clip;
  28043. this._localRoot = localRoot;
  28044. this.blendMode = blendMode;
  28045. const tracks = clip.tracks,
  28046. nTracks = tracks.length,
  28047. interpolants = new Array( nTracks );
  28048. const interpolantSettings = {
  28049. endingStart: ZeroCurvatureEnding,
  28050. endingEnd: ZeroCurvatureEnding
  28051. };
  28052. for ( let i = 0; i !== nTracks; ++ i ) {
  28053. const interpolant = tracks[ i ].createInterpolant( null );
  28054. interpolants[ i ] = interpolant;
  28055. interpolant.settings = interpolantSettings;
  28056. }
  28057. this._interpolantSettings = interpolantSettings;
  28058. this._interpolants = interpolants; // bound by the mixer
  28059. // inside: PropertyMixer (managed by the mixer)
  28060. this._propertyBindings = new Array( nTracks );
  28061. this._cacheIndex = null; // for the memory manager
  28062. this._byClipCacheIndex = null; // for the memory manager
  28063. this._timeScaleInterpolant = null;
  28064. this._weightInterpolant = null;
  28065. this.loop = LoopRepeat;
  28066. this._loopCount = - 1;
  28067. // global mixer time when the action is to be started
  28068. // it's set back to 'null' upon start of the action
  28069. this._startTime = null;
  28070. // scaled local time of the action
  28071. // gets clamped or wrapped to 0..clip.duration according to loop
  28072. this.time = 0;
  28073. this.timeScale = 1;
  28074. this._effectiveTimeScale = 1;
  28075. this.weight = 1;
  28076. this._effectiveWeight = 1;
  28077. this.repetitions = Infinity; // no. of repetitions when looping
  28078. this.paused = false; // true -> zero effective time scale
  28079. this.enabled = true; // false -> zero effective weight
  28080. this.clampWhenFinished = false;// keep feeding the last frame?
  28081. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  28082. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  28083. }
  28084. // State & Scheduling
  28085. play() {
  28086. this._mixer._activateAction( this );
  28087. return this;
  28088. }
  28089. stop() {
  28090. this._mixer._deactivateAction( this );
  28091. return this.reset();
  28092. }
  28093. reset() {
  28094. this.paused = false;
  28095. this.enabled = true;
  28096. this.time = 0; // restart clip
  28097. this._loopCount = - 1;// forget previous loops
  28098. this._startTime = null;// forget scheduling
  28099. return this.stopFading().stopWarping();
  28100. }
  28101. isRunning() {
  28102. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  28103. this._startTime === null && this._mixer._isActiveAction( this );
  28104. }
  28105. // return true when play has been called
  28106. isScheduled() {
  28107. return this._mixer._isActiveAction( this );
  28108. }
  28109. startAt( time ) {
  28110. this._startTime = time;
  28111. return this;
  28112. }
  28113. setLoop( mode, repetitions ) {
  28114. this.loop = mode;
  28115. this.repetitions = repetitions;
  28116. return this;
  28117. }
  28118. // Weight
  28119. // set the weight stopping any scheduled fading
  28120. // although .enabled = false yields an effective weight of zero, this
  28121. // method does *not* change .enabled, because it would be confusing
  28122. setEffectiveWeight( weight ) {
  28123. this.weight = weight;
  28124. // note: same logic as when updated at runtime
  28125. this._effectiveWeight = this.enabled ? weight : 0;
  28126. return this.stopFading();
  28127. }
  28128. // return the weight considering fading and .enabled
  28129. getEffectiveWeight() {
  28130. return this._effectiveWeight;
  28131. }
  28132. fadeIn( duration ) {
  28133. return this._scheduleFading( duration, 0, 1 );
  28134. }
  28135. fadeOut( duration ) {
  28136. return this._scheduleFading( duration, 1, 0 );
  28137. }
  28138. crossFadeFrom( fadeOutAction, duration, warp ) {
  28139. fadeOutAction.fadeOut( duration );
  28140. this.fadeIn( duration );
  28141. if ( warp ) {
  28142. const fadeInDuration = this._clip.duration,
  28143. fadeOutDuration = fadeOutAction._clip.duration,
  28144. startEndRatio = fadeOutDuration / fadeInDuration,
  28145. endStartRatio = fadeInDuration / fadeOutDuration;
  28146. fadeOutAction.warp( 1.0, startEndRatio, duration );
  28147. this.warp( endStartRatio, 1.0, duration );
  28148. }
  28149. return this;
  28150. }
  28151. crossFadeTo( fadeInAction, duration, warp ) {
  28152. return fadeInAction.crossFadeFrom( this, duration, warp );
  28153. }
  28154. stopFading() {
  28155. const weightInterpolant = this._weightInterpolant;
  28156. if ( weightInterpolant !== null ) {
  28157. this._weightInterpolant = null;
  28158. this._mixer._takeBackControlInterpolant( weightInterpolant );
  28159. }
  28160. return this;
  28161. }
  28162. // Time Scale Control
  28163. // set the time scale stopping any scheduled warping
  28164. // although .paused = true yields an effective time scale of zero, this
  28165. // method does *not* change .paused, because it would be confusing
  28166. setEffectiveTimeScale( timeScale ) {
  28167. this.timeScale = timeScale;
  28168. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  28169. return this.stopWarping();
  28170. }
  28171. // return the time scale considering warping and .paused
  28172. getEffectiveTimeScale() {
  28173. return this._effectiveTimeScale;
  28174. }
  28175. setDuration( duration ) {
  28176. this.timeScale = this._clip.duration / duration;
  28177. return this.stopWarping();
  28178. }
  28179. syncWith( action ) {
  28180. this.time = action.time;
  28181. this.timeScale = action.timeScale;
  28182. return this.stopWarping();
  28183. }
  28184. halt( duration ) {
  28185. return this.warp( this._effectiveTimeScale, 0, duration );
  28186. }
  28187. warp( startTimeScale, endTimeScale, duration ) {
  28188. const mixer = this._mixer,
  28189. now = mixer.time,
  28190. timeScale = this.timeScale;
  28191. let interpolant = this._timeScaleInterpolant;
  28192. if ( interpolant === null ) {
  28193. interpolant = mixer._lendControlInterpolant();
  28194. this._timeScaleInterpolant = interpolant;
  28195. }
  28196. const times = interpolant.parameterPositions,
  28197. values = interpolant.sampleValues;
  28198. times[ 0 ] = now;
  28199. times[ 1 ] = now + duration;
  28200. values[ 0 ] = startTimeScale / timeScale;
  28201. values[ 1 ] = endTimeScale / timeScale;
  28202. return this;
  28203. }
  28204. stopWarping() {
  28205. const timeScaleInterpolant = this._timeScaleInterpolant;
  28206. if ( timeScaleInterpolant !== null ) {
  28207. this._timeScaleInterpolant = null;
  28208. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  28209. }
  28210. return this;
  28211. }
  28212. // Object Accessors
  28213. getMixer() {
  28214. return this._mixer;
  28215. }
  28216. getClip() {
  28217. return this._clip;
  28218. }
  28219. getRoot() {
  28220. return this._localRoot || this._mixer._root;
  28221. }
  28222. // Interna
  28223. _update( time, deltaTime, timeDirection, accuIndex ) {
  28224. // called by the mixer
  28225. if ( ! this.enabled ) {
  28226. // call ._updateWeight() to update ._effectiveWeight
  28227. this._updateWeight( time );
  28228. return;
  28229. }
  28230. const startTime = this._startTime;
  28231. if ( startTime !== null ) {
  28232. // check for scheduled start of action
  28233. const timeRunning = ( time - startTime ) * timeDirection;
  28234. if ( timeRunning < 0 || timeDirection === 0 ) {
  28235. deltaTime = 0;
  28236. } else {
  28237. this._startTime = null; // unschedule
  28238. deltaTime = timeDirection * timeRunning;
  28239. }
  28240. }
  28241. // apply time scale and advance time
  28242. deltaTime *= this._updateTimeScale( time );
  28243. const clipTime = this._updateTime( deltaTime );
  28244. // note: _updateTime may disable the action resulting in
  28245. // an effective weight of 0
  28246. const weight = this._updateWeight( time );
  28247. if ( weight > 0 ) {
  28248. const interpolants = this._interpolants;
  28249. const propertyMixers = this._propertyBindings;
  28250. switch ( this.blendMode ) {
  28251. case AdditiveAnimationBlendMode:
  28252. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  28253. interpolants[ j ].evaluate( clipTime );
  28254. propertyMixers[ j ].accumulateAdditive( weight );
  28255. }
  28256. break;
  28257. case NormalAnimationBlendMode:
  28258. default:
  28259. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  28260. interpolants[ j ].evaluate( clipTime );
  28261. propertyMixers[ j ].accumulate( accuIndex, weight );
  28262. }
  28263. }
  28264. }
  28265. }
  28266. _updateWeight( time ) {
  28267. let weight = 0;
  28268. if ( this.enabled ) {
  28269. weight = this.weight;
  28270. const interpolant = this._weightInterpolant;
  28271. if ( interpolant !== null ) {
  28272. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  28273. weight *= interpolantValue;
  28274. if ( time > interpolant.parameterPositions[ 1 ] ) {
  28275. this.stopFading();
  28276. if ( interpolantValue === 0 ) {
  28277. // faded out, disable
  28278. this.enabled = false;
  28279. }
  28280. }
  28281. }
  28282. }
  28283. this._effectiveWeight = weight;
  28284. return weight;
  28285. }
  28286. _updateTimeScale( time ) {
  28287. let timeScale = 0;
  28288. if ( ! this.paused ) {
  28289. timeScale = this.timeScale;
  28290. const interpolant = this._timeScaleInterpolant;
  28291. if ( interpolant !== null ) {
  28292. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  28293. timeScale *= interpolantValue;
  28294. if ( time > interpolant.parameterPositions[ 1 ] ) {
  28295. this.stopWarping();
  28296. if ( timeScale === 0 ) {
  28297. // motion has halted, pause
  28298. this.paused = true;
  28299. } else {
  28300. // warp done - apply final time scale
  28301. this.timeScale = timeScale;
  28302. }
  28303. }
  28304. }
  28305. }
  28306. this._effectiveTimeScale = timeScale;
  28307. return timeScale;
  28308. }
  28309. _updateTime( deltaTime ) {
  28310. const duration = this._clip.duration;
  28311. const loop = this.loop;
  28312. let time = this.time + deltaTime;
  28313. let loopCount = this._loopCount;
  28314. const pingPong = ( loop === LoopPingPong );
  28315. if ( deltaTime === 0 ) {
  28316. if ( loopCount === - 1 ) return time;
  28317. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  28318. }
  28319. if ( loop === LoopOnce ) {
  28320. if ( loopCount === - 1 ) {
  28321. // just started
  28322. this._loopCount = 0;
  28323. this._setEndings( true, true, false );
  28324. }
  28325. handle_stop: {
  28326. if ( time >= duration ) {
  28327. time = duration;
  28328. } else if ( time < 0 ) {
  28329. time = 0;
  28330. } else {
  28331. this.time = time;
  28332. break handle_stop;
  28333. }
  28334. if ( this.clampWhenFinished ) this.paused = true;
  28335. else this.enabled = false;
  28336. this.time = time;
  28337. this._mixer.dispatchEvent( {
  28338. type: 'finished', action: this,
  28339. direction: deltaTime < 0 ? - 1 : 1
  28340. } );
  28341. }
  28342. } else { // repetitive Repeat or PingPong
  28343. if ( loopCount === - 1 ) {
  28344. // just started
  28345. if ( deltaTime >= 0 ) {
  28346. loopCount = 0;
  28347. this._setEndings( true, this.repetitions === 0, pingPong );
  28348. } else {
  28349. // when looping in reverse direction, the initial
  28350. // transition through zero counts as a repetition,
  28351. // so leave loopCount at -1
  28352. this._setEndings( this.repetitions === 0, true, pingPong );
  28353. }
  28354. }
  28355. if ( time >= duration || time < 0 ) {
  28356. // wrap around
  28357. const loopDelta = Math.floor( time / duration ); // signed
  28358. time -= duration * loopDelta;
  28359. loopCount += Math.abs( loopDelta );
  28360. const pending = this.repetitions - loopCount;
  28361. if ( pending <= 0 ) {
  28362. // have to stop (switch state, clamp time, fire event)
  28363. if ( this.clampWhenFinished ) this.paused = true;
  28364. else this.enabled = false;
  28365. time = deltaTime > 0 ? duration : 0;
  28366. this.time = time;
  28367. this._mixer.dispatchEvent( {
  28368. type: 'finished', action: this,
  28369. direction: deltaTime > 0 ? 1 : - 1
  28370. } );
  28371. } else {
  28372. // keep running
  28373. if ( pending === 1 ) {
  28374. // entering the last round
  28375. const atStart = deltaTime < 0;
  28376. this._setEndings( atStart, ! atStart, pingPong );
  28377. } else {
  28378. this._setEndings( false, false, pingPong );
  28379. }
  28380. this._loopCount = loopCount;
  28381. this.time = time;
  28382. this._mixer.dispatchEvent( {
  28383. type: 'loop', action: this, loopDelta: loopDelta
  28384. } );
  28385. }
  28386. } else {
  28387. this.time = time;
  28388. }
  28389. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  28390. // invert time for the "pong round"
  28391. return duration - time;
  28392. }
  28393. }
  28394. return time;
  28395. }
  28396. _setEndings( atStart, atEnd, pingPong ) {
  28397. const settings = this._interpolantSettings;
  28398. if ( pingPong ) {
  28399. settings.endingStart = ZeroSlopeEnding;
  28400. settings.endingEnd = ZeroSlopeEnding;
  28401. } else {
  28402. // assuming for LoopOnce atStart == atEnd == true
  28403. if ( atStart ) {
  28404. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  28405. } else {
  28406. settings.endingStart = WrapAroundEnding;
  28407. }
  28408. if ( atEnd ) {
  28409. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  28410. } else {
  28411. settings.endingEnd = WrapAroundEnding;
  28412. }
  28413. }
  28414. }
  28415. _scheduleFading( duration, weightNow, weightThen ) {
  28416. const mixer = this._mixer, now = mixer.time;
  28417. let interpolant = this._weightInterpolant;
  28418. if ( interpolant === null ) {
  28419. interpolant = mixer._lendControlInterpolant();
  28420. this._weightInterpolant = interpolant;
  28421. }
  28422. const times = interpolant.parameterPositions,
  28423. values = interpolant.sampleValues;
  28424. times[ 0 ] = now;
  28425. values[ 0 ] = weightNow;
  28426. times[ 1 ] = now + duration;
  28427. values[ 1 ] = weightThen;
  28428. return this;
  28429. }
  28430. }
  28431. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  28432. class AnimationMixer extends EventDispatcher {
  28433. constructor( root ) {
  28434. super();
  28435. this._root = root;
  28436. this._initMemoryManager();
  28437. this._accuIndex = 0;
  28438. this.time = 0;
  28439. this.timeScale = 1.0;
  28440. }
  28441. _bindAction( action, prototypeAction ) {
  28442. const root = action._localRoot || this._root,
  28443. tracks = action._clip.tracks,
  28444. nTracks = tracks.length,
  28445. bindings = action._propertyBindings,
  28446. interpolants = action._interpolants,
  28447. rootUuid = root.uuid,
  28448. bindingsByRoot = this._bindingsByRootAndName;
  28449. let bindingsByName = bindingsByRoot[ rootUuid ];
  28450. if ( bindingsByName === undefined ) {
  28451. bindingsByName = {};
  28452. bindingsByRoot[ rootUuid ] = bindingsByName;
  28453. }
  28454. for ( let i = 0; i !== nTracks; ++ i ) {
  28455. const track = tracks[ i ],
  28456. trackName = track.name;
  28457. let binding = bindingsByName[ trackName ];
  28458. if ( binding !== undefined ) {
  28459. ++ binding.referenceCount;
  28460. bindings[ i ] = binding;
  28461. } else {
  28462. binding = bindings[ i ];
  28463. if ( binding !== undefined ) {
  28464. // existing binding, make sure the cache knows
  28465. if ( binding._cacheIndex === null ) {
  28466. ++ binding.referenceCount;
  28467. this._addInactiveBinding( binding, rootUuid, trackName );
  28468. }
  28469. continue;
  28470. }
  28471. const path = prototypeAction && prototypeAction.
  28472. _propertyBindings[ i ].binding.parsedPath;
  28473. binding = new PropertyMixer(
  28474. PropertyBinding.create( root, trackName, path ),
  28475. track.ValueTypeName, track.getValueSize() );
  28476. ++ binding.referenceCount;
  28477. this._addInactiveBinding( binding, rootUuid, trackName );
  28478. bindings[ i ] = binding;
  28479. }
  28480. interpolants[ i ].resultBuffer = binding.buffer;
  28481. }
  28482. }
  28483. _activateAction( action ) {
  28484. if ( ! this._isActiveAction( action ) ) {
  28485. if ( action._cacheIndex === null ) {
  28486. // this action has been forgotten by the cache, but the user
  28487. // appears to be still using it -> rebind
  28488. const rootUuid = ( action._localRoot || this._root ).uuid,
  28489. clipUuid = action._clip.uuid,
  28490. actionsForClip = this._actionsByClip[ clipUuid ];
  28491. this._bindAction( action,
  28492. actionsForClip && actionsForClip.knownActions[ 0 ] );
  28493. this._addInactiveAction( action, clipUuid, rootUuid );
  28494. }
  28495. const bindings = action._propertyBindings;
  28496. // increment reference counts / sort out state
  28497. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28498. const binding = bindings[ i ];
  28499. if ( binding.useCount ++ === 0 ) {
  28500. this._lendBinding( binding );
  28501. binding.saveOriginalState();
  28502. }
  28503. }
  28504. this._lendAction( action );
  28505. }
  28506. }
  28507. _deactivateAction( action ) {
  28508. if ( this._isActiveAction( action ) ) {
  28509. const bindings = action._propertyBindings;
  28510. // decrement reference counts / sort out state
  28511. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28512. const binding = bindings[ i ];
  28513. if ( -- binding.useCount === 0 ) {
  28514. binding.restoreOriginalState();
  28515. this._takeBackBinding( binding );
  28516. }
  28517. }
  28518. this._takeBackAction( action );
  28519. }
  28520. }
  28521. // Memory manager
  28522. _initMemoryManager() {
  28523. this._actions = []; // 'nActiveActions' followed by inactive ones
  28524. this._nActiveActions = 0;
  28525. this._actionsByClip = {};
  28526. // inside:
  28527. // {
  28528. // knownActions: Array< AnimationAction > - used as prototypes
  28529. // actionByRoot: AnimationAction - lookup
  28530. // }
  28531. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  28532. this._nActiveBindings = 0;
  28533. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  28534. this._controlInterpolants = []; // same game as above
  28535. this._nActiveControlInterpolants = 0;
  28536. const scope = this;
  28537. this.stats = {
  28538. actions: {
  28539. get total() {
  28540. return scope._actions.length;
  28541. },
  28542. get inUse() {
  28543. return scope._nActiveActions;
  28544. }
  28545. },
  28546. bindings: {
  28547. get total() {
  28548. return scope._bindings.length;
  28549. },
  28550. get inUse() {
  28551. return scope._nActiveBindings;
  28552. }
  28553. },
  28554. controlInterpolants: {
  28555. get total() {
  28556. return scope._controlInterpolants.length;
  28557. },
  28558. get inUse() {
  28559. return scope._nActiveControlInterpolants;
  28560. }
  28561. }
  28562. };
  28563. }
  28564. // Memory management for AnimationAction objects
  28565. _isActiveAction( action ) {
  28566. const index = action._cacheIndex;
  28567. return index !== null && index < this._nActiveActions;
  28568. }
  28569. _addInactiveAction( action, clipUuid, rootUuid ) {
  28570. const actions = this._actions,
  28571. actionsByClip = this._actionsByClip;
  28572. let actionsForClip = actionsByClip[ clipUuid ];
  28573. if ( actionsForClip === undefined ) {
  28574. actionsForClip = {
  28575. knownActions: [ action ],
  28576. actionByRoot: {}
  28577. };
  28578. action._byClipCacheIndex = 0;
  28579. actionsByClip[ clipUuid ] = actionsForClip;
  28580. } else {
  28581. const knownActions = actionsForClip.knownActions;
  28582. action._byClipCacheIndex = knownActions.length;
  28583. knownActions.push( action );
  28584. }
  28585. action._cacheIndex = actions.length;
  28586. actions.push( action );
  28587. actionsForClip.actionByRoot[ rootUuid ] = action;
  28588. }
  28589. _removeInactiveAction( action ) {
  28590. const actions = this._actions,
  28591. lastInactiveAction = actions[ actions.length - 1 ],
  28592. cacheIndex = action._cacheIndex;
  28593. lastInactiveAction._cacheIndex = cacheIndex;
  28594. actions[ cacheIndex ] = lastInactiveAction;
  28595. actions.pop();
  28596. action._cacheIndex = null;
  28597. const clipUuid = action._clip.uuid,
  28598. actionsByClip = this._actionsByClip,
  28599. actionsForClip = actionsByClip[ clipUuid ],
  28600. knownActionsForClip = actionsForClip.knownActions,
  28601. lastKnownAction =
  28602. knownActionsForClip[ knownActionsForClip.length - 1 ],
  28603. byClipCacheIndex = action._byClipCacheIndex;
  28604. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  28605. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  28606. knownActionsForClip.pop();
  28607. action._byClipCacheIndex = null;
  28608. const actionByRoot = actionsForClip.actionByRoot,
  28609. rootUuid = ( action._localRoot || this._root ).uuid;
  28610. delete actionByRoot[ rootUuid ];
  28611. if ( knownActionsForClip.length === 0 ) {
  28612. delete actionsByClip[ clipUuid ];
  28613. }
  28614. this._removeInactiveBindingsForAction( action );
  28615. }
  28616. _removeInactiveBindingsForAction( action ) {
  28617. const bindings = action._propertyBindings;
  28618. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28619. const binding = bindings[ i ];
  28620. if ( -- binding.referenceCount === 0 ) {
  28621. this._removeInactiveBinding( binding );
  28622. }
  28623. }
  28624. }
  28625. _lendAction( action ) {
  28626. // [ active actions | inactive actions ]
  28627. // [ active actions >| inactive actions ]
  28628. // s a
  28629. // <-swap->
  28630. // a s
  28631. const actions = this._actions,
  28632. prevIndex = action._cacheIndex,
  28633. lastActiveIndex = this._nActiveActions ++,
  28634. firstInactiveAction = actions[ lastActiveIndex ];
  28635. action._cacheIndex = lastActiveIndex;
  28636. actions[ lastActiveIndex ] = action;
  28637. firstInactiveAction._cacheIndex = prevIndex;
  28638. actions[ prevIndex ] = firstInactiveAction;
  28639. }
  28640. _takeBackAction( action ) {
  28641. // [ active actions | inactive actions ]
  28642. // [ active actions |< inactive actions ]
  28643. // a s
  28644. // <-swap->
  28645. // s a
  28646. const actions = this._actions,
  28647. prevIndex = action._cacheIndex,
  28648. firstInactiveIndex = -- this._nActiveActions,
  28649. lastActiveAction = actions[ firstInactiveIndex ];
  28650. action._cacheIndex = firstInactiveIndex;
  28651. actions[ firstInactiveIndex ] = action;
  28652. lastActiveAction._cacheIndex = prevIndex;
  28653. actions[ prevIndex ] = lastActiveAction;
  28654. }
  28655. // Memory management for PropertyMixer objects
  28656. _addInactiveBinding( binding, rootUuid, trackName ) {
  28657. const bindingsByRoot = this._bindingsByRootAndName,
  28658. bindings = this._bindings;
  28659. let bindingByName = bindingsByRoot[ rootUuid ];
  28660. if ( bindingByName === undefined ) {
  28661. bindingByName = {};
  28662. bindingsByRoot[ rootUuid ] = bindingByName;
  28663. }
  28664. bindingByName[ trackName ] = binding;
  28665. binding._cacheIndex = bindings.length;
  28666. bindings.push( binding );
  28667. }
  28668. _removeInactiveBinding( binding ) {
  28669. const bindings = this._bindings,
  28670. propBinding = binding.binding,
  28671. rootUuid = propBinding.rootNode.uuid,
  28672. trackName = propBinding.path,
  28673. bindingsByRoot = this._bindingsByRootAndName,
  28674. bindingByName = bindingsByRoot[ rootUuid ],
  28675. lastInactiveBinding = bindings[ bindings.length - 1 ],
  28676. cacheIndex = binding._cacheIndex;
  28677. lastInactiveBinding._cacheIndex = cacheIndex;
  28678. bindings[ cacheIndex ] = lastInactiveBinding;
  28679. bindings.pop();
  28680. delete bindingByName[ trackName ];
  28681. if ( Object.keys( bindingByName ).length === 0 ) {
  28682. delete bindingsByRoot[ rootUuid ];
  28683. }
  28684. }
  28685. _lendBinding( binding ) {
  28686. const bindings = this._bindings,
  28687. prevIndex = binding._cacheIndex,
  28688. lastActiveIndex = this._nActiveBindings ++,
  28689. firstInactiveBinding = bindings[ lastActiveIndex ];
  28690. binding._cacheIndex = lastActiveIndex;
  28691. bindings[ lastActiveIndex ] = binding;
  28692. firstInactiveBinding._cacheIndex = prevIndex;
  28693. bindings[ prevIndex ] = firstInactiveBinding;
  28694. }
  28695. _takeBackBinding( binding ) {
  28696. const bindings = this._bindings,
  28697. prevIndex = binding._cacheIndex,
  28698. firstInactiveIndex = -- this._nActiveBindings,
  28699. lastActiveBinding = bindings[ firstInactiveIndex ];
  28700. binding._cacheIndex = firstInactiveIndex;
  28701. bindings[ firstInactiveIndex ] = binding;
  28702. lastActiveBinding._cacheIndex = prevIndex;
  28703. bindings[ prevIndex ] = lastActiveBinding;
  28704. }
  28705. // Memory management of Interpolants for weight and time scale
  28706. _lendControlInterpolant() {
  28707. const interpolants = this._controlInterpolants,
  28708. lastActiveIndex = this._nActiveControlInterpolants ++;
  28709. let interpolant = interpolants[ lastActiveIndex ];
  28710. if ( interpolant === undefined ) {
  28711. interpolant = new LinearInterpolant(
  28712. new Float32Array( 2 ), new Float32Array( 2 ),
  28713. 1, _controlInterpolantsResultBuffer );
  28714. interpolant.__cacheIndex = lastActiveIndex;
  28715. interpolants[ lastActiveIndex ] = interpolant;
  28716. }
  28717. return interpolant;
  28718. }
  28719. _takeBackControlInterpolant( interpolant ) {
  28720. const interpolants = this._controlInterpolants,
  28721. prevIndex = interpolant.__cacheIndex,
  28722. firstInactiveIndex = -- this._nActiveControlInterpolants,
  28723. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  28724. interpolant.__cacheIndex = firstInactiveIndex;
  28725. interpolants[ firstInactiveIndex ] = interpolant;
  28726. lastActiveInterpolant.__cacheIndex = prevIndex;
  28727. interpolants[ prevIndex ] = lastActiveInterpolant;
  28728. }
  28729. // return an action for a clip optionally using a custom root target
  28730. // object (this method allocates a lot of dynamic memory in case a
  28731. // previously unknown clip/root combination is specified)
  28732. clipAction( clip, optionalRoot, blendMode ) {
  28733. const root = optionalRoot || this._root,
  28734. rootUuid = root.uuid;
  28735. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  28736. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  28737. const actionsForClip = this._actionsByClip[ clipUuid ];
  28738. let prototypeAction = null;
  28739. if ( blendMode === undefined ) {
  28740. if ( clipObject !== null ) {
  28741. blendMode = clipObject.blendMode;
  28742. } else {
  28743. blendMode = NormalAnimationBlendMode;
  28744. }
  28745. }
  28746. if ( actionsForClip !== undefined ) {
  28747. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  28748. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  28749. return existingAction;
  28750. }
  28751. // we know the clip, so we don't have to parse all
  28752. // the bindings again but can just copy
  28753. prototypeAction = actionsForClip.knownActions[ 0 ];
  28754. // also, take the clip from the prototype action
  28755. if ( clipObject === null )
  28756. clipObject = prototypeAction._clip;
  28757. }
  28758. // clip must be known when specified via string
  28759. if ( clipObject === null ) return null;
  28760. // allocate all resources required to run it
  28761. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  28762. this._bindAction( newAction, prototypeAction );
  28763. // and make the action known to the memory manager
  28764. this._addInactiveAction( newAction, clipUuid, rootUuid );
  28765. return newAction;
  28766. }
  28767. // get an existing action
  28768. existingAction( clip, optionalRoot ) {
  28769. const root = optionalRoot || this._root,
  28770. rootUuid = root.uuid,
  28771. clipObject = typeof clip === 'string' ?
  28772. AnimationClip.findByName( root, clip ) : clip,
  28773. clipUuid = clipObject ? clipObject.uuid : clip,
  28774. actionsForClip = this._actionsByClip[ clipUuid ];
  28775. if ( actionsForClip !== undefined ) {
  28776. return actionsForClip.actionByRoot[ rootUuid ] || null;
  28777. }
  28778. return null;
  28779. }
  28780. // deactivates all previously scheduled actions
  28781. stopAllAction() {
  28782. const actions = this._actions,
  28783. nActions = this._nActiveActions;
  28784. for ( let i = nActions - 1; i >= 0; -- i ) {
  28785. actions[ i ].stop();
  28786. }
  28787. return this;
  28788. }
  28789. // advance the time and update apply the animation
  28790. update( deltaTime ) {
  28791. deltaTime *= this.timeScale;
  28792. const actions = this._actions,
  28793. nActions = this._nActiveActions,
  28794. time = this.time += deltaTime,
  28795. timeDirection = Math.sign( deltaTime ),
  28796. accuIndex = this._accuIndex ^= 1;
  28797. // run active actions
  28798. for ( let i = 0; i !== nActions; ++ i ) {
  28799. const action = actions[ i ];
  28800. action._update( time, deltaTime, timeDirection, accuIndex );
  28801. }
  28802. // update scene graph
  28803. const bindings = this._bindings,
  28804. nBindings = this._nActiveBindings;
  28805. for ( let i = 0; i !== nBindings; ++ i ) {
  28806. bindings[ i ].apply( accuIndex );
  28807. }
  28808. return this;
  28809. }
  28810. // Allows you to seek to a specific time in an animation.
  28811. setTime( timeInSeconds ) {
  28812. this.time = 0; // Zero out time attribute for AnimationMixer object;
  28813. for ( let i = 0; i < this._actions.length; i ++ ) {
  28814. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  28815. }
  28816. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  28817. }
  28818. // return this mixer's root target object
  28819. getRoot() {
  28820. return this._root;
  28821. }
  28822. // free all resources specific to a particular clip
  28823. uncacheClip( clip ) {
  28824. const actions = this._actions,
  28825. clipUuid = clip.uuid,
  28826. actionsByClip = this._actionsByClip,
  28827. actionsForClip = actionsByClip[ clipUuid ];
  28828. if ( actionsForClip !== undefined ) {
  28829. // note: just calling _removeInactiveAction would mess up the
  28830. // iteration state and also require updating the state we can
  28831. // just throw away
  28832. const actionsToRemove = actionsForClip.knownActions;
  28833. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  28834. const action = actionsToRemove[ i ];
  28835. this._deactivateAction( action );
  28836. const cacheIndex = action._cacheIndex,
  28837. lastInactiveAction = actions[ actions.length - 1 ];
  28838. action._cacheIndex = null;
  28839. action._byClipCacheIndex = null;
  28840. lastInactiveAction._cacheIndex = cacheIndex;
  28841. actions[ cacheIndex ] = lastInactiveAction;
  28842. actions.pop();
  28843. this._removeInactiveBindingsForAction( action );
  28844. }
  28845. delete actionsByClip[ clipUuid ];
  28846. }
  28847. }
  28848. // free all resources specific to a particular root target object
  28849. uncacheRoot( root ) {
  28850. const rootUuid = root.uuid,
  28851. actionsByClip = this._actionsByClip;
  28852. for ( const clipUuid in actionsByClip ) {
  28853. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  28854. action = actionByRoot[ rootUuid ];
  28855. if ( action !== undefined ) {
  28856. this._deactivateAction( action );
  28857. this._removeInactiveAction( action );
  28858. }
  28859. }
  28860. const bindingsByRoot = this._bindingsByRootAndName,
  28861. bindingByName = bindingsByRoot[ rootUuid ];
  28862. if ( bindingByName !== undefined ) {
  28863. for ( const trackName in bindingByName ) {
  28864. const binding = bindingByName[ trackName ];
  28865. binding.restoreOriginalState();
  28866. this._removeInactiveBinding( binding );
  28867. }
  28868. }
  28869. }
  28870. // remove a targeted clip from the cache
  28871. uncacheAction( clip, optionalRoot ) {
  28872. const action = this.existingAction( clip, optionalRoot );
  28873. if ( action !== null ) {
  28874. this._deactivateAction( action );
  28875. this._removeInactiveAction( action );
  28876. }
  28877. }
  28878. }
  28879. class Uniform {
  28880. constructor( value ) {
  28881. this.value = value;
  28882. }
  28883. clone() {
  28884. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  28885. }
  28886. }
  28887. let id = 0;
  28888. class UniformsGroup extends EventDispatcher {
  28889. constructor() {
  28890. super();
  28891. this.isUniformsGroup = true;
  28892. Object.defineProperty( this, 'id', { value: id ++ } );
  28893. this.name = '';
  28894. this.usage = StaticDrawUsage;
  28895. this.uniforms = [];
  28896. }
  28897. add( uniform ) {
  28898. this.uniforms.push( uniform );
  28899. return this;
  28900. }
  28901. remove( uniform ) {
  28902. const index = this.uniforms.indexOf( uniform );
  28903. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  28904. return this;
  28905. }
  28906. setName( name ) {
  28907. this.name = name;
  28908. return this;
  28909. }
  28910. setUsage( value ) {
  28911. this.usage = value;
  28912. return this;
  28913. }
  28914. dispose() {
  28915. this.dispatchEvent( { type: 'dispose' } );
  28916. return this;
  28917. }
  28918. copy( source ) {
  28919. this.name = source.name;
  28920. this.usage = source.usage;
  28921. const uniformsSource = source.uniforms;
  28922. this.uniforms.length = 0;
  28923. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  28924. this.uniforms.push( uniformsSource[ i ].clone() );
  28925. }
  28926. return this;
  28927. }
  28928. clone() {
  28929. return new this.constructor().copy( this );
  28930. }
  28931. }
  28932. class InstancedInterleavedBuffer extends InterleavedBuffer {
  28933. constructor( array, stride, meshPerAttribute = 1 ) {
  28934. super( array, stride );
  28935. this.isInstancedInterleavedBuffer = true;
  28936. this.meshPerAttribute = meshPerAttribute;
  28937. }
  28938. copy( source ) {
  28939. super.copy( source );
  28940. this.meshPerAttribute = source.meshPerAttribute;
  28941. return this;
  28942. }
  28943. clone( data ) {
  28944. const ib = super.clone( data );
  28945. ib.meshPerAttribute = this.meshPerAttribute;
  28946. return ib;
  28947. }
  28948. toJSON( data ) {
  28949. const json = super.toJSON( data );
  28950. json.isInstancedInterleavedBuffer = true;
  28951. json.meshPerAttribute = this.meshPerAttribute;
  28952. return json;
  28953. }
  28954. }
  28955. class GLBufferAttribute {
  28956. constructor( buffer, type, itemSize, elementSize, count ) {
  28957. this.isGLBufferAttribute = true;
  28958. this.name = '';
  28959. this.buffer = buffer;
  28960. this.type = type;
  28961. this.itemSize = itemSize;
  28962. this.elementSize = elementSize;
  28963. this.count = count;
  28964. this.version = 0;
  28965. }
  28966. set needsUpdate( value ) {
  28967. if ( value === true ) this.version ++;
  28968. }
  28969. setBuffer( buffer ) {
  28970. this.buffer = buffer;
  28971. return this;
  28972. }
  28973. setType( type, elementSize ) {
  28974. this.type = type;
  28975. this.elementSize = elementSize;
  28976. return this;
  28977. }
  28978. setItemSize( itemSize ) {
  28979. this.itemSize = itemSize;
  28980. return this;
  28981. }
  28982. setCount( count ) {
  28983. this.count = count;
  28984. return this;
  28985. }
  28986. }
  28987. class Raycaster {
  28988. constructor( origin, direction, near = 0, far = Infinity ) {
  28989. this.ray = new Ray( origin, direction );
  28990. // direction is assumed to be normalized (for accurate distance calculations)
  28991. this.near = near;
  28992. this.far = far;
  28993. this.camera = null;
  28994. this.layers = new Layers();
  28995. this.params = {
  28996. Mesh: {},
  28997. Line: { threshold: 1 },
  28998. LOD: {},
  28999. Points: { threshold: 1 },
  29000. Sprite: {}
  29001. };
  29002. }
  29003. set( origin, direction ) {
  29004. // direction is assumed to be normalized (for accurate distance calculations)
  29005. this.ray.set( origin, direction );
  29006. }
  29007. setFromCamera( coords, camera ) {
  29008. if ( camera.isPerspectiveCamera ) {
  29009. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  29010. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  29011. this.camera = camera;
  29012. } else if ( camera.isOrthographicCamera ) {
  29013. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  29014. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  29015. this.camera = camera;
  29016. } else {
  29017. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  29018. }
  29019. }
  29020. intersectObject( object, recursive = true, intersects = [] ) {
  29021. intersectObject( object, this, intersects, recursive );
  29022. intersects.sort( ascSort );
  29023. return intersects;
  29024. }
  29025. intersectObjects( objects, recursive = true, intersects = [] ) {
  29026. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  29027. intersectObject( objects[ i ], this, intersects, recursive );
  29028. }
  29029. intersects.sort( ascSort );
  29030. return intersects;
  29031. }
  29032. }
  29033. function ascSort( a, b ) {
  29034. return a.distance - b.distance;
  29035. }
  29036. function intersectObject( object, raycaster, intersects, recursive ) {
  29037. if ( object.layers.test( raycaster.layers ) ) {
  29038. object.raycast( raycaster, intersects );
  29039. }
  29040. if ( recursive === true ) {
  29041. const children = object.children;
  29042. for ( let i = 0, l = children.length; i < l; i ++ ) {
  29043. intersectObject( children[ i ], raycaster, intersects, true );
  29044. }
  29045. }
  29046. }
  29047. /**
  29048. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  29049. *
  29050. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  29051. * The azimuthal angle (theta) is measured from the positive z-axis.
  29052. */
  29053. class Spherical {
  29054. constructor( radius = 1, phi = 0, theta = 0 ) {
  29055. this.radius = radius;
  29056. this.phi = phi; // polar angle
  29057. this.theta = theta; // azimuthal angle
  29058. return this;
  29059. }
  29060. set( radius, phi, theta ) {
  29061. this.radius = radius;
  29062. this.phi = phi;
  29063. this.theta = theta;
  29064. return this;
  29065. }
  29066. copy( other ) {
  29067. this.radius = other.radius;
  29068. this.phi = other.phi;
  29069. this.theta = other.theta;
  29070. return this;
  29071. }
  29072. // restrict phi to be between EPS and PI-EPS
  29073. makeSafe() {
  29074. const EPS = 0.000001;
  29075. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  29076. return this;
  29077. }
  29078. setFromVector3( v ) {
  29079. return this.setFromCartesianCoords( v.x, v.y, v.z );
  29080. }
  29081. setFromCartesianCoords( x, y, z ) {
  29082. this.radius = Math.sqrt( x * x + y * y + z * z );
  29083. if ( this.radius === 0 ) {
  29084. this.theta = 0;
  29085. this.phi = 0;
  29086. } else {
  29087. this.theta = Math.atan2( x, z );
  29088. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  29089. }
  29090. return this;
  29091. }
  29092. clone() {
  29093. return new this.constructor().copy( this );
  29094. }
  29095. }
  29096. /**
  29097. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  29098. */
  29099. class Cylindrical {
  29100. constructor( radius = 1, theta = 0, y = 0 ) {
  29101. this.radius = radius; // distance from the origin to a point in the x-z plane
  29102. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  29103. this.y = y; // height above the x-z plane
  29104. return this;
  29105. }
  29106. set( radius, theta, y ) {
  29107. this.radius = radius;
  29108. this.theta = theta;
  29109. this.y = y;
  29110. return this;
  29111. }
  29112. copy( other ) {
  29113. this.radius = other.radius;
  29114. this.theta = other.theta;
  29115. this.y = other.y;
  29116. return this;
  29117. }
  29118. setFromVector3( v ) {
  29119. return this.setFromCartesianCoords( v.x, v.y, v.z );
  29120. }
  29121. setFromCartesianCoords( x, y, z ) {
  29122. this.radius = Math.sqrt( x * x + z * z );
  29123. this.theta = Math.atan2( x, z );
  29124. this.y = y;
  29125. return this;
  29126. }
  29127. clone() {
  29128. return new this.constructor().copy( this );
  29129. }
  29130. }
  29131. const _vector$4 = /*@__PURE__*/ new Vector2();
  29132. class Box2 {
  29133. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  29134. this.isBox2 = true;
  29135. this.min = min;
  29136. this.max = max;
  29137. }
  29138. set( min, max ) {
  29139. this.min.copy( min );
  29140. this.max.copy( max );
  29141. return this;
  29142. }
  29143. setFromPoints( points ) {
  29144. this.makeEmpty();
  29145. for ( let i = 0, il = points.length; i < il; i ++ ) {
  29146. this.expandByPoint( points[ i ] );
  29147. }
  29148. return this;
  29149. }
  29150. setFromCenterAndSize( center, size ) {
  29151. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  29152. this.min.copy( center ).sub( halfSize );
  29153. this.max.copy( center ).add( halfSize );
  29154. return this;
  29155. }
  29156. clone() {
  29157. return new this.constructor().copy( this );
  29158. }
  29159. copy( box ) {
  29160. this.min.copy( box.min );
  29161. this.max.copy( box.max );
  29162. return this;
  29163. }
  29164. makeEmpty() {
  29165. this.min.x = this.min.y = + Infinity;
  29166. this.max.x = this.max.y = - Infinity;
  29167. return this;
  29168. }
  29169. isEmpty() {
  29170. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  29171. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  29172. }
  29173. getCenter( target ) {
  29174. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  29175. }
  29176. getSize( target ) {
  29177. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  29178. }
  29179. expandByPoint( point ) {
  29180. this.min.min( point );
  29181. this.max.max( point );
  29182. return this;
  29183. }
  29184. expandByVector( vector ) {
  29185. this.min.sub( vector );
  29186. this.max.add( vector );
  29187. return this;
  29188. }
  29189. expandByScalar( scalar ) {
  29190. this.min.addScalar( - scalar );
  29191. this.max.addScalar( scalar );
  29192. return this;
  29193. }
  29194. containsPoint( point ) {
  29195. return point.x < this.min.x || point.x > this.max.x ||
  29196. point.y < this.min.y || point.y > this.max.y ? false : true;
  29197. }
  29198. containsBox( box ) {
  29199. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  29200. this.min.y <= box.min.y && box.max.y <= this.max.y;
  29201. }
  29202. getParameter( point, target ) {
  29203. // This can potentially have a divide by zero if the box
  29204. // has a size dimension of 0.
  29205. return target.set(
  29206. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  29207. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  29208. );
  29209. }
  29210. intersectsBox( box ) {
  29211. // using 4 splitting planes to rule out intersections
  29212. return box.max.x < this.min.x || box.min.x > this.max.x ||
  29213. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  29214. }
  29215. clampPoint( point, target ) {
  29216. return target.copy( point ).clamp( this.min, this.max );
  29217. }
  29218. distanceToPoint( point ) {
  29219. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  29220. }
  29221. intersect( box ) {
  29222. this.min.max( box.min );
  29223. this.max.min( box.max );
  29224. if ( this.isEmpty() ) this.makeEmpty();
  29225. return this;
  29226. }
  29227. union( box ) {
  29228. this.min.min( box.min );
  29229. this.max.max( box.max );
  29230. return this;
  29231. }
  29232. translate( offset ) {
  29233. this.min.add( offset );
  29234. this.max.add( offset );
  29235. return this;
  29236. }
  29237. equals( box ) {
  29238. return box.min.equals( this.min ) && box.max.equals( this.max );
  29239. }
  29240. }
  29241. const _startP = /*@__PURE__*/ new Vector3();
  29242. const _startEnd = /*@__PURE__*/ new Vector3();
  29243. class Line3 {
  29244. constructor( start = new Vector3(), end = new Vector3() ) {
  29245. this.start = start;
  29246. this.end = end;
  29247. }
  29248. set( start, end ) {
  29249. this.start.copy( start );
  29250. this.end.copy( end );
  29251. return this;
  29252. }
  29253. copy( line ) {
  29254. this.start.copy( line.start );
  29255. this.end.copy( line.end );
  29256. return this;
  29257. }
  29258. getCenter( target ) {
  29259. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  29260. }
  29261. delta( target ) {
  29262. return target.subVectors( this.end, this.start );
  29263. }
  29264. distanceSq() {
  29265. return this.start.distanceToSquared( this.end );
  29266. }
  29267. distance() {
  29268. return this.start.distanceTo( this.end );
  29269. }
  29270. at( t, target ) {
  29271. return this.delta( target ).multiplyScalar( t ).add( this.start );
  29272. }
  29273. closestPointToPointParameter( point, clampToLine ) {
  29274. _startP.subVectors( point, this.start );
  29275. _startEnd.subVectors( this.end, this.start );
  29276. const startEnd2 = _startEnd.dot( _startEnd );
  29277. const startEnd_startP = _startEnd.dot( _startP );
  29278. let t = startEnd_startP / startEnd2;
  29279. if ( clampToLine ) {
  29280. t = clamp( t, 0, 1 );
  29281. }
  29282. return t;
  29283. }
  29284. closestPointToPoint( point, clampToLine, target ) {
  29285. const t = this.closestPointToPointParameter( point, clampToLine );
  29286. return this.delta( target ).multiplyScalar( t ).add( this.start );
  29287. }
  29288. applyMatrix4( matrix ) {
  29289. this.start.applyMatrix4( matrix );
  29290. this.end.applyMatrix4( matrix );
  29291. return this;
  29292. }
  29293. equals( line ) {
  29294. return line.start.equals( this.start ) && line.end.equals( this.end );
  29295. }
  29296. clone() {
  29297. return new this.constructor().copy( this );
  29298. }
  29299. }
  29300. const _vector$3 = /*@__PURE__*/ new Vector3();
  29301. class SpotLightHelper extends Object3D {
  29302. constructor( light, color ) {
  29303. super();
  29304. this.light = light;
  29305. this.matrix = light.matrixWorld;
  29306. this.matrixAutoUpdate = false;
  29307. this.color = color;
  29308. this.type = 'SpotLightHelper';
  29309. const geometry = new BufferGeometry();
  29310. const positions = [
  29311. 0, 0, 0, 0, 0, 1,
  29312. 0, 0, 0, 1, 0, 1,
  29313. 0, 0, 0, - 1, 0, 1,
  29314. 0, 0, 0, 0, 1, 1,
  29315. 0, 0, 0, 0, - 1, 1
  29316. ];
  29317. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  29318. const p1 = ( i / l ) * Math.PI * 2;
  29319. const p2 = ( j / l ) * Math.PI * 2;
  29320. positions.push(
  29321. Math.cos( p1 ), Math.sin( p1 ), 1,
  29322. Math.cos( p2 ), Math.sin( p2 ), 1
  29323. );
  29324. }
  29325. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29326. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  29327. this.cone = new LineSegments( geometry, material );
  29328. this.add( this.cone );
  29329. this.update();
  29330. }
  29331. dispose() {
  29332. this.cone.geometry.dispose();
  29333. this.cone.material.dispose();
  29334. }
  29335. update() {
  29336. this.light.updateWorldMatrix( true, false );
  29337. this.light.target.updateWorldMatrix( true, false );
  29338. const coneLength = this.light.distance ? this.light.distance : 1000;
  29339. const coneWidth = coneLength * Math.tan( this.light.angle );
  29340. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  29341. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  29342. this.cone.lookAt( _vector$3 );
  29343. if ( this.color !== undefined ) {
  29344. this.cone.material.color.set( this.color );
  29345. } else {
  29346. this.cone.material.color.copy( this.light.color );
  29347. }
  29348. }
  29349. }
  29350. const _vector$2 = /*@__PURE__*/ new Vector3();
  29351. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  29352. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  29353. class SkeletonHelper extends LineSegments {
  29354. constructor( object ) {
  29355. const bones = getBoneList( object );
  29356. const geometry = new BufferGeometry();
  29357. const vertices = [];
  29358. const colors = [];
  29359. const color1 = new Color( 0, 0, 1 );
  29360. const color2 = new Color( 0, 1, 0 );
  29361. for ( let i = 0; i < bones.length; i ++ ) {
  29362. const bone = bones[ i ];
  29363. if ( bone.parent && bone.parent.isBone ) {
  29364. vertices.push( 0, 0, 0 );
  29365. vertices.push( 0, 0, 0 );
  29366. colors.push( color1.r, color1.g, color1.b );
  29367. colors.push( color2.r, color2.g, color2.b );
  29368. }
  29369. }
  29370. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29371. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29372. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  29373. super( geometry, material );
  29374. this.isSkeletonHelper = true;
  29375. this.type = 'SkeletonHelper';
  29376. this.root = object;
  29377. this.bones = bones;
  29378. this.matrix = object.matrixWorld;
  29379. this.matrixAutoUpdate = false;
  29380. }
  29381. updateMatrixWorld( force ) {
  29382. const bones = this.bones;
  29383. const geometry = this.geometry;
  29384. const position = geometry.getAttribute( 'position' );
  29385. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  29386. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  29387. const bone = bones[ i ];
  29388. if ( bone.parent && bone.parent.isBone ) {
  29389. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  29390. _vector$2.setFromMatrixPosition( _boneMatrix );
  29391. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  29392. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  29393. _vector$2.setFromMatrixPosition( _boneMatrix );
  29394. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  29395. j += 2;
  29396. }
  29397. }
  29398. geometry.getAttribute( 'position' ).needsUpdate = true;
  29399. super.updateMatrixWorld( force );
  29400. }
  29401. dispose() {
  29402. this.geometry.dispose();
  29403. this.material.dispose();
  29404. }
  29405. }
  29406. function getBoneList( object ) {
  29407. const boneList = [];
  29408. if ( object.isBone === true ) {
  29409. boneList.push( object );
  29410. }
  29411. for ( let i = 0; i < object.children.length; i ++ ) {
  29412. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  29413. }
  29414. return boneList;
  29415. }
  29416. class PointLightHelper extends Mesh {
  29417. constructor( light, sphereSize, color ) {
  29418. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  29419. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  29420. super( geometry, material );
  29421. this.light = light;
  29422. this.color = color;
  29423. this.type = 'PointLightHelper';
  29424. this.matrix = this.light.matrixWorld;
  29425. this.matrixAutoUpdate = false;
  29426. this.update();
  29427. /*
  29428. // TODO: delete this comment?
  29429. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  29430. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  29431. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  29432. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  29433. const d = light.distance;
  29434. if ( d === 0.0 ) {
  29435. this.lightDistance.visible = false;
  29436. } else {
  29437. this.lightDistance.scale.set( d, d, d );
  29438. }
  29439. this.add( this.lightDistance );
  29440. */
  29441. }
  29442. dispose() {
  29443. this.geometry.dispose();
  29444. this.material.dispose();
  29445. }
  29446. update() {
  29447. this.light.updateWorldMatrix( true, false );
  29448. if ( this.color !== undefined ) {
  29449. this.material.color.set( this.color );
  29450. } else {
  29451. this.material.color.copy( this.light.color );
  29452. }
  29453. /*
  29454. const d = this.light.distance;
  29455. if ( d === 0.0 ) {
  29456. this.lightDistance.visible = false;
  29457. } else {
  29458. this.lightDistance.visible = true;
  29459. this.lightDistance.scale.set( d, d, d );
  29460. }
  29461. */
  29462. }
  29463. }
  29464. const _vector$1 = /*@__PURE__*/ new Vector3();
  29465. const _color1 = /*@__PURE__*/ new Color();
  29466. const _color2 = /*@__PURE__*/ new Color();
  29467. class HemisphereLightHelper extends Object3D {
  29468. constructor( light, size, color ) {
  29469. super();
  29470. this.light = light;
  29471. this.matrix = light.matrixWorld;
  29472. this.matrixAutoUpdate = false;
  29473. this.color = color;
  29474. this.type = 'HemisphereLightHelper';
  29475. const geometry = new OctahedronGeometry( size );
  29476. geometry.rotateY( Math.PI * 0.5 );
  29477. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  29478. if ( this.color === undefined ) this.material.vertexColors = true;
  29479. const position = geometry.getAttribute( 'position' );
  29480. const colors = new Float32Array( position.count * 3 );
  29481. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  29482. this.add( new Mesh( geometry, this.material ) );
  29483. this.update();
  29484. }
  29485. dispose() {
  29486. this.children[ 0 ].geometry.dispose();
  29487. this.children[ 0 ].material.dispose();
  29488. }
  29489. update() {
  29490. const mesh = this.children[ 0 ];
  29491. if ( this.color !== undefined ) {
  29492. this.material.color.set( this.color );
  29493. } else {
  29494. const colors = mesh.geometry.getAttribute( 'color' );
  29495. _color1.copy( this.light.color );
  29496. _color2.copy( this.light.groundColor );
  29497. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  29498. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  29499. colors.setXYZ( i, color.r, color.g, color.b );
  29500. }
  29501. colors.needsUpdate = true;
  29502. }
  29503. this.light.updateWorldMatrix( true, false );
  29504. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  29505. }
  29506. }
  29507. class GridHelper extends LineSegments {
  29508. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  29509. color1 = new Color( color1 );
  29510. color2 = new Color( color2 );
  29511. const center = divisions / 2;
  29512. const step = size / divisions;
  29513. const halfSize = size / 2;
  29514. const vertices = [], colors = [];
  29515. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  29516. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  29517. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  29518. const color = i === center ? color1 : color2;
  29519. color.toArray( colors, j ); j += 3;
  29520. color.toArray( colors, j ); j += 3;
  29521. color.toArray( colors, j ); j += 3;
  29522. color.toArray( colors, j ); j += 3;
  29523. }
  29524. const geometry = new BufferGeometry();
  29525. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29526. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29527. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29528. super( geometry, material );
  29529. this.type = 'GridHelper';
  29530. }
  29531. dispose() {
  29532. this.geometry.dispose();
  29533. this.material.dispose();
  29534. }
  29535. }
  29536. class PolarGridHelper extends LineSegments {
  29537. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  29538. color1 = new Color( color1 );
  29539. color2 = new Color( color2 );
  29540. const vertices = [];
  29541. const colors = [];
  29542. // create the sectors
  29543. if ( sectors > 1 ) {
  29544. for ( let i = 0; i < sectors; i ++ ) {
  29545. const v = ( i / sectors ) * ( Math.PI * 2 );
  29546. const x = Math.sin( v ) * radius;
  29547. const z = Math.cos( v ) * radius;
  29548. vertices.push( 0, 0, 0 );
  29549. vertices.push( x, 0, z );
  29550. const color = ( i & 1 ) ? color1 : color2;
  29551. colors.push( color.r, color.g, color.b );
  29552. colors.push( color.r, color.g, color.b );
  29553. }
  29554. }
  29555. // create the rings
  29556. for ( let i = 0; i < rings; i ++ ) {
  29557. const color = ( i & 1 ) ? color1 : color2;
  29558. const r = radius - ( radius / rings * i );
  29559. for ( let j = 0; j < divisions; j ++ ) {
  29560. // first vertex
  29561. let v = ( j / divisions ) * ( Math.PI * 2 );
  29562. let x = Math.sin( v ) * r;
  29563. let z = Math.cos( v ) * r;
  29564. vertices.push( x, 0, z );
  29565. colors.push( color.r, color.g, color.b );
  29566. // second vertex
  29567. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  29568. x = Math.sin( v ) * r;
  29569. z = Math.cos( v ) * r;
  29570. vertices.push( x, 0, z );
  29571. colors.push( color.r, color.g, color.b );
  29572. }
  29573. }
  29574. const geometry = new BufferGeometry();
  29575. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29576. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29577. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29578. super( geometry, material );
  29579. this.type = 'PolarGridHelper';
  29580. }
  29581. dispose() {
  29582. this.geometry.dispose();
  29583. this.material.dispose();
  29584. }
  29585. }
  29586. const _v1 = /*@__PURE__*/ new Vector3();
  29587. const _v2 = /*@__PURE__*/ new Vector3();
  29588. const _v3 = /*@__PURE__*/ new Vector3();
  29589. class DirectionalLightHelper extends Object3D {
  29590. constructor( light, size, color ) {
  29591. super();
  29592. this.light = light;
  29593. this.matrix = light.matrixWorld;
  29594. this.matrixAutoUpdate = false;
  29595. this.color = color;
  29596. this.type = 'DirectionalLightHelper';
  29597. if ( size === undefined ) size = 1;
  29598. let geometry = new BufferGeometry();
  29599. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  29600. - size, size, 0,
  29601. size, size, 0,
  29602. size, - size, 0,
  29603. - size, - size, 0,
  29604. - size, size, 0
  29605. ], 3 ) );
  29606. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  29607. this.lightPlane = new Line( geometry, material );
  29608. this.add( this.lightPlane );
  29609. geometry = new BufferGeometry();
  29610. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  29611. this.targetLine = new Line( geometry, material );
  29612. this.add( this.targetLine );
  29613. this.update();
  29614. }
  29615. dispose() {
  29616. this.lightPlane.geometry.dispose();
  29617. this.lightPlane.material.dispose();
  29618. this.targetLine.geometry.dispose();
  29619. this.targetLine.material.dispose();
  29620. }
  29621. update() {
  29622. this.light.updateWorldMatrix( true, false );
  29623. this.light.target.updateWorldMatrix( true, false );
  29624. _v1.setFromMatrixPosition( this.light.matrixWorld );
  29625. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  29626. _v3.subVectors( _v2, _v1 );
  29627. this.lightPlane.lookAt( _v2 );
  29628. if ( this.color !== undefined ) {
  29629. this.lightPlane.material.color.set( this.color );
  29630. this.targetLine.material.color.set( this.color );
  29631. } else {
  29632. this.lightPlane.material.color.copy( this.light.color );
  29633. this.targetLine.material.color.copy( this.light.color );
  29634. }
  29635. this.targetLine.lookAt( _v2 );
  29636. this.targetLine.scale.z = _v3.length();
  29637. }
  29638. }
  29639. const _vector = /*@__PURE__*/ new Vector3();
  29640. const _camera = /*@__PURE__*/ new Camera();
  29641. /**
  29642. * - shows frustum, line of sight and up of the camera
  29643. * - suitable for fast updates
  29644. * - based on frustum visualization in lightgl.js shadowmap example
  29645. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  29646. */
  29647. class CameraHelper extends LineSegments {
  29648. constructor( camera ) {
  29649. const geometry = new BufferGeometry();
  29650. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  29651. const vertices = [];
  29652. const colors = [];
  29653. const pointMap = {};
  29654. // near
  29655. addLine( 'n1', 'n2' );
  29656. addLine( 'n2', 'n4' );
  29657. addLine( 'n4', 'n3' );
  29658. addLine( 'n3', 'n1' );
  29659. // far
  29660. addLine( 'f1', 'f2' );
  29661. addLine( 'f2', 'f4' );
  29662. addLine( 'f4', 'f3' );
  29663. addLine( 'f3', 'f1' );
  29664. // sides
  29665. addLine( 'n1', 'f1' );
  29666. addLine( 'n2', 'f2' );
  29667. addLine( 'n3', 'f3' );
  29668. addLine( 'n4', 'f4' );
  29669. // cone
  29670. addLine( 'p', 'n1' );
  29671. addLine( 'p', 'n2' );
  29672. addLine( 'p', 'n3' );
  29673. addLine( 'p', 'n4' );
  29674. // up
  29675. addLine( 'u1', 'u2' );
  29676. addLine( 'u2', 'u3' );
  29677. addLine( 'u3', 'u1' );
  29678. // target
  29679. addLine( 'c', 't' );
  29680. addLine( 'p', 'c' );
  29681. // cross
  29682. addLine( 'cn1', 'cn2' );
  29683. addLine( 'cn3', 'cn4' );
  29684. addLine( 'cf1', 'cf2' );
  29685. addLine( 'cf3', 'cf4' );
  29686. function addLine( a, b ) {
  29687. addPoint( a );
  29688. addPoint( b );
  29689. }
  29690. function addPoint( id ) {
  29691. vertices.push( 0, 0, 0 );
  29692. colors.push( 0, 0, 0 );
  29693. if ( pointMap[ id ] === undefined ) {
  29694. pointMap[ id ] = [];
  29695. }
  29696. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  29697. }
  29698. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29699. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29700. super( geometry, material );
  29701. this.type = 'CameraHelper';
  29702. this.camera = camera;
  29703. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  29704. this.matrix = camera.matrixWorld;
  29705. this.matrixAutoUpdate = false;
  29706. this.pointMap = pointMap;
  29707. this.update();
  29708. // colors
  29709. const colorFrustum = new Color( 0xffaa00 );
  29710. const colorCone = new Color( 0xff0000 );
  29711. const colorUp = new Color( 0x00aaff );
  29712. const colorTarget = new Color( 0xffffff );
  29713. const colorCross = new Color( 0x333333 );
  29714. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  29715. }
  29716. setColors( frustum, cone, up, target, cross ) {
  29717. const geometry = this.geometry;
  29718. const colorAttribute = geometry.getAttribute( 'color' );
  29719. // near
  29720. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  29721. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  29722. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  29723. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  29724. // far
  29725. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  29726. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  29727. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  29728. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  29729. // sides
  29730. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  29731. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  29732. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  29733. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  29734. // cone
  29735. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  29736. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  29737. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  29738. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  29739. // up
  29740. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  29741. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  29742. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  29743. // target
  29744. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  29745. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  29746. // cross
  29747. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  29748. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  29749. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  29750. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  29751. colorAttribute.needsUpdate = true;
  29752. }
  29753. update() {
  29754. const geometry = this.geometry;
  29755. const pointMap = this.pointMap;
  29756. const w = 1, h = 1;
  29757. // we need just camera projection matrix inverse
  29758. // world matrix must be identity
  29759. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  29760. // center / target
  29761. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  29762. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  29763. // near
  29764. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  29765. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  29766. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  29767. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  29768. // far
  29769. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  29770. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  29771. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  29772. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  29773. // up
  29774. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  29775. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  29776. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  29777. // cross
  29778. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  29779. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  29780. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  29781. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  29782. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  29783. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  29784. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  29785. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  29786. geometry.getAttribute( 'position' ).needsUpdate = true;
  29787. }
  29788. dispose() {
  29789. this.geometry.dispose();
  29790. this.material.dispose();
  29791. }
  29792. }
  29793. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  29794. _vector.set( x, y, z ).unproject( camera );
  29795. const points = pointMap[ point ];
  29796. if ( points !== undefined ) {
  29797. const position = geometry.getAttribute( 'position' );
  29798. for ( let i = 0, l = points.length; i < l; i ++ ) {
  29799. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  29800. }
  29801. }
  29802. }
  29803. const _box = /*@__PURE__*/ new Box3();
  29804. class BoxHelper extends LineSegments {
  29805. constructor( object, color = 0xffff00 ) {
  29806. 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 ] );
  29807. const positions = new Float32Array( 8 * 3 );
  29808. const geometry = new BufferGeometry();
  29809. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29810. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  29811. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29812. this.object = object;
  29813. this.type = 'BoxHelper';
  29814. this.matrixAutoUpdate = false;
  29815. this.update();
  29816. }
  29817. update( object ) {
  29818. if ( object !== undefined ) {
  29819. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  29820. }
  29821. if ( this.object !== undefined ) {
  29822. _box.setFromObject( this.object );
  29823. }
  29824. if ( _box.isEmpty() ) return;
  29825. const min = _box.min;
  29826. const max = _box.max;
  29827. /*
  29828. 5____4
  29829. 1/___0/|
  29830. | 6__|_7
  29831. 2/___3/
  29832. 0: max.x, max.y, max.z
  29833. 1: min.x, max.y, max.z
  29834. 2: min.x, min.y, max.z
  29835. 3: max.x, min.y, max.z
  29836. 4: max.x, max.y, min.z
  29837. 5: min.x, max.y, min.z
  29838. 6: min.x, min.y, min.z
  29839. 7: max.x, min.y, min.z
  29840. */
  29841. const position = this.geometry.attributes.position;
  29842. const array = position.array;
  29843. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  29844. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  29845. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  29846. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  29847. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  29848. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  29849. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  29850. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  29851. position.needsUpdate = true;
  29852. this.geometry.computeBoundingSphere();
  29853. }
  29854. setFromObject( object ) {
  29855. this.object = object;
  29856. this.update();
  29857. return this;
  29858. }
  29859. copy( source, recursive ) {
  29860. super.copy( source, recursive );
  29861. this.object = source.object;
  29862. return this;
  29863. }
  29864. dispose() {
  29865. this.geometry.dispose();
  29866. this.material.dispose();
  29867. }
  29868. }
  29869. class Box3Helper extends LineSegments {
  29870. constructor( box, color = 0xffff00 ) {
  29871. 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 ] );
  29872. 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 ];
  29873. const geometry = new BufferGeometry();
  29874. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29875. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29876. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29877. this.box = box;
  29878. this.type = 'Box3Helper';
  29879. this.geometry.computeBoundingSphere();
  29880. }
  29881. updateMatrixWorld( force ) {
  29882. const box = this.box;
  29883. if ( box.isEmpty() ) return;
  29884. box.getCenter( this.position );
  29885. box.getSize( this.scale );
  29886. this.scale.multiplyScalar( 0.5 );
  29887. super.updateMatrixWorld( force );
  29888. }
  29889. dispose() {
  29890. this.geometry.dispose();
  29891. this.material.dispose();
  29892. }
  29893. }
  29894. class PlaneHelper extends Line {
  29895. constructor( plane, size = 1, hex = 0xffff00 ) {
  29896. const color = hex;
  29897. 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 ];
  29898. const geometry = new BufferGeometry();
  29899. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29900. geometry.computeBoundingSphere();
  29901. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29902. this.type = 'PlaneHelper';
  29903. this.plane = plane;
  29904. this.size = size;
  29905. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  29906. const geometry2 = new BufferGeometry();
  29907. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  29908. geometry2.computeBoundingSphere();
  29909. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  29910. }
  29911. updateMatrixWorld( force ) {
  29912. this.position.set( 0, 0, 0 );
  29913. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  29914. this.lookAt( this.plane.normal );
  29915. this.translateZ( - this.plane.constant );
  29916. super.updateMatrixWorld( force );
  29917. }
  29918. dispose() {
  29919. this.geometry.dispose();
  29920. this.material.dispose();
  29921. this.children[ 0 ].geometry.dispose();
  29922. this.children[ 0 ].material.dispose();
  29923. }
  29924. }
  29925. const _axis = /*@__PURE__*/ new Vector3();
  29926. let _lineGeometry, _coneGeometry;
  29927. class ArrowHelper extends Object3D {
  29928. // dir is assumed to be normalized
  29929. 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 ) {
  29930. super();
  29931. this.type = 'ArrowHelper';
  29932. if ( _lineGeometry === undefined ) {
  29933. _lineGeometry = new BufferGeometry();
  29934. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  29935. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  29936. _coneGeometry.translate( 0, - 0.5, 0 );
  29937. }
  29938. this.position.copy( origin );
  29939. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29940. this.line.matrixAutoUpdate = false;
  29941. this.add( this.line );
  29942. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  29943. this.cone.matrixAutoUpdate = false;
  29944. this.add( this.cone );
  29945. this.setDirection( dir );
  29946. this.setLength( length, headLength, headWidth );
  29947. }
  29948. setDirection( dir ) {
  29949. // dir is assumed to be normalized
  29950. if ( dir.y > 0.99999 ) {
  29951. this.quaternion.set( 0, 0, 0, 1 );
  29952. } else if ( dir.y < - 0.99999 ) {
  29953. this.quaternion.set( 1, 0, 0, 0 );
  29954. } else {
  29955. _axis.set( dir.z, 0, - dir.x ).normalize();
  29956. const radians = Math.acos( dir.y );
  29957. this.quaternion.setFromAxisAngle( _axis, radians );
  29958. }
  29959. }
  29960. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  29961. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  29962. this.line.updateMatrix();
  29963. this.cone.scale.set( headWidth, headLength, headWidth );
  29964. this.cone.position.y = length;
  29965. this.cone.updateMatrix();
  29966. }
  29967. setColor( color ) {
  29968. this.line.material.color.set( color );
  29969. this.cone.material.color.set( color );
  29970. }
  29971. copy( source ) {
  29972. super.copy( source, false );
  29973. this.line.copy( source.line );
  29974. this.cone.copy( source.cone );
  29975. return this;
  29976. }
  29977. dispose() {
  29978. this.line.geometry.dispose();
  29979. this.line.material.dispose();
  29980. this.cone.geometry.dispose();
  29981. this.cone.material.dispose();
  29982. }
  29983. }
  29984. class AxesHelper extends LineSegments {
  29985. constructor( size = 1 ) {
  29986. const vertices = [
  29987. 0, 0, 0, size, 0, 0,
  29988. 0, 0, 0, 0, size, 0,
  29989. 0, 0, 0, 0, 0, size
  29990. ];
  29991. const colors = [
  29992. 1, 0, 0, 1, 0.6, 0,
  29993. 0, 1, 0, 0.6, 1, 0,
  29994. 0, 0, 1, 0, 0.6, 1
  29995. ];
  29996. const geometry = new BufferGeometry();
  29997. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29998. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29999. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  30000. super( geometry, material );
  30001. this.type = 'AxesHelper';
  30002. }
  30003. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  30004. const color = new Color();
  30005. const array = this.geometry.attributes.color.array;
  30006. color.set( xAxisColor );
  30007. color.toArray( array, 0 );
  30008. color.toArray( array, 3 );
  30009. color.set( yAxisColor );
  30010. color.toArray( array, 6 );
  30011. color.toArray( array, 9 );
  30012. color.set( zAxisColor );
  30013. color.toArray( array, 12 );
  30014. color.toArray( array, 15 );
  30015. this.geometry.attributes.color.needsUpdate = true;
  30016. return this;
  30017. }
  30018. dispose() {
  30019. this.geometry.dispose();
  30020. this.material.dispose();
  30021. }
  30022. }
  30023. class ShapePath {
  30024. constructor() {
  30025. this.type = 'ShapePath';
  30026. this.color = new Color();
  30027. this.subPaths = [];
  30028. this.currentPath = null;
  30029. }
  30030. moveTo( x, y ) {
  30031. this.currentPath = new Path();
  30032. this.subPaths.push( this.currentPath );
  30033. this.currentPath.moveTo( x, y );
  30034. return this;
  30035. }
  30036. lineTo( x, y ) {
  30037. this.currentPath.lineTo( x, y );
  30038. return this;
  30039. }
  30040. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  30041. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  30042. return this;
  30043. }
  30044. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  30045. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  30046. return this;
  30047. }
  30048. splineThru( pts ) {
  30049. this.currentPath.splineThru( pts );
  30050. return this;
  30051. }
  30052. toShapes( isCCW ) {
  30053. function toShapesNoHoles( inSubpaths ) {
  30054. const shapes = [];
  30055. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  30056. const tmpPath = inSubpaths[ i ];
  30057. const tmpShape = new Shape();
  30058. tmpShape.curves = tmpPath.curves;
  30059. shapes.push( tmpShape );
  30060. }
  30061. return shapes;
  30062. }
  30063. function isPointInsidePolygon( inPt, inPolygon ) {
  30064. const polyLen = inPolygon.length;
  30065. // inPt on polygon contour => immediate success or
  30066. // toggling of inside/outside at every single! intersection point of an edge
  30067. // with the horizontal line through inPt, left of inPt
  30068. // not counting lowerY endpoints of edges and whole edges on that line
  30069. let inside = false;
  30070. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  30071. let edgeLowPt = inPolygon[ p ];
  30072. let edgeHighPt = inPolygon[ q ];
  30073. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  30074. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  30075. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  30076. // not parallel
  30077. if ( edgeDy < 0 ) {
  30078. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  30079. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  30080. }
  30081. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  30082. if ( inPt.y === edgeLowPt.y ) {
  30083. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  30084. // continue; // no intersection or edgeLowPt => doesn't count !!!
  30085. } else {
  30086. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  30087. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  30088. if ( perpEdge < 0 ) continue;
  30089. inside = ! inside; // true intersection left of inPt
  30090. }
  30091. } else {
  30092. // parallel or collinear
  30093. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  30094. // edge lies on the same horizontal line as inPt
  30095. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  30096. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  30097. // continue;
  30098. }
  30099. }
  30100. return inside;
  30101. }
  30102. const isClockWise = ShapeUtils.isClockWise;
  30103. const subPaths = this.subPaths;
  30104. if ( subPaths.length === 0 ) return [];
  30105. let solid, tmpPath, tmpShape;
  30106. const shapes = [];
  30107. if ( subPaths.length === 1 ) {
  30108. tmpPath = subPaths[ 0 ];
  30109. tmpShape = new Shape();
  30110. tmpShape.curves = tmpPath.curves;
  30111. shapes.push( tmpShape );
  30112. return shapes;
  30113. }
  30114. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  30115. holesFirst = isCCW ? ! holesFirst : holesFirst;
  30116. // console.log("Holes first", holesFirst);
  30117. const betterShapeHoles = [];
  30118. const newShapes = [];
  30119. let newShapeHoles = [];
  30120. let mainIdx = 0;
  30121. let tmpPoints;
  30122. newShapes[ mainIdx ] = undefined;
  30123. newShapeHoles[ mainIdx ] = [];
  30124. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  30125. tmpPath = subPaths[ i ];
  30126. tmpPoints = tmpPath.getPoints();
  30127. solid = isClockWise( tmpPoints );
  30128. solid = isCCW ? ! solid : solid;
  30129. if ( solid ) {
  30130. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  30131. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  30132. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  30133. if ( holesFirst ) mainIdx ++;
  30134. newShapeHoles[ mainIdx ] = [];
  30135. //console.log('cw', i);
  30136. } else {
  30137. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  30138. //console.log('ccw', i);
  30139. }
  30140. }
  30141. // only Holes? -> probably all Shapes with wrong orientation
  30142. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  30143. if ( newShapes.length > 1 ) {
  30144. let ambiguous = false;
  30145. let toChange = 0;
  30146. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  30147. betterShapeHoles[ sIdx ] = [];
  30148. }
  30149. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  30150. const sho = newShapeHoles[ sIdx ];
  30151. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  30152. const ho = sho[ hIdx ];
  30153. let hole_unassigned = true;
  30154. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  30155. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  30156. if ( sIdx !== s2Idx ) toChange ++;
  30157. if ( hole_unassigned ) {
  30158. hole_unassigned = false;
  30159. betterShapeHoles[ s2Idx ].push( ho );
  30160. } else {
  30161. ambiguous = true;
  30162. }
  30163. }
  30164. }
  30165. if ( hole_unassigned ) {
  30166. betterShapeHoles[ sIdx ].push( ho );
  30167. }
  30168. }
  30169. }
  30170. if ( toChange > 0 && ambiguous === false ) {
  30171. newShapeHoles = betterShapeHoles;
  30172. }
  30173. }
  30174. let tmpHoles;
  30175. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  30176. tmpShape = newShapes[ i ].s;
  30177. shapes.push( tmpShape );
  30178. tmpHoles = newShapeHoles[ i ];
  30179. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  30180. tmpShape.holes.push( tmpHoles[ j ].h );
  30181. }
  30182. }
  30183. //console.log("shape", shapes);
  30184. return shapes;
  30185. }
  30186. }
  30187. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  30188. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  30189. revision: REVISION,
  30190. } } ) );
  30191. }
  30192. if ( typeof window !== 'undefined' ) {
  30193. if ( window.__THREE__ ) {
  30194. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  30195. } else {
  30196. window.__THREE__ = REVISION;
  30197. }
  30198. }
  30199. export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightProbe, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BackSide, BasicDepthPacking, BasicShadowMap, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, ColorManagement, CompressedArrayTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderGeometry, Cylindrical, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DisplayP3ColorSpace, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, EqualCompare, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Float32BufferAttribute, Float64BufferAttribute, FloatType, Fog, FogExp2, FramebufferTexture, FrontSide, Frustum, GLBufferAttribute, GLSL1, GLSL3, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightProbe, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, KeepStencilOp, KeyframeTrack, LOD, LatheGeometry, Layers, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LineSegments, 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, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronGeometry, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, PMREMGenerator, Path, PerspectiveCamera, Plane, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_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, RingGeometry, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, Scene, ShaderChunk, ShaderLib, ShaderMaterial, ShadowMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronGeometry, Texture, TextureLoader, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, TwoPassDoubleSide, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, UniformsLib, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, VideoTexture, WebGL1Renderer, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLRenderTarget, WebGLRenderer, WebGLUtils, WebGPUCoordinateSystem, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, _SRGBAFormat, sRGBEncoding };