three.module.js 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627
  1. /**
  2. * @license
  3. * Copyright 2010-2023 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '151dev';
  7. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  8. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  9. const CullFaceNone = 0;
  10. const CullFaceBack = 1;
  11. const CullFaceFront = 2;
  12. const CullFaceFrontBack = 3;
  13. const BasicShadowMap = 0;
  14. const PCFShadowMap = 1;
  15. const PCFSoftShadowMap = 2;
  16. const VSMShadowMap = 3;
  17. const FrontSide = 0;
  18. const BackSide = 1;
  19. const DoubleSide = 2;
  20. const TwoPassDoubleSide = 2; // r149
  21. const NoBlending = 0;
  22. const NormalBlending = 1;
  23. const AdditiveBlending = 2;
  24. const SubtractiveBlending = 3;
  25. const MultiplyBlending = 4;
  26. const CustomBlending = 5;
  27. const AddEquation = 100;
  28. const SubtractEquation = 101;
  29. const ReverseSubtractEquation = 102;
  30. const MinEquation = 103;
  31. const MaxEquation = 104;
  32. const ZeroFactor = 200;
  33. const OneFactor = 201;
  34. const SrcColorFactor = 202;
  35. const OneMinusSrcColorFactor = 203;
  36. const SrcAlphaFactor = 204;
  37. const OneMinusSrcAlphaFactor = 205;
  38. const DstAlphaFactor = 206;
  39. const OneMinusDstAlphaFactor = 207;
  40. const DstColorFactor = 208;
  41. const OneMinusDstColorFactor = 209;
  42. const SrcAlphaSaturateFactor = 210;
  43. const NeverDepth = 0;
  44. const AlwaysDepth = 1;
  45. const LessDepth = 2;
  46. const LessEqualDepth = 3;
  47. const EqualDepth = 4;
  48. const GreaterEqualDepth = 5;
  49. const GreaterDepth = 6;
  50. const NotEqualDepth = 7;
  51. const MultiplyOperation = 0;
  52. const MixOperation = 1;
  53. const AddOperation = 2;
  54. const NoToneMapping = 0;
  55. const LinearToneMapping = 1;
  56. const ReinhardToneMapping = 2;
  57. const CineonToneMapping = 3;
  58. const ACESFilmicToneMapping = 4;
  59. const CustomToneMapping = 5;
  60. const UVMapping = 300;
  61. const CubeReflectionMapping = 301;
  62. const CubeRefractionMapping = 302;
  63. const EquirectangularReflectionMapping = 303;
  64. const EquirectangularRefractionMapping = 304;
  65. const CubeUVReflectionMapping = 306;
  66. const RepeatWrapping = 1000;
  67. const ClampToEdgeWrapping = 1001;
  68. const MirroredRepeatWrapping = 1002;
  69. const NearestFilter = 1003;
  70. const NearestMipmapNearestFilter = 1004;
  71. const NearestMipMapNearestFilter = 1004;
  72. const NearestMipmapLinearFilter = 1005;
  73. const NearestMipMapLinearFilter = 1005;
  74. const LinearFilter = 1006;
  75. const LinearMipmapNearestFilter = 1007;
  76. const LinearMipMapNearestFilter = 1007;
  77. const LinearMipmapLinearFilter = 1008;
  78. const LinearMipMapLinearFilter = 1008;
  79. const UnsignedByteType = 1009;
  80. const ByteType = 1010;
  81. const ShortType = 1011;
  82. const UnsignedShortType = 1012;
  83. const IntType = 1013;
  84. const UnsignedIntType = 1014;
  85. const FloatType = 1015;
  86. const HalfFloatType = 1016;
  87. const UnsignedShort4444Type = 1017;
  88. const UnsignedShort5551Type = 1018;
  89. const UnsignedInt248Type = 1020;
  90. const AlphaFormat = 1021;
  91. const RGBAFormat = 1023;
  92. const LuminanceFormat = 1024;
  93. const LuminanceAlphaFormat = 1025;
  94. const DepthFormat = 1026;
  95. const DepthStencilFormat = 1027;
  96. const RedFormat = 1028;
  97. const RedIntegerFormat = 1029;
  98. const RGFormat = 1030;
  99. const RGIntegerFormat = 1031;
  100. const RGBAIntegerFormat = 1033;
  101. const RGB_S3TC_DXT1_Format = 33776;
  102. const RGBA_S3TC_DXT1_Format = 33777;
  103. const RGBA_S3TC_DXT3_Format = 33778;
  104. const RGBA_S3TC_DXT5_Format = 33779;
  105. const RGB_PVRTC_4BPPV1_Format = 35840;
  106. const RGB_PVRTC_2BPPV1_Format = 35841;
  107. const RGBA_PVRTC_4BPPV1_Format = 35842;
  108. const RGBA_PVRTC_2BPPV1_Format = 35843;
  109. const RGB_ETC1_Format = 36196;
  110. const RGB_ETC2_Format = 37492;
  111. const RGBA_ETC2_EAC_Format = 37496;
  112. const RGBA_ASTC_4x4_Format = 37808;
  113. const RGBA_ASTC_5x4_Format = 37809;
  114. const RGBA_ASTC_5x5_Format = 37810;
  115. const RGBA_ASTC_6x5_Format = 37811;
  116. const RGBA_ASTC_6x6_Format = 37812;
  117. const RGBA_ASTC_8x5_Format = 37813;
  118. const RGBA_ASTC_8x6_Format = 37814;
  119. const RGBA_ASTC_8x8_Format = 37815;
  120. const RGBA_ASTC_10x5_Format = 37816;
  121. const RGBA_ASTC_10x6_Format = 37817;
  122. const RGBA_ASTC_10x8_Format = 37818;
  123. const RGBA_ASTC_10x10_Format = 37819;
  124. const RGBA_ASTC_12x10_Format = 37820;
  125. const RGBA_ASTC_12x12_Format = 37821;
  126. const RGBA_BPTC_Format = 36492;
  127. const RED_RGTC1_Format = 36283;
  128. const SIGNED_RED_RGTC1_Format = 36284;
  129. const RED_GREEN_RGTC2_Format = 36285;
  130. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  131. const LoopOnce = 2200;
  132. const LoopRepeat = 2201;
  133. const LoopPingPong = 2202;
  134. const InterpolateDiscrete = 2300;
  135. const InterpolateLinear = 2301;
  136. const InterpolateSmooth = 2302;
  137. const ZeroCurvatureEnding = 2400;
  138. const ZeroSlopeEnding = 2401;
  139. const WrapAroundEnding = 2402;
  140. const NormalAnimationBlendMode = 2500;
  141. const AdditiveAnimationBlendMode = 2501;
  142. const TrianglesDrawMode = 0;
  143. const TriangleStripDrawMode = 1;
  144. const TriangleFanDrawMode = 2;
  145. const LinearEncoding = 3000;
  146. const sRGBEncoding = 3001;
  147. const BasicDepthPacking = 3200;
  148. const RGBADepthPacking = 3201;
  149. const TangentSpaceNormalMap = 0;
  150. const ObjectSpaceNormalMap = 1;
  151. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  152. const NoColorSpace = '';
  153. const SRGBColorSpace = 'srgb';
  154. const LinearSRGBColorSpace = 'srgb-linear';
  155. const DisplayP3ColorSpace = 'display-p3';
  156. const ZeroStencilOp = 0;
  157. const KeepStencilOp = 7680;
  158. const ReplaceStencilOp = 7681;
  159. const IncrementStencilOp = 7682;
  160. const DecrementStencilOp = 7683;
  161. const IncrementWrapStencilOp = 34055;
  162. const DecrementWrapStencilOp = 34056;
  163. const InvertStencilOp = 5386;
  164. const NeverStencilFunc = 512;
  165. const LessStencilFunc = 513;
  166. const EqualStencilFunc = 514;
  167. const LessEqualStencilFunc = 515;
  168. const GreaterStencilFunc = 516;
  169. const NotEqualStencilFunc = 517;
  170. const GreaterEqualStencilFunc = 518;
  171. const AlwaysStencilFunc = 519;
  172. const StaticDrawUsage = 35044;
  173. const DynamicDrawUsage = 35048;
  174. const StreamDrawUsage = 35040;
  175. const StaticReadUsage = 35045;
  176. const DynamicReadUsage = 35049;
  177. const StreamReadUsage = 35041;
  178. const StaticCopyUsage = 35046;
  179. const DynamicCopyUsage = 35050;
  180. const StreamCopyUsage = 35042;
  181. const GLSL1 = '100';
  182. const GLSL3 = '300 es';
  183. const _SRGBAFormat = 1035; // fallback for WebGL 1
  184. /**
  185. * https://github.com/mrdoob/eventdispatcher.js/
  186. */
  187. class EventDispatcher {
  188. addEventListener( type, listener ) {
  189. if ( this._listeners === undefined ) this._listeners = {};
  190. const listeners = this._listeners;
  191. if ( listeners[ type ] === undefined ) {
  192. listeners[ type ] = [];
  193. }
  194. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  195. listeners[ type ].push( listener );
  196. }
  197. }
  198. hasEventListener( type, listener ) {
  199. if ( this._listeners === undefined ) return false;
  200. const listeners = this._listeners;
  201. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  202. }
  203. removeEventListener( type, listener ) {
  204. if ( this._listeners === undefined ) return;
  205. const listeners = this._listeners;
  206. const listenerArray = listeners[ type ];
  207. if ( listenerArray !== undefined ) {
  208. const index = listenerArray.indexOf( listener );
  209. if ( index !== - 1 ) {
  210. listenerArray.splice( index, 1 );
  211. }
  212. }
  213. }
  214. dispatchEvent( event ) {
  215. if ( this._listeners === undefined ) return;
  216. const listeners = this._listeners;
  217. const listenerArray = listeners[ event.type ];
  218. if ( listenerArray !== undefined ) {
  219. event.target = this;
  220. // Make a copy, in case listeners are removed while iterating.
  221. const array = listenerArray.slice( 0 );
  222. for ( let i = 0, l = array.length; i < l; i ++ ) {
  223. array[ i ].call( this, event );
  224. }
  225. event.target = null;
  226. }
  227. }
  228. }
  229. 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' ];
  230. let _seed = 1234567;
  231. const DEG2RAD = Math.PI / 180;
  232. const RAD2DEG = 180 / Math.PI;
  233. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  234. function generateUUID() {
  235. const d0 = Math.random() * 0xffffffff | 0;
  236. const d1 = Math.random() * 0xffffffff | 0;
  237. const d2 = Math.random() * 0xffffffff | 0;
  238. const d3 = Math.random() * 0xffffffff | 0;
  239. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  240. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  241. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  242. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  243. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  244. return uuid.toLowerCase();
  245. }
  246. function clamp( value, min, max ) {
  247. return Math.max( min, Math.min( max, value ) );
  248. }
  249. // compute euclidean modulo of m % n
  250. // https://en.wikipedia.org/wiki/Modulo_operation
  251. function euclideanModulo( n, m ) {
  252. return ( ( n % m ) + m ) % m;
  253. }
  254. // Linear mapping from range <a1, a2> to range <b1, b2>
  255. function mapLinear( x, a1, a2, b1, b2 ) {
  256. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  257. }
  258. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  259. function inverseLerp( x, y, value ) {
  260. if ( x !== y ) {
  261. return ( value - x ) / ( y - x );
  262. } else {
  263. return 0;
  264. }
  265. }
  266. // https://en.wikipedia.org/wiki/Linear_interpolation
  267. function lerp( x, y, t ) {
  268. return ( 1 - t ) * x + t * y;
  269. }
  270. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  271. function damp( x, y, lambda, dt ) {
  272. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  273. }
  274. // https://www.desmos.com/calculator/vcsjnyz7x4
  275. function pingpong( x, length = 1 ) {
  276. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  277. }
  278. // http://en.wikipedia.org/wiki/Smoothstep
  279. function smoothstep( x, min, max ) {
  280. if ( x <= min ) return 0;
  281. if ( x >= max ) return 1;
  282. x = ( x - min ) / ( max - min );
  283. return x * x * ( 3 - 2 * x );
  284. }
  285. function smootherstep( x, min, max ) {
  286. if ( x <= min ) return 0;
  287. if ( x >= max ) return 1;
  288. x = ( x - min ) / ( max - min );
  289. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  290. }
  291. // Random integer from <low, high> interval
  292. function randInt( low, high ) {
  293. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  294. }
  295. // Random float from <low, high> interval
  296. function randFloat( low, high ) {
  297. return low + Math.random() * ( high - low );
  298. }
  299. // Random float from <-range/2, range/2> interval
  300. function randFloatSpread( range ) {
  301. return range * ( 0.5 - Math.random() );
  302. }
  303. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  304. function seededRandom( s ) {
  305. if ( s !== undefined ) _seed = s;
  306. // Mulberry32 generator
  307. let t = _seed += 0x6D2B79F5;
  308. t = Math.imul( t ^ t >>> 15, t | 1 );
  309. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  310. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  311. }
  312. function degToRad( degrees ) {
  313. return degrees * DEG2RAD;
  314. }
  315. function radToDeg( radians ) {
  316. return radians * RAD2DEG;
  317. }
  318. function isPowerOfTwo( value ) {
  319. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  320. }
  321. function ceilPowerOfTwo( value ) {
  322. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  323. }
  324. function floorPowerOfTwo( value ) {
  325. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  326. }
  327. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  328. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  329. // rotations are applied to the axes in the order specified by 'order'
  330. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  331. // angles are in radians
  332. const cos = Math.cos;
  333. const sin = Math.sin;
  334. const c2 = cos( b / 2 );
  335. const s2 = sin( b / 2 );
  336. const c13 = cos( ( a + c ) / 2 );
  337. const s13 = sin( ( a + c ) / 2 );
  338. const c1_3 = cos( ( a - c ) / 2 );
  339. const s1_3 = sin( ( a - c ) / 2 );
  340. const c3_1 = cos( ( c - a ) / 2 );
  341. const s3_1 = sin( ( c - a ) / 2 );
  342. switch ( order ) {
  343. case 'XYX':
  344. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  345. break;
  346. case 'YZY':
  347. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  348. break;
  349. case 'ZXZ':
  350. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  351. break;
  352. case 'XZX':
  353. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  354. break;
  355. case 'YXY':
  356. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  357. break;
  358. case 'ZYZ':
  359. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  360. break;
  361. default:
  362. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  363. }
  364. }
  365. function denormalize( value, array ) {
  366. switch ( array.constructor ) {
  367. case Float32Array:
  368. return value;
  369. case Uint16Array:
  370. return value / 65535.0;
  371. case Uint8Array:
  372. return value / 255.0;
  373. case Int16Array:
  374. return Math.max( value / 32767.0, - 1.0 );
  375. case Int8Array:
  376. return Math.max( value / 127.0, - 1.0 );
  377. default:
  378. throw new Error( 'Invalid component type.' );
  379. }
  380. }
  381. function normalize( value, array ) {
  382. switch ( array.constructor ) {
  383. case Float32Array:
  384. return value;
  385. case Uint16Array:
  386. return Math.round( value * 65535.0 );
  387. case Uint8Array:
  388. return Math.round( value * 255.0 );
  389. case Int16Array:
  390. return Math.round( value * 32767.0 );
  391. case Int8Array:
  392. return Math.round( value * 127.0 );
  393. default:
  394. throw new Error( 'Invalid component type.' );
  395. }
  396. }
  397. const MathUtils = {
  398. DEG2RAD: DEG2RAD,
  399. RAD2DEG: RAD2DEG,
  400. generateUUID: generateUUID,
  401. clamp: clamp,
  402. euclideanModulo: euclideanModulo,
  403. mapLinear: mapLinear,
  404. inverseLerp: inverseLerp,
  405. lerp: lerp,
  406. damp: damp,
  407. pingpong: pingpong,
  408. smoothstep: smoothstep,
  409. smootherstep: smootherstep,
  410. randInt: randInt,
  411. randFloat: randFloat,
  412. randFloatSpread: randFloatSpread,
  413. seededRandom: seededRandom,
  414. degToRad: degToRad,
  415. radToDeg: radToDeg,
  416. isPowerOfTwo: isPowerOfTwo,
  417. ceilPowerOfTwo: ceilPowerOfTwo,
  418. floorPowerOfTwo: floorPowerOfTwo,
  419. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  420. normalize: normalize,
  421. denormalize: denormalize
  422. };
  423. class Vector2 {
  424. constructor( x = 0, y = 0 ) {
  425. Vector2.prototype.isVector2 = true;
  426. this.x = x;
  427. this.y = y;
  428. }
  429. get width() {
  430. return this.x;
  431. }
  432. set width( value ) {
  433. this.x = value;
  434. }
  435. get height() {
  436. return this.y;
  437. }
  438. set height( value ) {
  439. this.y = value;
  440. }
  441. set( x, y ) {
  442. this.x = x;
  443. this.y = y;
  444. return this;
  445. }
  446. setScalar( scalar ) {
  447. this.x = scalar;
  448. this.y = scalar;
  449. return this;
  450. }
  451. setX( x ) {
  452. this.x = x;
  453. return this;
  454. }
  455. setY( y ) {
  456. this.y = y;
  457. return this;
  458. }
  459. setComponent( index, value ) {
  460. switch ( index ) {
  461. case 0: this.x = value; break;
  462. case 1: this.y = value; break;
  463. default: throw new Error( 'index is out of range: ' + index );
  464. }
  465. return this;
  466. }
  467. getComponent( index ) {
  468. switch ( index ) {
  469. case 0: return this.x;
  470. case 1: return this.y;
  471. default: throw new Error( 'index is out of range: ' + index );
  472. }
  473. }
  474. clone() {
  475. return new this.constructor( this.x, this.y );
  476. }
  477. copy( v ) {
  478. this.x = v.x;
  479. this.y = v.y;
  480. return this;
  481. }
  482. add( v ) {
  483. this.x += v.x;
  484. this.y += v.y;
  485. return this;
  486. }
  487. addScalar( s ) {
  488. this.x += s;
  489. this.y += s;
  490. return this;
  491. }
  492. addVectors( a, b ) {
  493. this.x = a.x + b.x;
  494. this.y = a.y + b.y;
  495. return this;
  496. }
  497. addScaledVector( v, s ) {
  498. this.x += v.x * s;
  499. this.y += v.y * s;
  500. return this;
  501. }
  502. sub( v ) {
  503. this.x -= v.x;
  504. this.y -= v.y;
  505. return this;
  506. }
  507. subScalar( s ) {
  508. this.x -= s;
  509. this.y -= s;
  510. return this;
  511. }
  512. subVectors( a, b ) {
  513. this.x = a.x - b.x;
  514. this.y = a.y - b.y;
  515. return this;
  516. }
  517. multiply( v ) {
  518. this.x *= v.x;
  519. this.y *= v.y;
  520. return this;
  521. }
  522. multiplyScalar( scalar ) {
  523. this.x *= scalar;
  524. this.y *= scalar;
  525. return this;
  526. }
  527. divide( v ) {
  528. this.x /= v.x;
  529. this.y /= v.y;
  530. return this;
  531. }
  532. divideScalar( scalar ) {
  533. return this.multiplyScalar( 1 / scalar );
  534. }
  535. applyMatrix3( m ) {
  536. const x = this.x, y = this.y;
  537. const e = m.elements;
  538. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  539. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  540. return this;
  541. }
  542. min( v ) {
  543. this.x = Math.min( this.x, v.x );
  544. this.y = Math.min( this.y, v.y );
  545. return this;
  546. }
  547. max( v ) {
  548. this.x = Math.max( this.x, v.x );
  549. this.y = Math.max( this.y, v.y );
  550. return this;
  551. }
  552. clamp( min, max ) {
  553. // assumes min < max, componentwise
  554. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  555. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  556. return this;
  557. }
  558. clampScalar( minVal, maxVal ) {
  559. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  560. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  561. return this;
  562. }
  563. clampLength( min, max ) {
  564. const length = this.length();
  565. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  566. }
  567. floor() {
  568. this.x = Math.floor( this.x );
  569. this.y = Math.floor( this.y );
  570. return this;
  571. }
  572. ceil() {
  573. this.x = Math.ceil( this.x );
  574. this.y = Math.ceil( this.y );
  575. return this;
  576. }
  577. round() {
  578. this.x = Math.round( this.x );
  579. this.y = Math.round( this.y );
  580. return this;
  581. }
  582. roundToZero() {
  583. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  584. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  585. return this;
  586. }
  587. negate() {
  588. this.x = - this.x;
  589. this.y = - this.y;
  590. return this;
  591. }
  592. dot( v ) {
  593. return this.x * v.x + this.y * v.y;
  594. }
  595. cross( v ) {
  596. return this.x * v.y - this.y * v.x;
  597. }
  598. lengthSq() {
  599. return this.x * this.x + this.y * this.y;
  600. }
  601. length() {
  602. return Math.sqrt( this.x * this.x + this.y * this.y );
  603. }
  604. manhattanLength() {
  605. return Math.abs( this.x ) + Math.abs( this.y );
  606. }
  607. normalize() {
  608. return this.divideScalar( this.length() || 1 );
  609. }
  610. angle() {
  611. // computes the angle in radians with respect to the positive x-axis
  612. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  613. return angle;
  614. }
  615. distanceTo( v ) {
  616. return Math.sqrt( this.distanceToSquared( v ) );
  617. }
  618. distanceToSquared( v ) {
  619. const dx = this.x - v.x, dy = this.y - v.y;
  620. return dx * dx + dy * dy;
  621. }
  622. manhattanDistanceTo( v ) {
  623. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  624. }
  625. setLength( length ) {
  626. return this.normalize().multiplyScalar( length );
  627. }
  628. lerp( v, alpha ) {
  629. this.x += ( v.x - this.x ) * alpha;
  630. this.y += ( v.y - this.y ) * alpha;
  631. return this;
  632. }
  633. lerpVectors( v1, v2, alpha ) {
  634. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  635. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  636. return this;
  637. }
  638. equals( v ) {
  639. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  640. }
  641. fromArray( array, offset = 0 ) {
  642. this.x = array[ offset ];
  643. this.y = array[ offset + 1 ];
  644. return this;
  645. }
  646. toArray( array = [], offset = 0 ) {
  647. array[ offset ] = this.x;
  648. array[ offset + 1 ] = this.y;
  649. return array;
  650. }
  651. fromBufferAttribute( attribute, index ) {
  652. this.x = attribute.getX( index );
  653. this.y = attribute.getY( index );
  654. return this;
  655. }
  656. rotateAround( center, angle ) {
  657. const c = Math.cos( angle ), s = Math.sin( angle );
  658. const x = this.x - center.x;
  659. const y = this.y - center.y;
  660. this.x = x * c - y * s + center.x;
  661. this.y = x * s + y * c + center.y;
  662. return this;
  663. }
  664. random() {
  665. this.x = Math.random();
  666. this.y = Math.random();
  667. return this;
  668. }
  669. *[ Symbol.iterator ]() {
  670. yield this.x;
  671. yield this.y;
  672. }
  673. }
  674. class Matrix3 {
  675. constructor() {
  676. Matrix3.prototype.isMatrix3 = true;
  677. this.elements = [
  678. 1, 0, 0,
  679. 0, 1, 0,
  680. 0, 0, 1
  681. ];
  682. }
  683. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  684. const te = this.elements;
  685. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  686. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  687. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  688. return this;
  689. }
  690. identity() {
  691. this.set(
  692. 1, 0, 0,
  693. 0, 1, 0,
  694. 0, 0, 1
  695. );
  696. return this;
  697. }
  698. copy( m ) {
  699. const te = this.elements;
  700. const me = m.elements;
  701. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  702. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  703. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  704. return this;
  705. }
  706. extractBasis( xAxis, yAxis, zAxis ) {
  707. xAxis.setFromMatrix3Column( this, 0 );
  708. yAxis.setFromMatrix3Column( this, 1 );
  709. zAxis.setFromMatrix3Column( this, 2 );
  710. return this;
  711. }
  712. setFromMatrix4( m ) {
  713. const me = m.elements;
  714. this.set(
  715. me[ 0 ], me[ 4 ], me[ 8 ],
  716. me[ 1 ], me[ 5 ], me[ 9 ],
  717. me[ 2 ], me[ 6 ], me[ 10 ]
  718. );
  719. return this;
  720. }
  721. multiply( m ) {
  722. return this.multiplyMatrices( this, m );
  723. }
  724. premultiply( m ) {
  725. return this.multiplyMatrices( m, this );
  726. }
  727. multiplyMatrices( a, b ) {
  728. const ae = a.elements;
  729. const be = b.elements;
  730. const te = this.elements;
  731. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  732. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  733. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  734. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  735. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  736. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  737. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  738. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  739. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  740. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  741. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  742. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  743. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  744. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  745. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  746. return this;
  747. }
  748. multiplyScalar( s ) {
  749. const te = this.elements;
  750. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  751. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  752. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  753. return this;
  754. }
  755. determinant() {
  756. const te = this.elements;
  757. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  758. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  759. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  760. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  761. }
  762. invert() {
  763. const te = this.elements,
  764. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  765. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  766. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  767. t11 = n33 * n22 - n32 * n23,
  768. t12 = n32 * n13 - n33 * n12,
  769. t13 = n23 * n12 - n22 * n13,
  770. det = n11 * t11 + n21 * t12 + n31 * t13;
  771. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  772. const detInv = 1 / det;
  773. te[ 0 ] = t11 * detInv;
  774. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  775. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  776. te[ 3 ] = t12 * detInv;
  777. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  778. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  779. te[ 6 ] = t13 * detInv;
  780. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  781. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  782. return this;
  783. }
  784. transpose() {
  785. let tmp;
  786. const m = this.elements;
  787. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  788. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  789. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  790. return this;
  791. }
  792. getNormalMatrix( matrix4 ) {
  793. return this.setFromMatrix4( matrix4 ).invert().transpose();
  794. }
  795. transposeIntoArray( r ) {
  796. const m = this.elements;
  797. r[ 0 ] = m[ 0 ];
  798. r[ 1 ] = m[ 3 ];
  799. r[ 2 ] = m[ 6 ];
  800. r[ 3 ] = m[ 1 ];
  801. r[ 4 ] = m[ 4 ];
  802. r[ 5 ] = m[ 7 ];
  803. r[ 6 ] = m[ 2 ];
  804. r[ 7 ] = m[ 5 ];
  805. r[ 8 ] = m[ 8 ];
  806. return this;
  807. }
  808. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  809. const c = Math.cos( rotation );
  810. const s = Math.sin( rotation );
  811. this.set(
  812. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  813. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  814. 0, 0, 1
  815. );
  816. return this;
  817. }
  818. //
  819. scale( sx, sy ) {
  820. this.premultiply( _m3.makeScale( sx, sy ) );
  821. return this;
  822. }
  823. rotate( theta ) {
  824. this.premultiply( _m3.makeRotation( - theta ) );
  825. return this;
  826. }
  827. translate( tx, ty ) {
  828. this.premultiply( _m3.makeTranslation( tx, ty ) );
  829. return this;
  830. }
  831. // for 2D Transforms
  832. makeTranslation( x, y ) {
  833. this.set(
  834. 1, 0, x,
  835. 0, 1, y,
  836. 0, 0, 1
  837. );
  838. return this;
  839. }
  840. makeRotation( theta ) {
  841. // counterclockwise
  842. const c = Math.cos( theta );
  843. const s = Math.sin( theta );
  844. this.set(
  845. c, - s, 0,
  846. s, c, 0,
  847. 0, 0, 1
  848. );
  849. return this;
  850. }
  851. makeScale( x, y ) {
  852. this.set(
  853. x, 0, 0,
  854. 0, y, 0,
  855. 0, 0, 1
  856. );
  857. return this;
  858. }
  859. //
  860. equals( matrix ) {
  861. const te = this.elements;
  862. const me = matrix.elements;
  863. for ( let i = 0; i < 9; i ++ ) {
  864. if ( te[ i ] !== me[ i ] ) return false;
  865. }
  866. return true;
  867. }
  868. fromArray( array, offset = 0 ) {
  869. for ( let i = 0; i < 9; i ++ ) {
  870. this.elements[ i ] = array[ i + offset ];
  871. }
  872. return this;
  873. }
  874. toArray( array = [], offset = 0 ) {
  875. const te = this.elements;
  876. array[ offset ] = te[ 0 ];
  877. array[ offset + 1 ] = te[ 1 ];
  878. array[ offset + 2 ] = te[ 2 ];
  879. array[ offset + 3 ] = te[ 3 ];
  880. array[ offset + 4 ] = te[ 4 ];
  881. array[ offset + 5 ] = te[ 5 ];
  882. array[ offset + 6 ] = te[ 6 ];
  883. array[ offset + 7 ] = te[ 7 ];
  884. array[ offset + 8 ] = te[ 8 ];
  885. return array;
  886. }
  887. clone() {
  888. return new this.constructor().fromArray( this.elements );
  889. }
  890. }
  891. const _m3 = /*@__PURE__*/ new Matrix3();
  892. function arrayNeedsUint32( array ) {
  893. // assumes larger values usually on last
  894. for ( let i = array.length - 1; i >= 0; -- i ) {
  895. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  896. }
  897. return false;
  898. }
  899. const TYPED_ARRAYS = {
  900. Int8Array: Int8Array,
  901. Uint8Array: Uint8Array,
  902. Uint8ClampedArray: Uint8ClampedArray,
  903. Int16Array: Int16Array,
  904. Uint16Array: Uint16Array,
  905. Int32Array: Int32Array,
  906. Uint32Array: Uint32Array,
  907. Float32Array: Float32Array,
  908. Float64Array: Float64Array
  909. };
  910. function getTypedArray( type, buffer ) {
  911. return new TYPED_ARRAYS[ type ]( buffer );
  912. }
  913. function createElementNS( name ) {
  914. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  915. }
  916. class Quaternion {
  917. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  918. this.isQuaternion = true;
  919. this._x = x;
  920. this._y = y;
  921. this._z = z;
  922. this._w = w;
  923. }
  924. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  925. // fuzz-free, array-based Quaternion SLERP operation
  926. let x0 = src0[ srcOffset0 + 0 ],
  927. y0 = src0[ srcOffset0 + 1 ],
  928. z0 = src0[ srcOffset0 + 2 ],
  929. w0 = src0[ srcOffset0 + 3 ];
  930. const x1 = src1[ srcOffset1 + 0 ],
  931. y1 = src1[ srcOffset1 + 1 ],
  932. z1 = src1[ srcOffset1 + 2 ],
  933. w1 = src1[ srcOffset1 + 3 ];
  934. if ( t === 0 ) {
  935. dst[ dstOffset + 0 ] = x0;
  936. dst[ dstOffset + 1 ] = y0;
  937. dst[ dstOffset + 2 ] = z0;
  938. dst[ dstOffset + 3 ] = w0;
  939. return;
  940. }
  941. if ( t === 1 ) {
  942. dst[ dstOffset + 0 ] = x1;
  943. dst[ dstOffset + 1 ] = y1;
  944. dst[ dstOffset + 2 ] = z1;
  945. dst[ dstOffset + 3 ] = w1;
  946. return;
  947. }
  948. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  949. let s = 1 - t;
  950. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  951. dir = ( cos >= 0 ? 1 : - 1 ),
  952. sqrSin = 1 - cos * cos;
  953. // Skip the Slerp for tiny steps to avoid numeric problems:
  954. if ( sqrSin > Number.EPSILON ) {
  955. const sin = Math.sqrt( sqrSin ),
  956. len = Math.atan2( sin, cos * dir );
  957. s = Math.sin( s * len ) / sin;
  958. t = Math.sin( t * len ) / sin;
  959. }
  960. const tDir = t * dir;
  961. x0 = x0 * s + x1 * tDir;
  962. y0 = y0 * s + y1 * tDir;
  963. z0 = z0 * s + z1 * tDir;
  964. w0 = w0 * s + w1 * tDir;
  965. // Normalize in case we just did a lerp:
  966. if ( s === 1 - t ) {
  967. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  968. x0 *= f;
  969. y0 *= f;
  970. z0 *= f;
  971. w0 *= f;
  972. }
  973. }
  974. dst[ dstOffset ] = x0;
  975. dst[ dstOffset + 1 ] = y0;
  976. dst[ dstOffset + 2 ] = z0;
  977. dst[ dstOffset + 3 ] = w0;
  978. }
  979. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  980. const x0 = src0[ srcOffset0 ];
  981. const y0 = src0[ srcOffset0 + 1 ];
  982. const z0 = src0[ srcOffset0 + 2 ];
  983. const w0 = src0[ srcOffset0 + 3 ];
  984. const x1 = src1[ srcOffset1 ];
  985. const y1 = src1[ srcOffset1 + 1 ];
  986. const z1 = src1[ srcOffset1 + 2 ];
  987. const w1 = src1[ srcOffset1 + 3 ];
  988. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  989. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  990. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  991. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  992. return dst;
  993. }
  994. get x() {
  995. return this._x;
  996. }
  997. set x( value ) {
  998. this._x = value;
  999. this._onChangeCallback();
  1000. }
  1001. get y() {
  1002. return this._y;
  1003. }
  1004. set y( value ) {
  1005. this._y = value;
  1006. this._onChangeCallback();
  1007. }
  1008. get z() {
  1009. return this._z;
  1010. }
  1011. set z( value ) {
  1012. this._z = value;
  1013. this._onChangeCallback();
  1014. }
  1015. get w() {
  1016. return this._w;
  1017. }
  1018. set w( value ) {
  1019. this._w = value;
  1020. this._onChangeCallback();
  1021. }
  1022. set( x, y, z, w ) {
  1023. this._x = x;
  1024. this._y = y;
  1025. this._z = z;
  1026. this._w = w;
  1027. this._onChangeCallback();
  1028. return this;
  1029. }
  1030. clone() {
  1031. return new this.constructor( this._x, this._y, this._z, this._w );
  1032. }
  1033. copy( quaternion ) {
  1034. this._x = quaternion.x;
  1035. this._y = quaternion.y;
  1036. this._z = quaternion.z;
  1037. this._w = quaternion.w;
  1038. this._onChangeCallback();
  1039. return this;
  1040. }
  1041. setFromEuler( euler, update ) {
  1042. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  1043. // http://www.mathworks.com/matlabcentral/fileexchange/
  1044. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  1045. // content/SpinCalc.m
  1046. const cos = Math.cos;
  1047. const sin = Math.sin;
  1048. const c1 = cos( x / 2 );
  1049. const c2 = cos( y / 2 );
  1050. const c3 = cos( z / 2 );
  1051. const s1 = sin( x / 2 );
  1052. const s2 = sin( y / 2 );
  1053. const s3 = sin( z / 2 );
  1054. switch ( order ) {
  1055. case 'XYZ':
  1056. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1057. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1058. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1059. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1060. break;
  1061. case 'YXZ':
  1062. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1063. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1064. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1065. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1066. break;
  1067. case 'ZXY':
  1068. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1069. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1070. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1071. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1072. break;
  1073. case 'ZYX':
  1074. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1075. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1076. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1077. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1078. break;
  1079. case 'YZX':
  1080. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  1081. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  1082. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  1083. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  1084. break;
  1085. case 'XZY':
  1086. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  1087. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  1088. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  1089. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  1090. break;
  1091. default:
  1092. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  1093. }
  1094. if ( update !== false ) this._onChangeCallback();
  1095. return this;
  1096. }
  1097. setFromAxisAngle( axis, angle ) {
  1098. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  1099. // assumes axis is normalized
  1100. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  1101. this._x = axis.x * s;
  1102. this._y = axis.y * s;
  1103. this._z = axis.z * s;
  1104. this._w = Math.cos( halfAngle );
  1105. this._onChangeCallback();
  1106. return this;
  1107. }
  1108. setFromRotationMatrix( m ) {
  1109. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  1110. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1111. const te = m.elements,
  1112. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1113. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1114. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  1115. trace = m11 + m22 + m33;
  1116. if ( trace > 0 ) {
  1117. const s = 0.5 / Math.sqrt( trace + 1.0 );
  1118. this._w = 0.25 / s;
  1119. this._x = ( m32 - m23 ) * s;
  1120. this._y = ( m13 - m31 ) * s;
  1121. this._z = ( m21 - m12 ) * s;
  1122. } else if ( m11 > m22 && m11 > m33 ) {
  1123. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  1124. this._w = ( m32 - m23 ) / s;
  1125. this._x = 0.25 * s;
  1126. this._y = ( m12 + m21 ) / s;
  1127. this._z = ( m13 + m31 ) / s;
  1128. } else if ( m22 > m33 ) {
  1129. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  1130. this._w = ( m13 - m31 ) / s;
  1131. this._x = ( m12 + m21 ) / s;
  1132. this._y = 0.25 * s;
  1133. this._z = ( m23 + m32 ) / s;
  1134. } else {
  1135. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  1136. this._w = ( m21 - m12 ) / s;
  1137. this._x = ( m13 + m31 ) / s;
  1138. this._y = ( m23 + m32 ) / s;
  1139. this._z = 0.25 * s;
  1140. }
  1141. this._onChangeCallback();
  1142. return this;
  1143. }
  1144. setFromUnitVectors( vFrom, vTo ) {
  1145. // assumes direction vectors vFrom and vTo are normalized
  1146. let r = vFrom.dot( vTo ) + 1;
  1147. if ( r < Number.EPSILON ) {
  1148. // vFrom and vTo point in opposite directions
  1149. r = 0;
  1150. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  1151. this._x = - vFrom.y;
  1152. this._y = vFrom.x;
  1153. this._z = 0;
  1154. this._w = r;
  1155. } else {
  1156. this._x = 0;
  1157. this._y = - vFrom.z;
  1158. this._z = vFrom.y;
  1159. this._w = r;
  1160. }
  1161. } else {
  1162. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  1163. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  1164. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  1165. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  1166. this._w = r;
  1167. }
  1168. return this.normalize();
  1169. }
  1170. angleTo( q ) {
  1171. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  1172. }
  1173. rotateTowards( q, step ) {
  1174. const angle = this.angleTo( q );
  1175. if ( angle === 0 ) return this;
  1176. const t = Math.min( 1, step / angle );
  1177. this.slerp( q, t );
  1178. return this;
  1179. }
  1180. identity() {
  1181. return this.set( 0, 0, 0, 1 );
  1182. }
  1183. invert() {
  1184. // quaternion is assumed to have unit length
  1185. return this.conjugate();
  1186. }
  1187. conjugate() {
  1188. this._x *= - 1;
  1189. this._y *= - 1;
  1190. this._z *= - 1;
  1191. this._onChangeCallback();
  1192. return this;
  1193. }
  1194. dot( v ) {
  1195. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  1196. }
  1197. lengthSq() {
  1198. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  1199. }
  1200. length() {
  1201. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  1202. }
  1203. normalize() {
  1204. let l = this.length();
  1205. if ( l === 0 ) {
  1206. this._x = 0;
  1207. this._y = 0;
  1208. this._z = 0;
  1209. this._w = 1;
  1210. } else {
  1211. l = 1 / l;
  1212. this._x = this._x * l;
  1213. this._y = this._y * l;
  1214. this._z = this._z * l;
  1215. this._w = this._w * l;
  1216. }
  1217. this._onChangeCallback();
  1218. return this;
  1219. }
  1220. multiply( q ) {
  1221. return this.multiplyQuaternions( this, q );
  1222. }
  1223. premultiply( q ) {
  1224. return this.multiplyQuaternions( q, this );
  1225. }
  1226. multiplyQuaternions( a, b ) {
  1227. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  1228. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  1229. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  1230. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  1231. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  1232. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  1233. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  1234. this._onChangeCallback();
  1235. return this;
  1236. }
  1237. slerp( qb, t ) {
  1238. if ( t === 0 ) return this;
  1239. if ( t === 1 ) return this.copy( qb );
  1240. const x = this._x, y = this._y, z = this._z, w = this._w;
  1241. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  1242. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  1243. if ( cosHalfTheta < 0 ) {
  1244. this._w = - qb._w;
  1245. this._x = - qb._x;
  1246. this._y = - qb._y;
  1247. this._z = - qb._z;
  1248. cosHalfTheta = - cosHalfTheta;
  1249. } else {
  1250. this.copy( qb );
  1251. }
  1252. if ( cosHalfTheta >= 1.0 ) {
  1253. this._w = w;
  1254. this._x = x;
  1255. this._y = y;
  1256. this._z = z;
  1257. return this;
  1258. }
  1259. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  1260. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  1261. const s = 1 - t;
  1262. this._w = s * w + t * this._w;
  1263. this._x = s * x + t * this._x;
  1264. this._y = s * y + t * this._y;
  1265. this._z = s * z + t * this._z;
  1266. this.normalize();
  1267. this._onChangeCallback();
  1268. return this;
  1269. }
  1270. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  1271. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  1272. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  1273. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  1274. this._w = ( w * ratioA + this._w * ratioB );
  1275. this._x = ( x * ratioA + this._x * ratioB );
  1276. this._y = ( y * ratioA + this._y * ratioB );
  1277. this._z = ( z * ratioA + this._z * ratioB );
  1278. this._onChangeCallback();
  1279. return this;
  1280. }
  1281. slerpQuaternions( qa, qb, t ) {
  1282. return this.copy( qa ).slerp( qb, t );
  1283. }
  1284. random() {
  1285. // Derived from http://planning.cs.uiuc.edu/node198.html
  1286. // Note, this source uses w, x, y, z ordering,
  1287. // so we swap the order below.
  1288. const u1 = Math.random();
  1289. const sqrt1u1 = Math.sqrt( 1 - u1 );
  1290. const sqrtu1 = Math.sqrt( u1 );
  1291. const u2 = 2 * Math.PI * Math.random();
  1292. const u3 = 2 * Math.PI * Math.random();
  1293. return this.set(
  1294. sqrt1u1 * Math.cos( u2 ),
  1295. sqrtu1 * Math.sin( u3 ),
  1296. sqrtu1 * Math.cos( u3 ),
  1297. sqrt1u1 * Math.sin( u2 ),
  1298. );
  1299. }
  1300. equals( quaternion ) {
  1301. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  1302. }
  1303. fromArray( array, offset = 0 ) {
  1304. this._x = array[ offset ];
  1305. this._y = array[ offset + 1 ];
  1306. this._z = array[ offset + 2 ];
  1307. this._w = array[ offset + 3 ];
  1308. this._onChangeCallback();
  1309. return this;
  1310. }
  1311. toArray( array = [], offset = 0 ) {
  1312. array[ offset ] = this._x;
  1313. array[ offset + 1 ] = this._y;
  1314. array[ offset + 2 ] = this._z;
  1315. array[ offset + 3 ] = this._w;
  1316. return array;
  1317. }
  1318. fromBufferAttribute( attribute, index ) {
  1319. this._x = attribute.getX( index );
  1320. this._y = attribute.getY( index );
  1321. this._z = attribute.getZ( index );
  1322. this._w = attribute.getW( index );
  1323. return this;
  1324. }
  1325. _onChange( callback ) {
  1326. this._onChangeCallback = callback;
  1327. return this;
  1328. }
  1329. _onChangeCallback() {}
  1330. *[ Symbol.iterator ]() {
  1331. yield this._x;
  1332. yield this._y;
  1333. yield this._z;
  1334. yield this._w;
  1335. }
  1336. }
  1337. class Vector3 {
  1338. constructor( x = 0, y = 0, z = 0 ) {
  1339. Vector3.prototype.isVector3 = true;
  1340. this.x = x;
  1341. this.y = y;
  1342. this.z = z;
  1343. }
  1344. set( x, y, z ) {
  1345. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  1346. this.x = x;
  1347. this.y = y;
  1348. this.z = z;
  1349. return this;
  1350. }
  1351. setScalar( scalar ) {
  1352. this.x = scalar;
  1353. this.y = scalar;
  1354. this.z = scalar;
  1355. return this;
  1356. }
  1357. setX( x ) {
  1358. this.x = x;
  1359. return this;
  1360. }
  1361. setY( y ) {
  1362. this.y = y;
  1363. return this;
  1364. }
  1365. setZ( z ) {
  1366. this.z = z;
  1367. return this;
  1368. }
  1369. setComponent( index, value ) {
  1370. switch ( index ) {
  1371. case 0: this.x = value; break;
  1372. case 1: this.y = value; break;
  1373. case 2: this.z = value; break;
  1374. default: throw new Error( 'index is out of range: ' + index );
  1375. }
  1376. return this;
  1377. }
  1378. getComponent( index ) {
  1379. switch ( index ) {
  1380. case 0: return this.x;
  1381. case 1: return this.y;
  1382. case 2: return this.z;
  1383. default: throw new Error( 'index is out of range: ' + index );
  1384. }
  1385. }
  1386. clone() {
  1387. return new this.constructor( this.x, this.y, this.z );
  1388. }
  1389. copy( v ) {
  1390. this.x = v.x;
  1391. this.y = v.y;
  1392. this.z = v.z;
  1393. return this;
  1394. }
  1395. add( v ) {
  1396. this.x += v.x;
  1397. this.y += v.y;
  1398. this.z += v.z;
  1399. return this;
  1400. }
  1401. addScalar( s ) {
  1402. this.x += s;
  1403. this.y += s;
  1404. this.z += s;
  1405. return this;
  1406. }
  1407. addVectors( a, b ) {
  1408. this.x = a.x + b.x;
  1409. this.y = a.y + b.y;
  1410. this.z = a.z + b.z;
  1411. return this;
  1412. }
  1413. addScaledVector( v, s ) {
  1414. this.x += v.x * s;
  1415. this.y += v.y * s;
  1416. this.z += v.z * s;
  1417. return this;
  1418. }
  1419. sub( v ) {
  1420. this.x -= v.x;
  1421. this.y -= v.y;
  1422. this.z -= v.z;
  1423. return this;
  1424. }
  1425. subScalar( s ) {
  1426. this.x -= s;
  1427. this.y -= s;
  1428. this.z -= s;
  1429. return this;
  1430. }
  1431. subVectors( a, b ) {
  1432. this.x = a.x - b.x;
  1433. this.y = a.y - b.y;
  1434. this.z = a.z - b.z;
  1435. return this;
  1436. }
  1437. multiply( v ) {
  1438. this.x *= v.x;
  1439. this.y *= v.y;
  1440. this.z *= v.z;
  1441. return this;
  1442. }
  1443. multiplyScalar( scalar ) {
  1444. this.x *= scalar;
  1445. this.y *= scalar;
  1446. this.z *= scalar;
  1447. return this;
  1448. }
  1449. multiplyVectors( a, b ) {
  1450. this.x = a.x * b.x;
  1451. this.y = a.y * b.y;
  1452. this.z = a.z * b.z;
  1453. return this;
  1454. }
  1455. applyEuler( euler ) {
  1456. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  1457. }
  1458. applyAxisAngle( axis, angle ) {
  1459. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  1460. }
  1461. applyMatrix3( m ) {
  1462. const x = this.x, y = this.y, z = this.z;
  1463. const e = m.elements;
  1464. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1465. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1466. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1467. return this;
  1468. }
  1469. applyNormalMatrix( m ) {
  1470. return this.applyMatrix3( m ).normalize();
  1471. }
  1472. applyMatrix4( m ) {
  1473. const x = this.x, y = this.y, z = this.z;
  1474. const e = m.elements;
  1475. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  1476. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  1477. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  1478. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  1479. return this;
  1480. }
  1481. applyQuaternion( q ) {
  1482. const x = this.x, y = this.y, z = this.z;
  1483. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  1484. // calculate quat * vector
  1485. const ix = qw * x + qy * z - qz * y;
  1486. const iy = qw * y + qz * x - qx * z;
  1487. const iz = qw * z + qx * y - qy * x;
  1488. const iw = - qx * x - qy * y - qz * z;
  1489. // calculate result * inverse quat
  1490. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1491. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1492. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1493. return this;
  1494. }
  1495. project( camera ) {
  1496. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  1497. }
  1498. unproject( camera ) {
  1499. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  1500. }
  1501. transformDirection( m ) {
  1502. // input: THREE.Matrix4 affine matrix
  1503. // vector interpreted as a direction
  1504. const x = this.x, y = this.y, z = this.z;
  1505. const e = m.elements;
  1506. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1507. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1508. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1509. return this.normalize();
  1510. }
  1511. divide( v ) {
  1512. this.x /= v.x;
  1513. this.y /= v.y;
  1514. this.z /= v.z;
  1515. return this;
  1516. }
  1517. divideScalar( scalar ) {
  1518. return this.multiplyScalar( 1 / scalar );
  1519. }
  1520. min( v ) {
  1521. this.x = Math.min( this.x, v.x );
  1522. this.y = Math.min( this.y, v.y );
  1523. this.z = Math.min( this.z, v.z );
  1524. return this;
  1525. }
  1526. max( v ) {
  1527. this.x = Math.max( this.x, v.x );
  1528. this.y = Math.max( this.y, v.y );
  1529. this.z = Math.max( this.z, v.z );
  1530. return this;
  1531. }
  1532. clamp( min, max ) {
  1533. // assumes min < max, componentwise
  1534. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1535. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1536. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1537. return this;
  1538. }
  1539. clampScalar( minVal, maxVal ) {
  1540. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1541. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1542. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1543. return this;
  1544. }
  1545. clampLength( min, max ) {
  1546. const length = this.length();
  1547. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1548. }
  1549. floor() {
  1550. this.x = Math.floor( this.x );
  1551. this.y = Math.floor( this.y );
  1552. this.z = Math.floor( this.z );
  1553. return this;
  1554. }
  1555. ceil() {
  1556. this.x = Math.ceil( this.x );
  1557. this.y = Math.ceil( this.y );
  1558. this.z = Math.ceil( this.z );
  1559. return this;
  1560. }
  1561. round() {
  1562. this.x = Math.round( this.x );
  1563. this.y = Math.round( this.y );
  1564. this.z = Math.round( this.z );
  1565. return this;
  1566. }
  1567. roundToZero() {
  1568. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1569. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1570. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1571. return this;
  1572. }
  1573. negate() {
  1574. this.x = - this.x;
  1575. this.y = - this.y;
  1576. this.z = - this.z;
  1577. return this;
  1578. }
  1579. dot( v ) {
  1580. return this.x * v.x + this.y * v.y + this.z * v.z;
  1581. }
  1582. // TODO lengthSquared?
  1583. lengthSq() {
  1584. return this.x * this.x + this.y * this.y + this.z * this.z;
  1585. }
  1586. length() {
  1587. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1588. }
  1589. manhattanLength() {
  1590. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1591. }
  1592. normalize() {
  1593. return this.divideScalar( this.length() || 1 );
  1594. }
  1595. setLength( length ) {
  1596. return this.normalize().multiplyScalar( length );
  1597. }
  1598. lerp( v, alpha ) {
  1599. this.x += ( v.x - this.x ) * alpha;
  1600. this.y += ( v.y - this.y ) * alpha;
  1601. this.z += ( v.z - this.z ) * alpha;
  1602. return this;
  1603. }
  1604. lerpVectors( v1, v2, alpha ) {
  1605. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1606. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1607. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1608. return this;
  1609. }
  1610. cross( v ) {
  1611. return this.crossVectors( this, v );
  1612. }
  1613. crossVectors( a, b ) {
  1614. const ax = a.x, ay = a.y, az = a.z;
  1615. const bx = b.x, by = b.y, bz = b.z;
  1616. this.x = ay * bz - az * by;
  1617. this.y = az * bx - ax * bz;
  1618. this.z = ax * by - ay * bx;
  1619. return this;
  1620. }
  1621. projectOnVector( v ) {
  1622. const denominator = v.lengthSq();
  1623. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  1624. const scalar = v.dot( this ) / denominator;
  1625. return this.copy( v ).multiplyScalar( scalar );
  1626. }
  1627. projectOnPlane( planeNormal ) {
  1628. _vector$d.copy( this ).projectOnVector( planeNormal );
  1629. return this.sub( _vector$d );
  1630. }
  1631. reflect( normal ) {
  1632. // reflect incident vector off plane orthogonal to normal
  1633. // normal is assumed to have unit length
  1634. return this.sub( _vector$d.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1635. }
  1636. angleTo( v ) {
  1637. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  1638. if ( denominator === 0 ) return Math.PI / 2;
  1639. const theta = this.dot( v ) / denominator;
  1640. // clamp, to handle numerical problems
  1641. return Math.acos( clamp( theta, - 1, 1 ) );
  1642. }
  1643. distanceTo( v ) {
  1644. return Math.sqrt( this.distanceToSquared( v ) );
  1645. }
  1646. distanceToSquared( v ) {
  1647. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  1648. return dx * dx + dy * dy + dz * dz;
  1649. }
  1650. manhattanDistanceTo( v ) {
  1651. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  1652. }
  1653. setFromSpherical( s ) {
  1654. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  1655. }
  1656. setFromSphericalCoords( radius, phi, theta ) {
  1657. const sinPhiRadius = Math.sin( phi ) * radius;
  1658. this.x = sinPhiRadius * Math.sin( theta );
  1659. this.y = Math.cos( phi ) * radius;
  1660. this.z = sinPhiRadius * Math.cos( theta );
  1661. return this;
  1662. }
  1663. setFromCylindrical( c ) {
  1664. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  1665. }
  1666. setFromCylindricalCoords( radius, theta, y ) {
  1667. this.x = radius * Math.sin( theta );
  1668. this.y = y;
  1669. this.z = radius * Math.cos( theta );
  1670. return this;
  1671. }
  1672. setFromMatrixPosition( m ) {
  1673. const e = m.elements;
  1674. this.x = e[ 12 ];
  1675. this.y = e[ 13 ];
  1676. this.z = e[ 14 ];
  1677. return this;
  1678. }
  1679. setFromMatrixScale( m ) {
  1680. const sx = this.setFromMatrixColumn( m, 0 ).length();
  1681. const sy = this.setFromMatrixColumn( m, 1 ).length();
  1682. const sz = this.setFromMatrixColumn( m, 2 ).length();
  1683. this.x = sx;
  1684. this.y = sy;
  1685. this.z = sz;
  1686. return this;
  1687. }
  1688. setFromMatrixColumn( m, index ) {
  1689. return this.fromArray( m.elements, index * 4 );
  1690. }
  1691. setFromMatrix3Column( m, index ) {
  1692. return this.fromArray( m.elements, index * 3 );
  1693. }
  1694. setFromEuler( e ) {
  1695. this.x = e._x;
  1696. this.y = e._y;
  1697. this.z = e._z;
  1698. return this;
  1699. }
  1700. equals( v ) {
  1701. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1702. }
  1703. fromArray( array, offset = 0 ) {
  1704. this.x = array[ offset ];
  1705. this.y = array[ offset + 1 ];
  1706. this.z = array[ offset + 2 ];
  1707. return this;
  1708. }
  1709. toArray( array = [], offset = 0 ) {
  1710. array[ offset ] = this.x;
  1711. array[ offset + 1 ] = this.y;
  1712. array[ offset + 2 ] = this.z;
  1713. return array;
  1714. }
  1715. fromBufferAttribute( attribute, index ) {
  1716. this.x = attribute.getX( index );
  1717. this.y = attribute.getY( index );
  1718. this.z = attribute.getZ( index );
  1719. return this;
  1720. }
  1721. random() {
  1722. this.x = Math.random();
  1723. this.y = Math.random();
  1724. this.z = Math.random();
  1725. return this;
  1726. }
  1727. randomDirection() {
  1728. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  1729. const u = ( Math.random() - 0.5 ) * 2;
  1730. const t = Math.random() * Math.PI * 2;
  1731. const f = Math.sqrt( 1 - u ** 2 );
  1732. this.x = f * Math.cos( t );
  1733. this.y = f * Math.sin( t );
  1734. this.z = u;
  1735. return this;
  1736. }
  1737. *[ Symbol.iterator ]() {
  1738. yield this.x;
  1739. yield this.y;
  1740. yield this.z;
  1741. }
  1742. }
  1743. const _vector$d = /*@__PURE__*/ new Vector3();
  1744. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  1745. function SRGBToLinear( c ) {
  1746. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  1747. }
  1748. function LinearToSRGB( c ) {
  1749. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  1750. }
  1751. /**
  1752. * Matrices converting P3 <-> Rec. 709 primaries, without gamut mapping
  1753. * or clipping. Based on W3C specifications for sRGB and Display P3,
  1754. * and ICC specifications for the D50 connection space. Values in/out
  1755. * are _linear_ sRGB and _linear_ Display P3.
  1756. *
  1757. * Note that both sRGB and Display P3 use the sRGB transfer functions.
  1758. *
  1759. * Reference:
  1760. * - http://www.russellcottrell.com/photo/matrixCalculator.htm
  1761. */
  1762. const LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 = new Matrix3().fromArray( [
  1763. 0.8224621, 0.0331941, 0.0170827,
  1764. 0.1775380, 0.9668058, 0.0723974,
  1765. - 0.0000001, 0.0000001, 0.9105199
  1766. ] );
  1767. const LINEAR_DISPLAY_P3_TO_LINEAR_SRGB = new Matrix3().fromArray( [
  1768. 1.2249401, - 0.0420569, - 0.0196376,
  1769. - 0.2249404, 1.0420571, - 0.0786361,
  1770. 0.0000001, 0.0000000, 1.0982735
  1771. ] );
  1772. const _vector$c = new Vector3();
  1773. function DisplayP3ToLinearSRGB( color ) {
  1774. color.convertSRGBToLinear();
  1775. _vector$c.set( color.r, color.g, color.b ).applyMatrix3( LINEAR_DISPLAY_P3_TO_LINEAR_SRGB );
  1776. return color.setRGB( _vector$c.x, _vector$c.y, _vector$c.z );
  1777. }
  1778. function LinearSRGBToDisplayP3( color ) {
  1779. _vector$c.set( color.r, color.g, color.b ).applyMatrix3( LINEAR_SRGB_TO_LINEAR_DISPLAY_P3 );
  1780. return color.setRGB( _vector$c.x, _vector$c.y, _vector$c.z ).convertLinearToSRGB();
  1781. }
  1782. // Conversions from <source> to Linear-sRGB reference space.
  1783. const TO_LINEAR = {
  1784. [ LinearSRGBColorSpace ]: ( color ) => color,
  1785. [ SRGBColorSpace ]: ( color ) => color.convertSRGBToLinear(),
  1786. [ DisplayP3ColorSpace ]: DisplayP3ToLinearSRGB,
  1787. };
  1788. // Conversions to <target> from Linear-sRGB reference space.
  1789. const FROM_LINEAR = {
  1790. [ LinearSRGBColorSpace ]: ( color ) => color,
  1791. [ SRGBColorSpace ]: ( color ) => color.convertLinearToSRGB(),
  1792. [ DisplayP3ColorSpace ]: LinearSRGBToDisplayP3,
  1793. };
  1794. const ColorManagement = {
  1795. enabled: false,
  1796. get legacyMode() {
  1797. console.warn( 'THREE.ColorManagement: .legacyMode=false renamed to .enabled=true in r150.' );
  1798. return ! this.enabled;
  1799. },
  1800. set legacyMode( legacyMode ) {
  1801. console.warn( 'THREE.ColorManagement: .legacyMode=false renamed to .enabled=true in r150.' );
  1802. this.enabled = ! legacyMode;
  1803. },
  1804. get workingColorSpace() {
  1805. return LinearSRGBColorSpace;
  1806. },
  1807. set workingColorSpace( colorSpace ) {
  1808. console.warn( 'THREE.ColorManagement: .workingColorSpace is readonly.' );
  1809. },
  1810. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  1811. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  1812. return color;
  1813. }
  1814. const sourceToLinear = TO_LINEAR[ sourceColorSpace ];
  1815. const targetFromLinear = FROM_LINEAR[ targetColorSpace ];
  1816. if ( sourceToLinear === undefined || targetFromLinear === undefined ) {
  1817. throw new Error( `Unsupported color space conversion, "${ sourceColorSpace }" to "${ targetColorSpace }".` );
  1818. }
  1819. return targetFromLinear( sourceToLinear( color ) );
  1820. },
  1821. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  1822. return this.convert( color, this.workingColorSpace, targetColorSpace );
  1823. },
  1824. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  1825. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  1826. },
  1827. };
  1828. let _canvas;
  1829. class ImageUtils {
  1830. static getDataURL( image ) {
  1831. if ( /^data:/i.test( image.src ) ) {
  1832. return image.src;
  1833. }
  1834. if ( typeof HTMLCanvasElement == 'undefined' ) {
  1835. return image.src;
  1836. }
  1837. let canvas;
  1838. if ( image instanceof HTMLCanvasElement ) {
  1839. canvas = image;
  1840. } else {
  1841. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1842. _canvas.width = image.width;
  1843. _canvas.height = image.height;
  1844. const context = _canvas.getContext( '2d' );
  1845. if ( image instanceof ImageData ) {
  1846. context.putImageData( image, 0, 0 );
  1847. } else {
  1848. context.drawImage( image, 0, 0, image.width, image.height );
  1849. }
  1850. canvas = _canvas;
  1851. }
  1852. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1853. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1854. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1855. } else {
  1856. return canvas.toDataURL( 'image/png' );
  1857. }
  1858. }
  1859. static sRGBToLinear( image ) {
  1860. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1861. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1862. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1863. const canvas = createElementNS( 'canvas' );
  1864. canvas.width = image.width;
  1865. canvas.height = image.height;
  1866. const context = canvas.getContext( '2d' );
  1867. context.drawImage( image, 0, 0, image.width, image.height );
  1868. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1869. const data = imageData.data;
  1870. for ( let i = 0; i < data.length; i ++ ) {
  1871. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1872. }
  1873. context.putImageData( imageData, 0, 0 );
  1874. return canvas;
  1875. } else if ( image.data ) {
  1876. const data = image.data.slice( 0 );
  1877. for ( let i = 0; i < data.length; i ++ ) {
  1878. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1879. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1880. } else {
  1881. // assuming float
  1882. data[ i ] = SRGBToLinear( data[ i ] );
  1883. }
  1884. }
  1885. return {
  1886. data: data,
  1887. width: image.width,
  1888. height: image.height
  1889. };
  1890. } else {
  1891. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1892. return image;
  1893. }
  1894. }
  1895. }
  1896. class Source {
  1897. constructor( data = null ) {
  1898. this.isSource = true;
  1899. this.uuid = generateUUID();
  1900. this.data = data;
  1901. this.version = 0;
  1902. }
  1903. set needsUpdate( value ) {
  1904. if ( value === true ) this.version ++;
  1905. }
  1906. toJSON( meta ) {
  1907. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1908. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1909. return meta.images[ this.uuid ];
  1910. }
  1911. const output = {
  1912. uuid: this.uuid,
  1913. url: ''
  1914. };
  1915. const data = this.data;
  1916. if ( data !== null ) {
  1917. let url;
  1918. if ( Array.isArray( data ) ) {
  1919. // cube texture
  1920. url = [];
  1921. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1922. if ( data[ i ].isDataTexture ) {
  1923. url.push( serializeImage( data[ i ].image ) );
  1924. } else {
  1925. url.push( serializeImage( data[ i ] ) );
  1926. }
  1927. }
  1928. } else {
  1929. // texture
  1930. url = serializeImage( data );
  1931. }
  1932. output.url = url;
  1933. }
  1934. if ( ! isRootObject ) {
  1935. meta.images[ this.uuid ] = output;
  1936. }
  1937. return output;
  1938. }
  1939. }
  1940. function serializeImage( image ) {
  1941. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1942. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1943. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1944. // default images
  1945. return ImageUtils.getDataURL( image );
  1946. } else {
  1947. if ( image.data ) {
  1948. // images of DataTexture
  1949. return {
  1950. data: Array.from( image.data ),
  1951. width: image.width,
  1952. height: image.height,
  1953. type: image.data.constructor.name
  1954. };
  1955. } else {
  1956. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1957. return {};
  1958. }
  1959. }
  1960. }
  1961. let textureId = 0;
  1962. class Texture extends EventDispatcher {
  1963. constructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = Texture.DEFAULT_ANISOTROPY, encoding = LinearEncoding ) {
  1964. super();
  1965. this.isTexture = true;
  1966. Object.defineProperty( this, 'id', { value: textureId ++ } );
  1967. this.uuid = generateUUID();
  1968. this.name = '';
  1969. this.source = new Source( image );
  1970. this.mipmaps = [];
  1971. this.mapping = mapping;
  1972. this.wrapS = wrapS;
  1973. this.wrapT = wrapT;
  1974. this.magFilter = magFilter;
  1975. this.minFilter = minFilter;
  1976. this.anisotropy = anisotropy;
  1977. this.format = format;
  1978. this.internalFormat = null;
  1979. this.type = type;
  1980. this.offset = new Vector2( 0, 0 );
  1981. this.repeat = new Vector2( 1, 1 );
  1982. this.center = new Vector2( 0, 0 );
  1983. this.rotation = 0;
  1984. this.matrixAutoUpdate = true;
  1985. this.matrix = new Matrix3();
  1986. this.generateMipmaps = true;
  1987. this.premultiplyAlpha = false;
  1988. this.flipY = true;
  1989. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1990. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1991. //
  1992. // Also changing the encoding after already used by a Material will not automatically make the Material
  1993. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1994. this.encoding = encoding;
  1995. this.userData = {};
  1996. this.version = 0;
  1997. this.onUpdate = null;
  1998. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1999. this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  2000. }
  2001. get image() {
  2002. return this.source.data;
  2003. }
  2004. set image( value = null ) {
  2005. this.source.data = value;
  2006. }
  2007. updateMatrix() {
  2008. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  2009. }
  2010. clone() {
  2011. return new this.constructor().copy( this );
  2012. }
  2013. copy( source ) {
  2014. this.name = source.name;
  2015. this.source = source.source;
  2016. this.mipmaps = source.mipmaps.slice( 0 );
  2017. this.mapping = source.mapping;
  2018. this.wrapS = source.wrapS;
  2019. this.wrapT = source.wrapT;
  2020. this.magFilter = source.magFilter;
  2021. this.minFilter = source.minFilter;
  2022. this.anisotropy = source.anisotropy;
  2023. this.format = source.format;
  2024. this.internalFormat = source.internalFormat;
  2025. this.type = source.type;
  2026. this.offset.copy( source.offset );
  2027. this.repeat.copy( source.repeat );
  2028. this.center.copy( source.center );
  2029. this.rotation = source.rotation;
  2030. this.matrixAutoUpdate = source.matrixAutoUpdate;
  2031. this.matrix.copy( source.matrix );
  2032. this.generateMipmaps = source.generateMipmaps;
  2033. this.premultiplyAlpha = source.premultiplyAlpha;
  2034. this.flipY = source.flipY;
  2035. this.unpackAlignment = source.unpackAlignment;
  2036. this.encoding = source.encoding;
  2037. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  2038. this.needsUpdate = true;
  2039. return this;
  2040. }
  2041. toJSON( meta ) {
  2042. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  2043. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  2044. return meta.textures[ this.uuid ];
  2045. }
  2046. const output = {
  2047. metadata: {
  2048. version: 4.5,
  2049. type: 'Texture',
  2050. generator: 'Texture.toJSON'
  2051. },
  2052. uuid: this.uuid,
  2053. name: this.name,
  2054. image: this.source.toJSON( meta ).uuid,
  2055. mapping: this.mapping,
  2056. repeat: [ this.repeat.x, this.repeat.y ],
  2057. offset: [ this.offset.x, this.offset.y ],
  2058. center: [ this.center.x, this.center.y ],
  2059. rotation: this.rotation,
  2060. wrap: [ this.wrapS, this.wrapT ],
  2061. format: this.format,
  2062. internalFormat: this.internalFormat,
  2063. type: this.type,
  2064. encoding: this.encoding,
  2065. minFilter: this.minFilter,
  2066. magFilter: this.magFilter,
  2067. anisotropy: this.anisotropy,
  2068. flipY: this.flipY,
  2069. generateMipmaps: this.generateMipmaps,
  2070. premultiplyAlpha: this.premultiplyAlpha,
  2071. unpackAlignment: this.unpackAlignment
  2072. };
  2073. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  2074. if ( ! isRootObject ) {
  2075. meta.textures[ this.uuid ] = output;
  2076. }
  2077. return output;
  2078. }
  2079. dispose() {
  2080. this.dispatchEvent( { type: 'dispose' } );
  2081. }
  2082. transformUv( uv ) {
  2083. if ( this.mapping !== UVMapping ) return uv;
  2084. uv.applyMatrix3( this.matrix );
  2085. if ( uv.x < 0 || uv.x > 1 ) {
  2086. switch ( this.wrapS ) {
  2087. case RepeatWrapping:
  2088. uv.x = uv.x - Math.floor( uv.x );
  2089. break;
  2090. case ClampToEdgeWrapping:
  2091. uv.x = uv.x < 0 ? 0 : 1;
  2092. break;
  2093. case MirroredRepeatWrapping:
  2094. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  2095. uv.x = Math.ceil( uv.x ) - uv.x;
  2096. } else {
  2097. uv.x = uv.x - Math.floor( uv.x );
  2098. }
  2099. break;
  2100. }
  2101. }
  2102. if ( uv.y < 0 || uv.y > 1 ) {
  2103. switch ( this.wrapT ) {
  2104. case RepeatWrapping:
  2105. uv.y = uv.y - Math.floor( uv.y );
  2106. break;
  2107. case ClampToEdgeWrapping:
  2108. uv.y = uv.y < 0 ? 0 : 1;
  2109. break;
  2110. case MirroredRepeatWrapping:
  2111. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  2112. uv.y = Math.ceil( uv.y ) - uv.y;
  2113. } else {
  2114. uv.y = uv.y - Math.floor( uv.y );
  2115. }
  2116. break;
  2117. }
  2118. }
  2119. if ( this.flipY ) {
  2120. uv.y = 1 - uv.y;
  2121. }
  2122. return uv;
  2123. }
  2124. set needsUpdate( value ) {
  2125. if ( value === true ) {
  2126. this.version ++;
  2127. this.source.needsUpdate = true;
  2128. }
  2129. }
  2130. }
  2131. Texture.DEFAULT_IMAGE = null;
  2132. Texture.DEFAULT_MAPPING = UVMapping;
  2133. Texture.DEFAULT_ANISOTROPY = 1;
  2134. class Vector4 {
  2135. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2136. Vector4.prototype.isVector4 = true;
  2137. this.x = x;
  2138. this.y = y;
  2139. this.z = z;
  2140. this.w = w;
  2141. }
  2142. get width() {
  2143. return this.z;
  2144. }
  2145. set width( value ) {
  2146. this.z = value;
  2147. }
  2148. get height() {
  2149. return this.w;
  2150. }
  2151. set height( value ) {
  2152. this.w = value;
  2153. }
  2154. set( x, y, z, w ) {
  2155. this.x = x;
  2156. this.y = y;
  2157. this.z = z;
  2158. this.w = w;
  2159. return this;
  2160. }
  2161. setScalar( scalar ) {
  2162. this.x = scalar;
  2163. this.y = scalar;
  2164. this.z = scalar;
  2165. this.w = scalar;
  2166. return this;
  2167. }
  2168. setX( x ) {
  2169. this.x = x;
  2170. return this;
  2171. }
  2172. setY( y ) {
  2173. this.y = y;
  2174. return this;
  2175. }
  2176. setZ( z ) {
  2177. this.z = z;
  2178. return this;
  2179. }
  2180. setW( w ) {
  2181. this.w = w;
  2182. return this;
  2183. }
  2184. setComponent( index, value ) {
  2185. switch ( index ) {
  2186. case 0: this.x = value; break;
  2187. case 1: this.y = value; break;
  2188. case 2: this.z = value; break;
  2189. case 3: this.w = value; break;
  2190. default: throw new Error( 'index is out of range: ' + index );
  2191. }
  2192. return this;
  2193. }
  2194. getComponent( index ) {
  2195. switch ( index ) {
  2196. case 0: return this.x;
  2197. case 1: return this.y;
  2198. case 2: return this.z;
  2199. case 3: return this.w;
  2200. default: throw new Error( 'index is out of range: ' + index );
  2201. }
  2202. }
  2203. clone() {
  2204. return new this.constructor( this.x, this.y, this.z, this.w );
  2205. }
  2206. copy( v ) {
  2207. this.x = v.x;
  2208. this.y = v.y;
  2209. this.z = v.z;
  2210. this.w = ( v.w !== undefined ) ? v.w : 1;
  2211. return this;
  2212. }
  2213. add( v ) {
  2214. this.x += v.x;
  2215. this.y += v.y;
  2216. this.z += v.z;
  2217. this.w += v.w;
  2218. return this;
  2219. }
  2220. addScalar( s ) {
  2221. this.x += s;
  2222. this.y += s;
  2223. this.z += s;
  2224. this.w += s;
  2225. return this;
  2226. }
  2227. addVectors( a, b ) {
  2228. this.x = a.x + b.x;
  2229. this.y = a.y + b.y;
  2230. this.z = a.z + b.z;
  2231. this.w = a.w + b.w;
  2232. return this;
  2233. }
  2234. addScaledVector( v, s ) {
  2235. this.x += v.x * s;
  2236. this.y += v.y * s;
  2237. this.z += v.z * s;
  2238. this.w += v.w * s;
  2239. return this;
  2240. }
  2241. sub( v ) {
  2242. this.x -= v.x;
  2243. this.y -= v.y;
  2244. this.z -= v.z;
  2245. this.w -= v.w;
  2246. return this;
  2247. }
  2248. subScalar( s ) {
  2249. this.x -= s;
  2250. this.y -= s;
  2251. this.z -= s;
  2252. this.w -= s;
  2253. return this;
  2254. }
  2255. subVectors( a, b ) {
  2256. this.x = a.x - b.x;
  2257. this.y = a.y - b.y;
  2258. this.z = a.z - b.z;
  2259. this.w = a.w - b.w;
  2260. return this;
  2261. }
  2262. multiply( v ) {
  2263. this.x *= v.x;
  2264. this.y *= v.y;
  2265. this.z *= v.z;
  2266. this.w *= v.w;
  2267. return this;
  2268. }
  2269. multiplyScalar( scalar ) {
  2270. this.x *= scalar;
  2271. this.y *= scalar;
  2272. this.z *= scalar;
  2273. this.w *= scalar;
  2274. return this;
  2275. }
  2276. applyMatrix4( m ) {
  2277. const x = this.x, y = this.y, z = this.z, w = this.w;
  2278. const e = m.elements;
  2279. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  2280. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  2281. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  2282. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  2283. return this;
  2284. }
  2285. divideScalar( scalar ) {
  2286. return this.multiplyScalar( 1 / scalar );
  2287. }
  2288. setAxisAngleFromQuaternion( q ) {
  2289. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  2290. // q is assumed to be normalized
  2291. this.w = 2 * Math.acos( q.w );
  2292. const s = Math.sqrt( 1 - q.w * q.w );
  2293. if ( s < 0.0001 ) {
  2294. this.x = 1;
  2295. this.y = 0;
  2296. this.z = 0;
  2297. } else {
  2298. this.x = q.x / s;
  2299. this.y = q.y / s;
  2300. this.z = q.z / s;
  2301. }
  2302. return this;
  2303. }
  2304. setAxisAngleFromRotationMatrix( m ) {
  2305. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  2306. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2307. let angle, x, y, z; // variables for result
  2308. const epsilon = 0.01, // margin to allow for rounding errors
  2309. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  2310. te = m.elements,
  2311. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2312. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2313. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  2314. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  2315. ( Math.abs( m13 - m31 ) < epsilon ) &&
  2316. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  2317. // singularity found
  2318. // first check for identity matrix which must have +1 for all terms
  2319. // in leading diagonal and zero in other terms
  2320. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  2321. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  2322. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  2323. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  2324. // this singularity is identity matrix so angle = 0
  2325. this.set( 1, 0, 0, 0 );
  2326. return this; // zero angle, arbitrary axis
  2327. }
  2328. // otherwise this singularity is angle = 180
  2329. angle = Math.PI;
  2330. const xx = ( m11 + 1 ) / 2;
  2331. const yy = ( m22 + 1 ) / 2;
  2332. const zz = ( m33 + 1 ) / 2;
  2333. const xy = ( m12 + m21 ) / 4;
  2334. const xz = ( m13 + m31 ) / 4;
  2335. const yz = ( m23 + m32 ) / 4;
  2336. if ( ( xx > yy ) && ( xx > zz ) ) {
  2337. // m11 is the largest diagonal term
  2338. if ( xx < epsilon ) {
  2339. x = 0;
  2340. y = 0.707106781;
  2341. z = 0.707106781;
  2342. } else {
  2343. x = Math.sqrt( xx );
  2344. y = xy / x;
  2345. z = xz / x;
  2346. }
  2347. } else if ( yy > zz ) {
  2348. // m22 is the largest diagonal term
  2349. if ( yy < epsilon ) {
  2350. x = 0.707106781;
  2351. y = 0;
  2352. z = 0.707106781;
  2353. } else {
  2354. y = Math.sqrt( yy );
  2355. x = xy / y;
  2356. z = yz / y;
  2357. }
  2358. } else {
  2359. // m33 is the largest diagonal term so base result on this
  2360. if ( zz < epsilon ) {
  2361. x = 0.707106781;
  2362. y = 0.707106781;
  2363. z = 0;
  2364. } else {
  2365. z = Math.sqrt( zz );
  2366. x = xz / z;
  2367. y = yz / z;
  2368. }
  2369. }
  2370. this.set( x, y, z, angle );
  2371. return this; // return 180 deg rotation
  2372. }
  2373. // as we have reached here there are no singularities so we can handle normally
  2374. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  2375. ( m13 - m31 ) * ( m13 - m31 ) +
  2376. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  2377. if ( Math.abs( s ) < 0.001 ) s = 1;
  2378. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  2379. // caught by singularity test above, but I've left it in just in case
  2380. this.x = ( m32 - m23 ) / s;
  2381. this.y = ( m13 - m31 ) / s;
  2382. this.z = ( m21 - m12 ) / s;
  2383. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  2384. return this;
  2385. }
  2386. min( v ) {
  2387. this.x = Math.min( this.x, v.x );
  2388. this.y = Math.min( this.y, v.y );
  2389. this.z = Math.min( this.z, v.z );
  2390. this.w = Math.min( this.w, v.w );
  2391. return this;
  2392. }
  2393. max( v ) {
  2394. this.x = Math.max( this.x, v.x );
  2395. this.y = Math.max( this.y, v.y );
  2396. this.z = Math.max( this.z, v.z );
  2397. this.w = Math.max( this.w, v.w );
  2398. return this;
  2399. }
  2400. clamp( min, max ) {
  2401. // assumes min < max, componentwise
  2402. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2403. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2404. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2405. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  2406. return this;
  2407. }
  2408. clampScalar( minVal, maxVal ) {
  2409. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2410. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2411. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2412. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  2413. return this;
  2414. }
  2415. clampLength( min, max ) {
  2416. const length = this.length();
  2417. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2418. }
  2419. floor() {
  2420. this.x = Math.floor( this.x );
  2421. this.y = Math.floor( this.y );
  2422. this.z = Math.floor( this.z );
  2423. this.w = Math.floor( this.w );
  2424. return this;
  2425. }
  2426. ceil() {
  2427. this.x = Math.ceil( this.x );
  2428. this.y = Math.ceil( this.y );
  2429. this.z = Math.ceil( this.z );
  2430. this.w = Math.ceil( this.w );
  2431. return this;
  2432. }
  2433. round() {
  2434. this.x = Math.round( this.x );
  2435. this.y = Math.round( this.y );
  2436. this.z = Math.round( this.z );
  2437. this.w = Math.round( this.w );
  2438. return this;
  2439. }
  2440. roundToZero() {
  2441. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2442. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2443. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2444. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  2445. return this;
  2446. }
  2447. negate() {
  2448. this.x = - this.x;
  2449. this.y = - this.y;
  2450. this.z = - this.z;
  2451. this.w = - this.w;
  2452. return this;
  2453. }
  2454. dot( v ) {
  2455. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  2456. }
  2457. lengthSq() {
  2458. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  2459. }
  2460. length() {
  2461. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2462. }
  2463. manhattanLength() {
  2464. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  2465. }
  2466. normalize() {
  2467. return this.divideScalar( this.length() || 1 );
  2468. }
  2469. setLength( length ) {
  2470. return this.normalize().multiplyScalar( length );
  2471. }
  2472. lerp( v, alpha ) {
  2473. this.x += ( v.x - this.x ) * alpha;
  2474. this.y += ( v.y - this.y ) * alpha;
  2475. this.z += ( v.z - this.z ) * alpha;
  2476. this.w += ( v.w - this.w ) * alpha;
  2477. return this;
  2478. }
  2479. lerpVectors( v1, v2, alpha ) {
  2480. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2481. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2482. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2483. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  2484. return this;
  2485. }
  2486. equals( v ) {
  2487. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  2488. }
  2489. fromArray( array, offset = 0 ) {
  2490. this.x = array[ offset ];
  2491. this.y = array[ offset + 1 ];
  2492. this.z = array[ offset + 2 ];
  2493. this.w = array[ offset + 3 ];
  2494. return this;
  2495. }
  2496. toArray( array = [], offset = 0 ) {
  2497. array[ offset ] = this.x;
  2498. array[ offset + 1 ] = this.y;
  2499. array[ offset + 2 ] = this.z;
  2500. array[ offset + 3 ] = this.w;
  2501. return array;
  2502. }
  2503. fromBufferAttribute( attribute, index ) {
  2504. this.x = attribute.getX( index );
  2505. this.y = attribute.getY( index );
  2506. this.z = attribute.getZ( index );
  2507. this.w = attribute.getW( index );
  2508. return this;
  2509. }
  2510. random() {
  2511. this.x = Math.random();
  2512. this.y = Math.random();
  2513. this.z = Math.random();
  2514. this.w = Math.random();
  2515. return this;
  2516. }
  2517. *[ Symbol.iterator ]() {
  2518. yield this.x;
  2519. yield this.y;
  2520. yield this.z;
  2521. yield this.w;
  2522. }
  2523. }
  2524. /*
  2525. In options, we can specify:
  2526. * Texture parameters for an auto-generated target texture
  2527. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  2528. */
  2529. class WebGLRenderTarget extends EventDispatcher {
  2530. constructor( width = 1, height = 1, options = {} ) {
  2531. super();
  2532. this.isWebGLRenderTarget = true;
  2533. this.width = width;
  2534. this.height = height;
  2535. this.depth = 1;
  2536. this.scissor = new Vector4( 0, 0, width, height );
  2537. this.scissorTest = false;
  2538. this.viewport = new Vector4( 0, 0, width, height );
  2539. const image = { width: width, height: height, depth: 1 };
  2540. this.texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  2541. this.texture.isRenderTargetTexture = true;
  2542. this.texture.flipY = false;
  2543. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2544. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  2545. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2546. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2547. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  2548. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2549. this.samples = options.samples !== undefined ? options.samples : 0;
  2550. }
  2551. setSize( width, height, depth = 1 ) {
  2552. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  2553. this.width = width;
  2554. this.height = height;
  2555. this.depth = depth;
  2556. this.texture.image.width = width;
  2557. this.texture.image.height = height;
  2558. this.texture.image.depth = depth;
  2559. this.dispose();
  2560. }
  2561. this.viewport.set( 0, 0, width, height );
  2562. this.scissor.set( 0, 0, width, height );
  2563. }
  2564. clone() {
  2565. return new this.constructor().copy( this );
  2566. }
  2567. copy( source ) {
  2568. this.width = source.width;
  2569. this.height = source.height;
  2570. this.depth = source.depth;
  2571. this.viewport.copy( source.viewport );
  2572. this.texture = source.texture.clone();
  2573. this.texture.isRenderTargetTexture = true;
  2574. // ensure image object is not shared, see #20328
  2575. const image = Object.assign( {}, source.texture.image );
  2576. this.texture.source = new Source( image );
  2577. this.depthBuffer = source.depthBuffer;
  2578. this.stencilBuffer = source.stencilBuffer;
  2579. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  2580. this.samples = source.samples;
  2581. return this;
  2582. }
  2583. dispose() {
  2584. this.dispatchEvent( { type: 'dispose' } );
  2585. }
  2586. }
  2587. class DataArrayTexture extends Texture {
  2588. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  2589. super( null );
  2590. this.isDataArrayTexture = true;
  2591. this.image = { data, width, height, depth };
  2592. this.magFilter = NearestFilter;
  2593. this.minFilter = NearestFilter;
  2594. this.wrapR = ClampToEdgeWrapping;
  2595. this.generateMipmaps = false;
  2596. this.flipY = false;
  2597. this.unpackAlignment = 1;
  2598. }
  2599. }
  2600. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  2601. constructor( width = 1, height = 1, depth = 1 ) {
  2602. super( width, height );
  2603. this.isWebGLArrayRenderTarget = true;
  2604. this.depth = depth;
  2605. this.texture = new DataArrayTexture( null, width, height, depth );
  2606. this.texture.isRenderTargetTexture = true;
  2607. }
  2608. }
  2609. class Data3DTexture extends Texture {
  2610. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  2611. // We're going to add .setXXX() methods for setting properties later.
  2612. // Users can still set in DataTexture3D directly.
  2613. //
  2614. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  2615. // texture.anisotropy = 16;
  2616. //
  2617. // See #14839
  2618. super( null );
  2619. this.isData3DTexture = true;
  2620. this.image = { data, width, height, depth };
  2621. this.magFilter = NearestFilter;
  2622. this.minFilter = NearestFilter;
  2623. this.wrapR = ClampToEdgeWrapping;
  2624. this.generateMipmaps = false;
  2625. this.flipY = false;
  2626. this.unpackAlignment = 1;
  2627. }
  2628. }
  2629. class WebGL3DRenderTarget extends WebGLRenderTarget {
  2630. constructor( width = 1, height = 1, depth = 1 ) {
  2631. super( width, height );
  2632. this.isWebGL3DRenderTarget = true;
  2633. this.depth = depth;
  2634. this.texture = new Data3DTexture( null, width, height, depth );
  2635. this.texture.isRenderTargetTexture = true;
  2636. }
  2637. }
  2638. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  2639. constructor( width = 1, height = 1, count = 1, options = {} ) {
  2640. super( width, height, options );
  2641. this.isWebGLMultipleRenderTargets = true;
  2642. const texture = this.texture;
  2643. this.texture = [];
  2644. for ( let i = 0; i < count; i ++ ) {
  2645. this.texture[ i ] = texture.clone();
  2646. this.texture[ i ].isRenderTargetTexture = true;
  2647. }
  2648. }
  2649. setSize( width, height, depth = 1 ) {
  2650. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  2651. this.width = width;
  2652. this.height = height;
  2653. this.depth = depth;
  2654. for ( let i = 0, il = this.texture.length; i < il; i ++ ) {
  2655. this.texture[ i ].image.width = width;
  2656. this.texture[ i ].image.height = height;
  2657. this.texture[ i ].image.depth = depth;
  2658. }
  2659. this.dispose();
  2660. }
  2661. this.viewport.set( 0, 0, width, height );
  2662. this.scissor.set( 0, 0, width, height );
  2663. return this;
  2664. }
  2665. copy( source ) {
  2666. this.dispose();
  2667. this.width = source.width;
  2668. this.height = source.height;
  2669. this.depth = source.depth;
  2670. this.viewport.set( 0, 0, this.width, this.height );
  2671. this.scissor.set( 0, 0, this.width, this.height );
  2672. this.depthBuffer = source.depthBuffer;
  2673. this.stencilBuffer = source.stencilBuffer;
  2674. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  2675. this.texture.length = 0;
  2676. for ( let i = 0, il = source.texture.length; i < il; i ++ ) {
  2677. this.texture[ i ] = source.texture[ i ].clone();
  2678. this.texture[ i ].isRenderTargetTexture = true;
  2679. }
  2680. return this;
  2681. }
  2682. }
  2683. class Box3 {
  2684. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2685. this.isBox3 = true;
  2686. this.min = min;
  2687. this.max = max;
  2688. }
  2689. set( min, max ) {
  2690. this.min.copy( min );
  2691. this.max.copy( max );
  2692. return this;
  2693. }
  2694. setFromArray( array ) {
  2695. let minX = + Infinity;
  2696. let minY = + Infinity;
  2697. let minZ = + Infinity;
  2698. let maxX = - Infinity;
  2699. let maxY = - Infinity;
  2700. let maxZ = - Infinity;
  2701. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  2702. const x = array[ i ];
  2703. const y = array[ i + 1 ];
  2704. const z = array[ i + 2 ];
  2705. if ( x < minX ) minX = x;
  2706. if ( y < minY ) minY = y;
  2707. if ( z < minZ ) minZ = z;
  2708. if ( x > maxX ) maxX = x;
  2709. if ( y > maxY ) maxY = y;
  2710. if ( z > maxZ ) maxZ = z;
  2711. }
  2712. this.min.set( minX, minY, minZ );
  2713. this.max.set( maxX, maxY, maxZ );
  2714. return this;
  2715. }
  2716. setFromBufferAttribute( attribute ) {
  2717. let minX = + Infinity;
  2718. let minY = + Infinity;
  2719. let minZ = + Infinity;
  2720. let maxX = - Infinity;
  2721. let maxY = - Infinity;
  2722. let maxZ = - Infinity;
  2723. for ( let i = 0, l = attribute.count; i < l; i ++ ) {
  2724. const x = attribute.getX( i );
  2725. const y = attribute.getY( i );
  2726. const z = attribute.getZ( i );
  2727. if ( x < minX ) minX = x;
  2728. if ( y < minY ) minY = y;
  2729. if ( z < minZ ) minZ = z;
  2730. if ( x > maxX ) maxX = x;
  2731. if ( y > maxY ) maxY = y;
  2732. if ( z > maxZ ) maxZ = z;
  2733. }
  2734. this.min.set( minX, minY, minZ );
  2735. this.max.set( maxX, maxY, maxZ );
  2736. return this;
  2737. }
  2738. setFromPoints( points ) {
  2739. this.makeEmpty();
  2740. for ( let i = 0, il = points.length; i < il; i ++ ) {
  2741. this.expandByPoint( points[ i ] );
  2742. }
  2743. return this;
  2744. }
  2745. setFromCenterAndSize( center, size ) {
  2746. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  2747. this.min.copy( center ).sub( halfSize );
  2748. this.max.copy( center ).add( halfSize );
  2749. return this;
  2750. }
  2751. setFromObject( object, precise = false ) {
  2752. this.makeEmpty();
  2753. return this.expandByObject( object, precise );
  2754. }
  2755. clone() {
  2756. return new this.constructor().copy( this );
  2757. }
  2758. copy( box ) {
  2759. this.min.copy( box.min );
  2760. this.max.copy( box.max );
  2761. return this;
  2762. }
  2763. makeEmpty() {
  2764. this.min.x = this.min.y = this.min.z = + Infinity;
  2765. this.max.x = this.max.y = this.max.z = - Infinity;
  2766. return this;
  2767. }
  2768. isEmpty() {
  2769. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2770. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2771. }
  2772. getCenter( target ) {
  2773. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2774. }
  2775. getSize( target ) {
  2776. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  2777. }
  2778. expandByPoint( point ) {
  2779. this.min.min( point );
  2780. this.max.max( point );
  2781. return this;
  2782. }
  2783. expandByVector( vector ) {
  2784. this.min.sub( vector );
  2785. this.max.add( vector );
  2786. return this;
  2787. }
  2788. expandByScalar( scalar ) {
  2789. this.min.addScalar( - scalar );
  2790. this.max.addScalar( scalar );
  2791. return this;
  2792. }
  2793. expandByObject( object, precise = false ) {
  2794. // Computes the world-axis-aligned bounding box of an object (including its children),
  2795. // accounting for both the object's, and children's, world transforms
  2796. object.updateWorldMatrix( false, false );
  2797. const geometry = object.geometry;
  2798. if ( geometry !== undefined ) {
  2799. if ( precise && geometry.attributes != undefined && geometry.attributes.position !== undefined ) {
  2800. const position = geometry.attributes.position;
  2801. for ( let i = 0, l = position.count; i < l; i ++ ) {
  2802. _vector$b.fromBufferAttribute( position, i ).applyMatrix4( object.matrixWorld );
  2803. this.expandByPoint( _vector$b );
  2804. }
  2805. } else {
  2806. if ( geometry.boundingBox === null ) {
  2807. geometry.computeBoundingBox();
  2808. }
  2809. _box$3.copy( geometry.boundingBox );
  2810. _box$3.applyMatrix4( object.matrixWorld );
  2811. this.union( _box$3 );
  2812. }
  2813. }
  2814. const children = object.children;
  2815. for ( let i = 0, l = children.length; i < l; i ++ ) {
  2816. this.expandByObject( children[ i ], precise );
  2817. }
  2818. return this;
  2819. }
  2820. containsPoint( point ) {
  2821. return point.x < this.min.x || point.x > this.max.x ||
  2822. point.y < this.min.y || point.y > this.max.y ||
  2823. point.z < this.min.z || point.z > this.max.z ? false : true;
  2824. }
  2825. containsBox( box ) {
  2826. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  2827. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  2828. this.min.z <= box.min.z && box.max.z <= this.max.z;
  2829. }
  2830. getParameter( point, target ) {
  2831. // This can potentially have a divide by zero if the box
  2832. // has a size dimension of 0.
  2833. return target.set(
  2834. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2835. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2836. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2837. );
  2838. }
  2839. intersectsBox( box ) {
  2840. // using 6 splitting planes to rule out intersections.
  2841. return box.max.x < this.min.x || box.min.x > this.max.x ||
  2842. box.max.y < this.min.y || box.min.y > this.max.y ||
  2843. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  2844. }
  2845. intersectsSphere( sphere ) {
  2846. // Find the point on the AABB closest to the sphere center.
  2847. this.clampPoint( sphere.center, _vector$b );
  2848. // If that point is inside the sphere, the AABB and sphere intersect.
  2849. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2850. }
  2851. intersectsPlane( plane ) {
  2852. // We compute the minimum and maximum dot product values. If those values
  2853. // are on the same side (back or front) of the plane, then there is no intersection.
  2854. let min, max;
  2855. if ( plane.normal.x > 0 ) {
  2856. min = plane.normal.x * this.min.x;
  2857. max = plane.normal.x * this.max.x;
  2858. } else {
  2859. min = plane.normal.x * this.max.x;
  2860. max = plane.normal.x * this.min.x;
  2861. }
  2862. if ( plane.normal.y > 0 ) {
  2863. min += plane.normal.y * this.min.y;
  2864. max += plane.normal.y * this.max.y;
  2865. } else {
  2866. min += plane.normal.y * this.max.y;
  2867. max += plane.normal.y * this.min.y;
  2868. }
  2869. if ( plane.normal.z > 0 ) {
  2870. min += plane.normal.z * this.min.z;
  2871. max += plane.normal.z * this.max.z;
  2872. } else {
  2873. min += plane.normal.z * this.max.z;
  2874. max += plane.normal.z * this.min.z;
  2875. }
  2876. return ( min <= - plane.constant && max >= - plane.constant );
  2877. }
  2878. intersectsTriangle( triangle ) {
  2879. if ( this.isEmpty() ) {
  2880. return false;
  2881. }
  2882. // compute box center and extents
  2883. this.getCenter( _center );
  2884. _extents.subVectors( this.max, _center );
  2885. // translate triangle to aabb origin
  2886. _v0$2.subVectors( triangle.a, _center );
  2887. _v1$7.subVectors( triangle.b, _center );
  2888. _v2$4.subVectors( triangle.c, _center );
  2889. // compute edge vectors for triangle
  2890. _f0.subVectors( _v1$7, _v0$2 );
  2891. _f1.subVectors( _v2$4, _v1$7 );
  2892. _f2.subVectors( _v0$2, _v2$4 );
  2893. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  2894. // 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
  2895. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  2896. let axes = [
  2897. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  2898. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  2899. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  2900. ];
  2901. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2902. return false;
  2903. }
  2904. // test 3 face normals from the aabb
  2905. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  2906. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents ) ) {
  2907. return false;
  2908. }
  2909. // finally testing the face normal of the triangle
  2910. // use already existing triangle edge vectors here
  2911. _triangleNormal.crossVectors( _f0, _f1 );
  2912. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  2913. return satForAxes( axes, _v0$2, _v1$7, _v2$4, _extents );
  2914. }
  2915. clampPoint( point, target ) {
  2916. return target.copy( point ).clamp( this.min, this.max );
  2917. }
  2918. distanceToPoint( point ) {
  2919. return this.clampPoint( point, _vector$b ).distanceTo( point );
  2920. }
  2921. getBoundingSphere( target ) {
  2922. if ( this.isEmpty() ) {
  2923. target.makeEmpty();
  2924. } else {
  2925. this.getCenter( target.center );
  2926. target.radius = this.getSize( _vector$b ).length() * 0.5;
  2927. }
  2928. return target;
  2929. }
  2930. intersect( box ) {
  2931. this.min.max( box.min );
  2932. this.max.min( box.max );
  2933. // 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.
  2934. if ( this.isEmpty() ) this.makeEmpty();
  2935. return this;
  2936. }
  2937. union( box ) {
  2938. this.min.min( box.min );
  2939. this.max.max( box.max );
  2940. return this;
  2941. }
  2942. applyMatrix4( matrix ) {
  2943. // transform of empty box is an empty box.
  2944. if ( this.isEmpty() ) return this;
  2945. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2946. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2947. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2948. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2949. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2950. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2951. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2952. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2953. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2954. this.setFromPoints( _points );
  2955. return this;
  2956. }
  2957. translate( offset ) {
  2958. this.min.add( offset );
  2959. this.max.add( offset );
  2960. return this;
  2961. }
  2962. equals( box ) {
  2963. return box.min.equals( this.min ) && box.max.equals( this.max );
  2964. }
  2965. }
  2966. const _points = [
  2967. /*@__PURE__*/ new Vector3(),
  2968. /*@__PURE__*/ new Vector3(),
  2969. /*@__PURE__*/ new Vector3(),
  2970. /*@__PURE__*/ new Vector3(),
  2971. /*@__PURE__*/ new Vector3(),
  2972. /*@__PURE__*/ new Vector3(),
  2973. /*@__PURE__*/ new Vector3(),
  2974. /*@__PURE__*/ new Vector3()
  2975. ];
  2976. const _vector$b = /*@__PURE__*/ new Vector3();
  2977. const _box$3 = /*@__PURE__*/ new Box3();
  2978. // triangle centered vertices
  2979. const _v0$2 = /*@__PURE__*/ new Vector3();
  2980. const _v1$7 = /*@__PURE__*/ new Vector3();
  2981. const _v2$4 = /*@__PURE__*/ new Vector3();
  2982. // triangle edge vectors
  2983. const _f0 = /*@__PURE__*/ new Vector3();
  2984. const _f1 = /*@__PURE__*/ new Vector3();
  2985. const _f2 = /*@__PURE__*/ new Vector3();
  2986. const _center = /*@__PURE__*/ new Vector3();
  2987. const _extents = /*@__PURE__*/ new Vector3();
  2988. const _triangleNormal = /*@__PURE__*/ new Vector3();
  2989. const _testAxis = /*@__PURE__*/ new Vector3();
  2990. function satForAxes( axes, v0, v1, v2, extents ) {
  2991. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  2992. _testAxis.fromArray( axes, i );
  2993. // project the aabb onto the separating axis
  2994. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  2995. // project all 3 vertices of the triangle onto the separating axis
  2996. const p0 = v0.dot( _testAxis );
  2997. const p1 = v1.dot( _testAxis );
  2998. const p2 = v2.dot( _testAxis );
  2999. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3000. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3001. // points of the projected triangle are outside the projected half-length of the aabb
  3002. // the axis is separating and we can exit
  3003. return false;
  3004. }
  3005. }
  3006. return true;
  3007. }
  3008. const _box$2 = /*@__PURE__*/ new Box3();
  3009. const _v1$6 = /*@__PURE__*/ new Vector3();
  3010. const _v2$3 = /*@__PURE__*/ new Vector3();
  3011. class Sphere {
  3012. constructor( center = new Vector3(), radius = - 1 ) {
  3013. this.center = center;
  3014. this.radius = radius;
  3015. }
  3016. set( center, radius ) {
  3017. this.center.copy( center );
  3018. this.radius = radius;
  3019. return this;
  3020. }
  3021. setFromPoints( points, optionalCenter ) {
  3022. const center = this.center;
  3023. if ( optionalCenter !== undefined ) {
  3024. center.copy( optionalCenter );
  3025. } else {
  3026. _box$2.setFromPoints( points ).getCenter( center );
  3027. }
  3028. let maxRadiusSq = 0;
  3029. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3030. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3031. }
  3032. this.radius = Math.sqrt( maxRadiusSq );
  3033. return this;
  3034. }
  3035. copy( sphere ) {
  3036. this.center.copy( sphere.center );
  3037. this.radius = sphere.radius;
  3038. return this;
  3039. }
  3040. isEmpty() {
  3041. return ( this.radius < 0 );
  3042. }
  3043. makeEmpty() {
  3044. this.center.set( 0, 0, 0 );
  3045. this.radius = - 1;
  3046. return this;
  3047. }
  3048. containsPoint( point ) {
  3049. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3050. }
  3051. distanceToPoint( point ) {
  3052. return ( point.distanceTo( this.center ) - this.radius );
  3053. }
  3054. intersectsSphere( sphere ) {
  3055. const radiusSum = this.radius + sphere.radius;
  3056. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3057. }
  3058. intersectsBox( box ) {
  3059. return box.intersectsSphere( this );
  3060. }
  3061. intersectsPlane( plane ) {
  3062. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3063. }
  3064. clampPoint( point, target ) {
  3065. const deltaLengthSq = this.center.distanceToSquared( point );
  3066. target.copy( point );
  3067. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3068. target.sub( this.center ).normalize();
  3069. target.multiplyScalar( this.radius ).add( this.center );
  3070. }
  3071. return target;
  3072. }
  3073. getBoundingBox( target ) {
  3074. if ( this.isEmpty() ) {
  3075. // Empty sphere produces empty bounding box
  3076. target.makeEmpty();
  3077. return target;
  3078. }
  3079. target.set( this.center, this.center );
  3080. target.expandByScalar( this.radius );
  3081. return target;
  3082. }
  3083. applyMatrix4( matrix ) {
  3084. this.center.applyMatrix4( matrix );
  3085. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3086. return this;
  3087. }
  3088. translate( offset ) {
  3089. this.center.add( offset );
  3090. return this;
  3091. }
  3092. expandByPoint( point ) {
  3093. if ( this.isEmpty() ) {
  3094. this.center.copy( point );
  3095. this.radius = 0;
  3096. return this;
  3097. }
  3098. _v1$6.subVectors( point, this.center );
  3099. const lengthSq = _v1$6.lengthSq();
  3100. if ( lengthSq > ( this.radius * this.radius ) ) {
  3101. // calculate the minimal sphere
  3102. const length = Math.sqrt( lengthSq );
  3103. const delta = ( length - this.radius ) * 0.5;
  3104. this.center.addScaledVector( _v1$6, delta / length );
  3105. this.radius += delta;
  3106. }
  3107. return this;
  3108. }
  3109. union( sphere ) {
  3110. if ( sphere.isEmpty() ) {
  3111. return this;
  3112. }
  3113. if ( this.isEmpty() ) {
  3114. this.copy( sphere );
  3115. return this;
  3116. }
  3117. if ( this.center.equals( sphere.center ) === true ) {
  3118. this.radius = Math.max( this.radius, sphere.radius );
  3119. } else {
  3120. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  3121. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  3122. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  3123. }
  3124. return this;
  3125. }
  3126. equals( sphere ) {
  3127. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3128. }
  3129. clone() {
  3130. return new this.constructor().copy( this );
  3131. }
  3132. }
  3133. const _vector$a = /*@__PURE__*/ new Vector3();
  3134. const _segCenter = /*@__PURE__*/ new Vector3();
  3135. const _segDir = /*@__PURE__*/ new Vector3();
  3136. const _diff = /*@__PURE__*/ new Vector3();
  3137. const _edge1 = /*@__PURE__*/ new Vector3();
  3138. const _edge2 = /*@__PURE__*/ new Vector3();
  3139. const _normal$1 = /*@__PURE__*/ new Vector3();
  3140. class Ray {
  3141. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3142. this.origin = origin;
  3143. this.direction = direction;
  3144. }
  3145. set( origin, direction ) {
  3146. this.origin.copy( origin );
  3147. this.direction.copy( direction );
  3148. return this;
  3149. }
  3150. copy( ray ) {
  3151. this.origin.copy( ray.origin );
  3152. this.direction.copy( ray.direction );
  3153. return this;
  3154. }
  3155. at( t, target ) {
  3156. return target.copy( this.origin ).addScaledVector( this.direction, t );
  3157. }
  3158. lookAt( v ) {
  3159. this.direction.copy( v ).sub( this.origin ).normalize();
  3160. return this;
  3161. }
  3162. recast( t ) {
  3163. this.origin.copy( this.at( t, _vector$a ) );
  3164. return this;
  3165. }
  3166. closestPointToPoint( point, target ) {
  3167. target.subVectors( point, this.origin );
  3168. const directionDistance = target.dot( this.direction );
  3169. if ( directionDistance < 0 ) {
  3170. return target.copy( this.origin );
  3171. }
  3172. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3173. }
  3174. distanceToPoint( point ) {
  3175. return Math.sqrt( this.distanceSqToPoint( point ) );
  3176. }
  3177. distanceSqToPoint( point ) {
  3178. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3179. // point behind the ray
  3180. if ( directionDistance < 0 ) {
  3181. return this.origin.distanceToSquared( point );
  3182. }
  3183. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  3184. return _vector$a.distanceToSquared( point );
  3185. }
  3186. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3187. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3188. // It returns the min distance between the ray and the segment
  3189. // defined by v0 and v1
  3190. // It can also set two optional targets :
  3191. // - The closest point on the ray
  3192. // - The closest point on the segment
  3193. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3194. _segDir.copy( v1 ).sub( v0 ).normalize();
  3195. _diff.copy( this.origin ).sub( _segCenter );
  3196. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3197. const a01 = - this.direction.dot( _segDir );
  3198. const b0 = _diff.dot( this.direction );
  3199. const b1 = - _diff.dot( _segDir );
  3200. const c = _diff.lengthSq();
  3201. const det = Math.abs( 1 - a01 * a01 );
  3202. let s0, s1, sqrDist, extDet;
  3203. if ( det > 0 ) {
  3204. // The ray and segment are not parallel.
  3205. s0 = a01 * b1 - b0;
  3206. s1 = a01 * b0 - b1;
  3207. extDet = segExtent * det;
  3208. if ( s0 >= 0 ) {
  3209. if ( s1 >= - extDet ) {
  3210. if ( s1 <= extDet ) {
  3211. // region 0
  3212. // Minimum at interior points of ray and segment.
  3213. const invDet = 1 / det;
  3214. s0 *= invDet;
  3215. s1 *= invDet;
  3216. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3217. } else {
  3218. // region 1
  3219. s1 = segExtent;
  3220. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3221. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3222. }
  3223. } else {
  3224. // region 5
  3225. s1 = - segExtent;
  3226. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3227. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3228. }
  3229. } else {
  3230. if ( s1 <= - extDet ) {
  3231. // region 4
  3232. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3233. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3234. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3235. } else if ( s1 <= extDet ) {
  3236. // region 3
  3237. s0 = 0;
  3238. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3239. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3240. } else {
  3241. // region 2
  3242. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3243. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3244. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3245. }
  3246. }
  3247. } else {
  3248. // Ray and segment are parallel.
  3249. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3250. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3251. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3252. }
  3253. if ( optionalPointOnRay ) {
  3254. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  3255. }
  3256. if ( optionalPointOnSegment ) {
  3257. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  3258. }
  3259. return sqrDist;
  3260. }
  3261. intersectSphere( sphere, target ) {
  3262. _vector$a.subVectors( sphere.center, this.origin );
  3263. const tca = _vector$a.dot( this.direction );
  3264. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3265. const radius2 = sphere.radius * sphere.radius;
  3266. if ( d2 > radius2 ) return null;
  3267. const thc = Math.sqrt( radius2 - d2 );
  3268. // t0 = first intersect point - entrance on front of sphere
  3269. const t0 = tca - thc;
  3270. // t1 = second intersect point - exit point on back of sphere
  3271. const t1 = tca + thc;
  3272. // test to see if t1 is behind the ray - if so, return null
  3273. if ( t1 < 0 ) return null;
  3274. // test to see if t0 is behind the ray:
  3275. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3276. // in order to always return an intersect point that is in front of the ray.
  3277. if ( t0 < 0 ) return this.at( t1, target );
  3278. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3279. return this.at( t0, target );
  3280. }
  3281. intersectsSphere( sphere ) {
  3282. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3283. }
  3284. distanceToPlane( plane ) {
  3285. const denominator = plane.normal.dot( this.direction );
  3286. if ( denominator === 0 ) {
  3287. // line is coplanar, return origin
  3288. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3289. return 0;
  3290. }
  3291. // Null is preferable to undefined since undefined means.... it is undefined
  3292. return null;
  3293. }
  3294. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3295. // Return if the ray never intersects the plane
  3296. return t >= 0 ? t : null;
  3297. }
  3298. intersectPlane( plane, target ) {
  3299. const t = this.distanceToPlane( plane );
  3300. if ( t === null ) {
  3301. return null;
  3302. }
  3303. return this.at( t, target );
  3304. }
  3305. intersectsPlane( plane ) {
  3306. // check if the ray lies on the plane first
  3307. const distToPoint = plane.distanceToPoint( this.origin );
  3308. if ( distToPoint === 0 ) {
  3309. return true;
  3310. }
  3311. const denominator = plane.normal.dot( this.direction );
  3312. if ( denominator * distToPoint < 0 ) {
  3313. return true;
  3314. }
  3315. // ray origin is behind the plane (and is pointing behind it)
  3316. return false;
  3317. }
  3318. intersectBox( box, target ) {
  3319. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3320. const invdirx = 1 / this.direction.x,
  3321. invdiry = 1 / this.direction.y,
  3322. invdirz = 1 / this.direction.z;
  3323. const origin = this.origin;
  3324. if ( invdirx >= 0 ) {
  3325. tmin = ( box.min.x - origin.x ) * invdirx;
  3326. tmax = ( box.max.x - origin.x ) * invdirx;
  3327. } else {
  3328. tmin = ( box.max.x - origin.x ) * invdirx;
  3329. tmax = ( box.min.x - origin.x ) * invdirx;
  3330. }
  3331. if ( invdiry >= 0 ) {
  3332. tymin = ( box.min.y - origin.y ) * invdiry;
  3333. tymax = ( box.max.y - origin.y ) * invdiry;
  3334. } else {
  3335. tymin = ( box.max.y - origin.y ) * invdiry;
  3336. tymax = ( box.min.y - origin.y ) * invdiry;
  3337. }
  3338. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3339. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  3340. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  3341. if ( invdirz >= 0 ) {
  3342. tzmin = ( box.min.z - origin.z ) * invdirz;
  3343. tzmax = ( box.max.z - origin.z ) * invdirz;
  3344. } else {
  3345. tzmin = ( box.max.z - origin.z ) * invdirz;
  3346. tzmax = ( box.min.z - origin.z ) * invdirz;
  3347. }
  3348. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3349. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3350. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3351. //return point closest to the ray (positive side)
  3352. if ( tmax < 0 ) return null;
  3353. return this.at( tmin >= 0 ? tmin : tmax, target );
  3354. }
  3355. intersectsBox( box ) {
  3356. return this.intersectBox( box, _vector$a ) !== null;
  3357. }
  3358. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3359. // Compute the offset origin, edges, and normal.
  3360. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3361. _edge1.subVectors( b, a );
  3362. _edge2.subVectors( c, a );
  3363. _normal$1.crossVectors( _edge1, _edge2 );
  3364. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3365. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3366. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3367. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3368. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3369. let DdN = this.direction.dot( _normal$1 );
  3370. let sign;
  3371. if ( DdN > 0 ) {
  3372. if ( backfaceCulling ) return null;
  3373. sign = 1;
  3374. } else if ( DdN < 0 ) {
  3375. sign = - 1;
  3376. DdN = - DdN;
  3377. } else {
  3378. return null;
  3379. }
  3380. _diff.subVectors( this.origin, a );
  3381. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3382. // b1 < 0, no intersection
  3383. if ( DdQxE2 < 0 ) {
  3384. return null;
  3385. }
  3386. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3387. // b2 < 0, no intersection
  3388. if ( DdE1xQ < 0 ) {
  3389. return null;
  3390. }
  3391. // b1+b2 > 1, no intersection
  3392. if ( DdQxE2 + DdE1xQ > DdN ) {
  3393. return null;
  3394. }
  3395. // Line intersects triangle, check if ray does.
  3396. const QdN = - sign * _diff.dot( _normal$1 );
  3397. // t < 0, no intersection
  3398. if ( QdN < 0 ) {
  3399. return null;
  3400. }
  3401. // Ray intersects triangle.
  3402. return this.at( QdN / DdN, target );
  3403. }
  3404. applyMatrix4( matrix4 ) {
  3405. this.origin.applyMatrix4( matrix4 );
  3406. this.direction.transformDirection( matrix4 );
  3407. return this;
  3408. }
  3409. equals( ray ) {
  3410. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3411. }
  3412. clone() {
  3413. return new this.constructor().copy( this );
  3414. }
  3415. }
  3416. class Matrix4 {
  3417. constructor() {
  3418. Matrix4.prototype.isMatrix4 = true;
  3419. this.elements = [
  3420. 1, 0, 0, 0,
  3421. 0, 1, 0, 0,
  3422. 0, 0, 1, 0,
  3423. 0, 0, 0, 1
  3424. ];
  3425. }
  3426. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3427. const te = this.elements;
  3428. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3429. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3430. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3431. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3432. return this;
  3433. }
  3434. identity() {
  3435. this.set(
  3436. 1, 0, 0, 0,
  3437. 0, 1, 0, 0,
  3438. 0, 0, 1, 0,
  3439. 0, 0, 0, 1
  3440. );
  3441. return this;
  3442. }
  3443. clone() {
  3444. return new Matrix4().fromArray( this.elements );
  3445. }
  3446. copy( m ) {
  3447. const te = this.elements;
  3448. const me = m.elements;
  3449. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3450. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3451. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3452. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3453. return this;
  3454. }
  3455. copyPosition( m ) {
  3456. const te = this.elements, me = m.elements;
  3457. te[ 12 ] = me[ 12 ];
  3458. te[ 13 ] = me[ 13 ];
  3459. te[ 14 ] = me[ 14 ];
  3460. return this;
  3461. }
  3462. setFromMatrix3( m ) {
  3463. const me = m.elements;
  3464. this.set(
  3465. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3466. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3467. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3468. 0, 0, 0, 1
  3469. );
  3470. return this;
  3471. }
  3472. extractBasis( xAxis, yAxis, zAxis ) {
  3473. xAxis.setFromMatrixColumn( this, 0 );
  3474. yAxis.setFromMatrixColumn( this, 1 );
  3475. zAxis.setFromMatrixColumn( this, 2 );
  3476. return this;
  3477. }
  3478. makeBasis( xAxis, yAxis, zAxis ) {
  3479. this.set(
  3480. xAxis.x, yAxis.x, zAxis.x, 0,
  3481. xAxis.y, yAxis.y, zAxis.y, 0,
  3482. xAxis.z, yAxis.z, zAxis.z, 0,
  3483. 0, 0, 0, 1
  3484. );
  3485. return this;
  3486. }
  3487. extractRotation( m ) {
  3488. // this method does not support reflection matrices
  3489. const te = this.elements;
  3490. const me = m.elements;
  3491. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3492. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3493. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3494. te[ 0 ] = me[ 0 ] * scaleX;
  3495. te[ 1 ] = me[ 1 ] * scaleX;
  3496. te[ 2 ] = me[ 2 ] * scaleX;
  3497. te[ 3 ] = 0;
  3498. te[ 4 ] = me[ 4 ] * scaleY;
  3499. te[ 5 ] = me[ 5 ] * scaleY;
  3500. te[ 6 ] = me[ 6 ] * scaleY;
  3501. te[ 7 ] = 0;
  3502. te[ 8 ] = me[ 8 ] * scaleZ;
  3503. te[ 9 ] = me[ 9 ] * scaleZ;
  3504. te[ 10 ] = me[ 10 ] * scaleZ;
  3505. te[ 11 ] = 0;
  3506. te[ 12 ] = 0;
  3507. te[ 13 ] = 0;
  3508. te[ 14 ] = 0;
  3509. te[ 15 ] = 1;
  3510. return this;
  3511. }
  3512. makeRotationFromEuler( euler ) {
  3513. const te = this.elements;
  3514. const x = euler.x, y = euler.y, z = euler.z;
  3515. const a = Math.cos( x ), b = Math.sin( x );
  3516. const c = Math.cos( y ), d = Math.sin( y );
  3517. const e = Math.cos( z ), f = Math.sin( z );
  3518. if ( euler.order === 'XYZ' ) {
  3519. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3520. te[ 0 ] = c * e;
  3521. te[ 4 ] = - c * f;
  3522. te[ 8 ] = d;
  3523. te[ 1 ] = af + be * d;
  3524. te[ 5 ] = ae - bf * d;
  3525. te[ 9 ] = - b * c;
  3526. te[ 2 ] = bf - ae * d;
  3527. te[ 6 ] = be + af * d;
  3528. te[ 10 ] = a * c;
  3529. } else if ( euler.order === 'YXZ' ) {
  3530. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3531. te[ 0 ] = ce + df * b;
  3532. te[ 4 ] = de * b - cf;
  3533. te[ 8 ] = a * d;
  3534. te[ 1 ] = a * f;
  3535. te[ 5 ] = a * e;
  3536. te[ 9 ] = - b;
  3537. te[ 2 ] = cf * b - de;
  3538. te[ 6 ] = df + ce * b;
  3539. te[ 10 ] = a * c;
  3540. } else if ( euler.order === 'ZXY' ) {
  3541. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3542. te[ 0 ] = ce - df * b;
  3543. te[ 4 ] = - a * f;
  3544. te[ 8 ] = de + cf * b;
  3545. te[ 1 ] = cf + de * b;
  3546. te[ 5 ] = a * e;
  3547. te[ 9 ] = df - ce * b;
  3548. te[ 2 ] = - a * d;
  3549. te[ 6 ] = b;
  3550. te[ 10 ] = a * c;
  3551. } else if ( euler.order === 'ZYX' ) {
  3552. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3553. te[ 0 ] = c * e;
  3554. te[ 4 ] = be * d - af;
  3555. te[ 8 ] = ae * d + bf;
  3556. te[ 1 ] = c * f;
  3557. te[ 5 ] = bf * d + ae;
  3558. te[ 9 ] = af * d - be;
  3559. te[ 2 ] = - d;
  3560. te[ 6 ] = b * c;
  3561. te[ 10 ] = a * c;
  3562. } else if ( euler.order === 'YZX' ) {
  3563. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3564. te[ 0 ] = c * e;
  3565. te[ 4 ] = bd - ac * f;
  3566. te[ 8 ] = bc * f + ad;
  3567. te[ 1 ] = f;
  3568. te[ 5 ] = a * e;
  3569. te[ 9 ] = - b * e;
  3570. te[ 2 ] = - d * e;
  3571. te[ 6 ] = ad * f + bc;
  3572. te[ 10 ] = ac - bd * f;
  3573. } else if ( euler.order === 'XZY' ) {
  3574. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3575. te[ 0 ] = c * e;
  3576. te[ 4 ] = - f;
  3577. te[ 8 ] = d * e;
  3578. te[ 1 ] = ac * f + bd;
  3579. te[ 5 ] = a * e;
  3580. te[ 9 ] = ad * f - bc;
  3581. te[ 2 ] = bc * f - ad;
  3582. te[ 6 ] = b * e;
  3583. te[ 10 ] = bd * f + ac;
  3584. }
  3585. // bottom row
  3586. te[ 3 ] = 0;
  3587. te[ 7 ] = 0;
  3588. te[ 11 ] = 0;
  3589. // last column
  3590. te[ 12 ] = 0;
  3591. te[ 13 ] = 0;
  3592. te[ 14 ] = 0;
  3593. te[ 15 ] = 1;
  3594. return this;
  3595. }
  3596. makeRotationFromQuaternion( q ) {
  3597. return this.compose( _zero, q, _one );
  3598. }
  3599. lookAt( eye, target, up ) {
  3600. const te = this.elements;
  3601. _z.subVectors( eye, target );
  3602. if ( _z.lengthSq() === 0 ) {
  3603. // eye and target are in the same position
  3604. _z.z = 1;
  3605. }
  3606. _z.normalize();
  3607. _x.crossVectors( up, _z );
  3608. if ( _x.lengthSq() === 0 ) {
  3609. // up and z are parallel
  3610. if ( Math.abs( up.z ) === 1 ) {
  3611. _z.x += 0.0001;
  3612. } else {
  3613. _z.z += 0.0001;
  3614. }
  3615. _z.normalize();
  3616. _x.crossVectors( up, _z );
  3617. }
  3618. _x.normalize();
  3619. _y.crossVectors( _z, _x );
  3620. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3621. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3622. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3623. return this;
  3624. }
  3625. multiply( m ) {
  3626. return this.multiplyMatrices( this, m );
  3627. }
  3628. premultiply( m ) {
  3629. return this.multiplyMatrices( m, this );
  3630. }
  3631. multiplyMatrices( a, b ) {
  3632. const ae = a.elements;
  3633. const be = b.elements;
  3634. const te = this.elements;
  3635. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3636. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3637. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3638. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3639. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3640. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3641. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3642. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3643. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3644. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3645. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3646. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3647. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3648. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3649. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3650. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3651. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3652. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3653. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3654. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3655. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3656. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3657. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3658. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3659. return this;
  3660. }
  3661. multiplyScalar( s ) {
  3662. const te = this.elements;
  3663. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3664. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3665. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3666. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3667. return this;
  3668. }
  3669. determinant() {
  3670. const te = this.elements;
  3671. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3672. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3673. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3674. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3675. //TODO: make this more efficient
  3676. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3677. return (
  3678. n41 * (
  3679. + n14 * n23 * n32
  3680. - n13 * n24 * n32
  3681. - n14 * n22 * n33
  3682. + n12 * n24 * n33
  3683. + n13 * n22 * n34
  3684. - n12 * n23 * n34
  3685. ) +
  3686. n42 * (
  3687. + n11 * n23 * n34
  3688. - n11 * n24 * n33
  3689. + n14 * n21 * n33
  3690. - n13 * n21 * n34
  3691. + n13 * n24 * n31
  3692. - n14 * n23 * n31
  3693. ) +
  3694. n43 * (
  3695. + n11 * n24 * n32
  3696. - n11 * n22 * n34
  3697. - n14 * n21 * n32
  3698. + n12 * n21 * n34
  3699. + n14 * n22 * n31
  3700. - n12 * n24 * n31
  3701. ) +
  3702. n44 * (
  3703. - n13 * n22 * n31
  3704. - n11 * n23 * n32
  3705. + n11 * n22 * n33
  3706. + n13 * n21 * n32
  3707. - n12 * n21 * n33
  3708. + n12 * n23 * n31
  3709. )
  3710. );
  3711. }
  3712. transpose() {
  3713. const te = this.elements;
  3714. let tmp;
  3715. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3716. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3717. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3718. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3719. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3720. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3721. return this;
  3722. }
  3723. setPosition( x, y, z ) {
  3724. const te = this.elements;
  3725. if ( x.isVector3 ) {
  3726. te[ 12 ] = x.x;
  3727. te[ 13 ] = x.y;
  3728. te[ 14 ] = x.z;
  3729. } else {
  3730. te[ 12 ] = x;
  3731. te[ 13 ] = y;
  3732. te[ 14 ] = z;
  3733. }
  3734. return this;
  3735. }
  3736. invert() {
  3737. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3738. const te = this.elements,
  3739. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  3740. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  3741. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  3742. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  3743. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3744. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3745. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3746. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3747. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3748. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  3749. const detInv = 1 / det;
  3750. te[ 0 ] = t11 * detInv;
  3751. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  3752. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  3753. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  3754. te[ 4 ] = t12 * detInv;
  3755. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  3756. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  3757. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  3758. te[ 8 ] = t13 * detInv;
  3759. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  3760. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  3761. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  3762. te[ 12 ] = t14 * detInv;
  3763. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  3764. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  3765. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  3766. return this;
  3767. }
  3768. scale( v ) {
  3769. const te = this.elements;
  3770. const x = v.x, y = v.y, z = v.z;
  3771. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3772. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3773. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3774. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3775. return this;
  3776. }
  3777. getMaxScaleOnAxis() {
  3778. const te = this.elements;
  3779. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3780. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3781. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3782. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3783. }
  3784. makeTranslation( x, y, z ) {
  3785. this.set(
  3786. 1, 0, 0, x,
  3787. 0, 1, 0, y,
  3788. 0, 0, 1, z,
  3789. 0, 0, 0, 1
  3790. );
  3791. return this;
  3792. }
  3793. makeRotationX( theta ) {
  3794. const c = Math.cos( theta ), s = Math.sin( theta );
  3795. this.set(
  3796. 1, 0, 0, 0,
  3797. 0, c, - s, 0,
  3798. 0, s, c, 0,
  3799. 0, 0, 0, 1
  3800. );
  3801. return this;
  3802. }
  3803. makeRotationY( theta ) {
  3804. const c = Math.cos( theta ), s = Math.sin( theta );
  3805. this.set(
  3806. c, 0, s, 0,
  3807. 0, 1, 0, 0,
  3808. - s, 0, c, 0,
  3809. 0, 0, 0, 1
  3810. );
  3811. return this;
  3812. }
  3813. makeRotationZ( theta ) {
  3814. const c = Math.cos( theta ), s = Math.sin( theta );
  3815. this.set(
  3816. c, - s, 0, 0,
  3817. s, c, 0, 0,
  3818. 0, 0, 1, 0,
  3819. 0, 0, 0, 1
  3820. );
  3821. return this;
  3822. }
  3823. makeRotationAxis( axis, angle ) {
  3824. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3825. const c = Math.cos( angle );
  3826. const s = Math.sin( angle );
  3827. const t = 1 - c;
  3828. const x = axis.x, y = axis.y, z = axis.z;
  3829. const tx = t * x, ty = t * y;
  3830. this.set(
  3831. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3832. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3833. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3834. 0, 0, 0, 1
  3835. );
  3836. return this;
  3837. }
  3838. makeScale( x, y, z ) {
  3839. this.set(
  3840. x, 0, 0, 0,
  3841. 0, y, 0, 0,
  3842. 0, 0, z, 0,
  3843. 0, 0, 0, 1
  3844. );
  3845. return this;
  3846. }
  3847. makeShear( xy, xz, yx, yz, zx, zy ) {
  3848. this.set(
  3849. 1, yx, zx, 0,
  3850. xy, 1, zy, 0,
  3851. xz, yz, 1, 0,
  3852. 0, 0, 0, 1
  3853. );
  3854. return this;
  3855. }
  3856. compose( position, quaternion, scale ) {
  3857. const te = this.elements;
  3858. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  3859. const x2 = x + x, y2 = y + y, z2 = z + z;
  3860. const xx = x * x2, xy = x * y2, xz = x * z2;
  3861. const yy = y * y2, yz = y * z2, zz = z * z2;
  3862. const wx = w * x2, wy = w * y2, wz = w * z2;
  3863. const sx = scale.x, sy = scale.y, sz = scale.z;
  3864. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  3865. te[ 1 ] = ( xy + wz ) * sx;
  3866. te[ 2 ] = ( xz - wy ) * sx;
  3867. te[ 3 ] = 0;
  3868. te[ 4 ] = ( xy - wz ) * sy;
  3869. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  3870. te[ 6 ] = ( yz + wx ) * sy;
  3871. te[ 7 ] = 0;
  3872. te[ 8 ] = ( xz + wy ) * sz;
  3873. te[ 9 ] = ( yz - wx ) * sz;
  3874. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  3875. te[ 11 ] = 0;
  3876. te[ 12 ] = position.x;
  3877. te[ 13 ] = position.y;
  3878. te[ 14 ] = position.z;
  3879. te[ 15 ] = 1;
  3880. return this;
  3881. }
  3882. decompose( position, quaternion, scale ) {
  3883. const te = this.elements;
  3884. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3885. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3886. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3887. // if determine is negative, we need to invert one scale
  3888. const det = this.determinant();
  3889. if ( det < 0 ) sx = - sx;
  3890. position.x = te[ 12 ];
  3891. position.y = te[ 13 ];
  3892. position.z = te[ 14 ];
  3893. // scale the rotation part
  3894. _m1$2.copy( this );
  3895. const invSX = 1 / sx;
  3896. const invSY = 1 / sy;
  3897. const invSZ = 1 / sz;
  3898. _m1$2.elements[ 0 ] *= invSX;
  3899. _m1$2.elements[ 1 ] *= invSX;
  3900. _m1$2.elements[ 2 ] *= invSX;
  3901. _m1$2.elements[ 4 ] *= invSY;
  3902. _m1$2.elements[ 5 ] *= invSY;
  3903. _m1$2.elements[ 6 ] *= invSY;
  3904. _m1$2.elements[ 8 ] *= invSZ;
  3905. _m1$2.elements[ 9 ] *= invSZ;
  3906. _m1$2.elements[ 10 ] *= invSZ;
  3907. quaternion.setFromRotationMatrix( _m1$2 );
  3908. scale.x = sx;
  3909. scale.y = sy;
  3910. scale.z = sz;
  3911. return this;
  3912. }
  3913. makePerspective( left, right, top, bottom, near, far ) {
  3914. const te = this.elements;
  3915. const x = 2 * near / ( right - left );
  3916. const y = 2 * near / ( top - bottom );
  3917. const a = ( right + left ) / ( right - left );
  3918. const b = ( top + bottom ) / ( top - bottom );
  3919. const c = - ( far + near ) / ( far - near );
  3920. const d = - 2 * far * near / ( far - near );
  3921. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3922. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3923. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3924. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3925. return this;
  3926. }
  3927. makeOrthographic( left, right, top, bottom, near, far ) {
  3928. const te = this.elements;
  3929. const w = 1.0 / ( right - left );
  3930. const h = 1.0 / ( top - bottom );
  3931. const p = 1.0 / ( far - near );
  3932. const x = ( right + left ) * w;
  3933. const y = ( top + bottom ) * h;
  3934. const z = ( far + near ) * p;
  3935. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  3936. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  3937. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  3938. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  3939. return this;
  3940. }
  3941. equals( matrix ) {
  3942. const te = this.elements;
  3943. const me = matrix.elements;
  3944. for ( let i = 0; i < 16; i ++ ) {
  3945. if ( te[ i ] !== me[ i ] ) return false;
  3946. }
  3947. return true;
  3948. }
  3949. fromArray( array, offset = 0 ) {
  3950. for ( let i = 0; i < 16; i ++ ) {
  3951. this.elements[ i ] = array[ i + offset ];
  3952. }
  3953. return this;
  3954. }
  3955. toArray( array = [], offset = 0 ) {
  3956. const te = this.elements;
  3957. array[ offset ] = te[ 0 ];
  3958. array[ offset + 1 ] = te[ 1 ];
  3959. array[ offset + 2 ] = te[ 2 ];
  3960. array[ offset + 3 ] = te[ 3 ];
  3961. array[ offset + 4 ] = te[ 4 ];
  3962. array[ offset + 5 ] = te[ 5 ];
  3963. array[ offset + 6 ] = te[ 6 ];
  3964. array[ offset + 7 ] = te[ 7 ];
  3965. array[ offset + 8 ] = te[ 8 ];
  3966. array[ offset + 9 ] = te[ 9 ];
  3967. array[ offset + 10 ] = te[ 10 ];
  3968. array[ offset + 11 ] = te[ 11 ];
  3969. array[ offset + 12 ] = te[ 12 ];
  3970. array[ offset + 13 ] = te[ 13 ];
  3971. array[ offset + 14 ] = te[ 14 ];
  3972. array[ offset + 15 ] = te[ 15 ];
  3973. return array;
  3974. }
  3975. }
  3976. const _v1$5 = /*@__PURE__*/ new Vector3();
  3977. const _m1$2 = /*@__PURE__*/ new Matrix4();
  3978. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  3979. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  3980. const _x = /*@__PURE__*/ new Vector3();
  3981. const _y = /*@__PURE__*/ new Vector3();
  3982. const _z = /*@__PURE__*/ new Vector3();
  3983. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  3984. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  3985. class Euler {
  3986. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  3987. this.isEuler = true;
  3988. this._x = x;
  3989. this._y = y;
  3990. this._z = z;
  3991. this._order = order;
  3992. }
  3993. get x() {
  3994. return this._x;
  3995. }
  3996. set x( value ) {
  3997. this._x = value;
  3998. this._onChangeCallback();
  3999. }
  4000. get y() {
  4001. return this._y;
  4002. }
  4003. set y( value ) {
  4004. this._y = value;
  4005. this._onChangeCallback();
  4006. }
  4007. get z() {
  4008. return this._z;
  4009. }
  4010. set z( value ) {
  4011. this._z = value;
  4012. this._onChangeCallback();
  4013. }
  4014. get order() {
  4015. return this._order;
  4016. }
  4017. set order( value ) {
  4018. this._order = value;
  4019. this._onChangeCallback();
  4020. }
  4021. set( x, y, z, order = this._order ) {
  4022. this._x = x;
  4023. this._y = y;
  4024. this._z = z;
  4025. this._order = order;
  4026. this._onChangeCallback();
  4027. return this;
  4028. }
  4029. clone() {
  4030. return new this.constructor( this._x, this._y, this._z, this._order );
  4031. }
  4032. copy( euler ) {
  4033. this._x = euler._x;
  4034. this._y = euler._y;
  4035. this._z = euler._z;
  4036. this._order = euler._order;
  4037. this._onChangeCallback();
  4038. return this;
  4039. }
  4040. setFromRotationMatrix( m, order = this._order, update = true ) {
  4041. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4042. const te = m.elements;
  4043. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4044. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4045. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4046. switch ( order ) {
  4047. case 'XYZ':
  4048. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4049. if ( Math.abs( m13 ) < 0.9999999 ) {
  4050. this._x = Math.atan2( - m23, m33 );
  4051. this._z = Math.atan2( - m12, m11 );
  4052. } else {
  4053. this._x = Math.atan2( m32, m22 );
  4054. this._z = 0;
  4055. }
  4056. break;
  4057. case 'YXZ':
  4058. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4059. if ( Math.abs( m23 ) < 0.9999999 ) {
  4060. this._y = Math.atan2( m13, m33 );
  4061. this._z = Math.atan2( m21, m22 );
  4062. } else {
  4063. this._y = Math.atan2( - m31, m11 );
  4064. this._z = 0;
  4065. }
  4066. break;
  4067. case 'ZXY':
  4068. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4069. if ( Math.abs( m32 ) < 0.9999999 ) {
  4070. this._y = Math.atan2( - m31, m33 );
  4071. this._z = Math.atan2( - m12, m22 );
  4072. } else {
  4073. this._y = 0;
  4074. this._z = Math.atan2( m21, m11 );
  4075. }
  4076. break;
  4077. case 'ZYX':
  4078. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4079. if ( Math.abs( m31 ) < 0.9999999 ) {
  4080. this._x = Math.atan2( m32, m33 );
  4081. this._z = Math.atan2( m21, m11 );
  4082. } else {
  4083. this._x = 0;
  4084. this._z = Math.atan2( - m12, m22 );
  4085. }
  4086. break;
  4087. case 'YZX':
  4088. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4089. if ( Math.abs( m21 ) < 0.9999999 ) {
  4090. this._x = Math.atan2( - m23, m22 );
  4091. this._y = Math.atan2( - m31, m11 );
  4092. } else {
  4093. this._x = 0;
  4094. this._y = Math.atan2( m13, m33 );
  4095. }
  4096. break;
  4097. case 'XZY':
  4098. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  4099. if ( Math.abs( m12 ) < 0.9999999 ) {
  4100. this._x = Math.atan2( m32, m22 );
  4101. this._y = Math.atan2( m13, m11 );
  4102. } else {
  4103. this._x = Math.atan2( - m23, m33 );
  4104. this._y = 0;
  4105. }
  4106. break;
  4107. default:
  4108. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4109. }
  4110. this._order = order;
  4111. if ( update === true ) this._onChangeCallback();
  4112. return this;
  4113. }
  4114. setFromQuaternion( q, order, update ) {
  4115. _matrix$1.makeRotationFromQuaternion( q );
  4116. return this.setFromRotationMatrix( _matrix$1, order, update );
  4117. }
  4118. setFromVector3( v, order = this._order ) {
  4119. return this.set( v.x, v.y, v.z, order );
  4120. }
  4121. reorder( newOrder ) {
  4122. // WARNING: this discards revolution information -bhouston
  4123. _quaternion$3.setFromEuler( this );
  4124. return this.setFromQuaternion( _quaternion$3, newOrder );
  4125. }
  4126. equals( euler ) {
  4127. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4128. }
  4129. fromArray( array ) {
  4130. this._x = array[ 0 ];
  4131. this._y = array[ 1 ];
  4132. this._z = array[ 2 ];
  4133. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4134. this._onChangeCallback();
  4135. return this;
  4136. }
  4137. toArray( array = [], offset = 0 ) {
  4138. array[ offset ] = this._x;
  4139. array[ offset + 1 ] = this._y;
  4140. array[ offset + 2 ] = this._z;
  4141. array[ offset + 3 ] = this._order;
  4142. return array;
  4143. }
  4144. _onChange( callback ) {
  4145. this._onChangeCallback = callback;
  4146. return this;
  4147. }
  4148. _onChangeCallback() {}
  4149. *[ Symbol.iterator ]() {
  4150. yield this._x;
  4151. yield this._y;
  4152. yield this._z;
  4153. yield this._order;
  4154. }
  4155. }
  4156. Euler.DEFAULT_ORDER = 'XYZ';
  4157. class Layers {
  4158. constructor() {
  4159. this.mask = 1 | 0;
  4160. }
  4161. set( channel ) {
  4162. this.mask = ( 1 << channel | 0 ) >>> 0;
  4163. }
  4164. enable( channel ) {
  4165. this.mask |= 1 << channel | 0;
  4166. }
  4167. enableAll() {
  4168. this.mask = 0xffffffff | 0;
  4169. }
  4170. toggle( channel ) {
  4171. this.mask ^= 1 << channel | 0;
  4172. }
  4173. disable( channel ) {
  4174. this.mask &= ~ ( 1 << channel | 0 );
  4175. }
  4176. disableAll() {
  4177. this.mask = 0;
  4178. }
  4179. test( layers ) {
  4180. return ( this.mask & layers.mask ) !== 0;
  4181. }
  4182. isEnabled( channel ) {
  4183. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4184. }
  4185. }
  4186. let _object3DId = 0;
  4187. const _v1$4 = /*@__PURE__*/ new Vector3();
  4188. const _q1 = /*@__PURE__*/ new Quaternion();
  4189. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4190. const _target = /*@__PURE__*/ new Vector3();
  4191. const _position$3 = /*@__PURE__*/ new Vector3();
  4192. const _scale$2 = /*@__PURE__*/ new Vector3();
  4193. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4194. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4195. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4196. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4197. const _addedEvent = { type: 'added' };
  4198. const _removedEvent = { type: 'removed' };
  4199. class Object3D extends EventDispatcher {
  4200. constructor() {
  4201. super();
  4202. this.isObject3D = true;
  4203. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4204. this.uuid = generateUUID();
  4205. this.name = '';
  4206. this.type = 'Object3D';
  4207. this.parent = null;
  4208. this.children = [];
  4209. this.up = Object3D.DEFAULT_UP.clone();
  4210. const position = new Vector3();
  4211. const rotation = new Euler();
  4212. const quaternion = new Quaternion();
  4213. const scale = new Vector3( 1, 1, 1 );
  4214. function onRotationChange() {
  4215. quaternion.setFromEuler( rotation, false );
  4216. }
  4217. function onQuaternionChange() {
  4218. rotation.setFromQuaternion( quaternion, undefined, false );
  4219. }
  4220. rotation._onChange( onRotationChange );
  4221. quaternion._onChange( onQuaternionChange );
  4222. Object.defineProperties( this, {
  4223. position: {
  4224. configurable: true,
  4225. enumerable: true,
  4226. value: position
  4227. },
  4228. rotation: {
  4229. configurable: true,
  4230. enumerable: true,
  4231. value: rotation
  4232. },
  4233. quaternion: {
  4234. configurable: true,
  4235. enumerable: true,
  4236. value: quaternion
  4237. },
  4238. scale: {
  4239. configurable: true,
  4240. enumerable: true,
  4241. value: scale
  4242. },
  4243. modelViewMatrix: {
  4244. value: new Matrix4()
  4245. },
  4246. normalMatrix: {
  4247. value: new Matrix3()
  4248. }
  4249. } );
  4250. this.matrix = new Matrix4();
  4251. this.matrixWorld = new Matrix4();
  4252. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  4253. this.matrixWorldNeedsUpdate = false;
  4254. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  4255. this.layers = new Layers();
  4256. this.visible = true;
  4257. this.castShadow = false;
  4258. this.receiveShadow = false;
  4259. this.frustumCulled = true;
  4260. this.renderOrder = 0;
  4261. this.animations = [];
  4262. this.userData = {};
  4263. }
  4264. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4265. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4266. applyMatrix4( matrix ) {
  4267. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4268. this.matrix.premultiply( matrix );
  4269. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4270. }
  4271. applyQuaternion( q ) {
  4272. this.quaternion.premultiply( q );
  4273. return this;
  4274. }
  4275. setRotationFromAxisAngle( axis, angle ) {
  4276. // assumes axis is normalized
  4277. this.quaternion.setFromAxisAngle( axis, angle );
  4278. }
  4279. setRotationFromEuler( euler ) {
  4280. this.quaternion.setFromEuler( euler, true );
  4281. }
  4282. setRotationFromMatrix( m ) {
  4283. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4284. this.quaternion.setFromRotationMatrix( m );
  4285. }
  4286. setRotationFromQuaternion( q ) {
  4287. // assumes q is normalized
  4288. this.quaternion.copy( q );
  4289. }
  4290. rotateOnAxis( axis, angle ) {
  4291. // rotate object on axis in object space
  4292. // axis is assumed to be normalized
  4293. _q1.setFromAxisAngle( axis, angle );
  4294. this.quaternion.multiply( _q1 );
  4295. return this;
  4296. }
  4297. rotateOnWorldAxis( axis, angle ) {
  4298. // rotate object on axis in world space
  4299. // axis is assumed to be normalized
  4300. // method assumes no rotated parent
  4301. _q1.setFromAxisAngle( axis, angle );
  4302. this.quaternion.premultiply( _q1 );
  4303. return this;
  4304. }
  4305. rotateX( angle ) {
  4306. return this.rotateOnAxis( _xAxis, angle );
  4307. }
  4308. rotateY( angle ) {
  4309. return this.rotateOnAxis( _yAxis, angle );
  4310. }
  4311. rotateZ( angle ) {
  4312. return this.rotateOnAxis( _zAxis, angle );
  4313. }
  4314. translateOnAxis( axis, distance ) {
  4315. // translate object by distance along axis in object space
  4316. // axis is assumed to be normalized
  4317. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4318. this.position.add( _v1$4.multiplyScalar( distance ) );
  4319. return this;
  4320. }
  4321. translateX( distance ) {
  4322. return this.translateOnAxis( _xAxis, distance );
  4323. }
  4324. translateY( distance ) {
  4325. return this.translateOnAxis( _yAxis, distance );
  4326. }
  4327. translateZ( distance ) {
  4328. return this.translateOnAxis( _zAxis, distance );
  4329. }
  4330. localToWorld( vector ) {
  4331. this.updateWorldMatrix( true, false );
  4332. return vector.applyMatrix4( this.matrixWorld );
  4333. }
  4334. worldToLocal( vector ) {
  4335. this.updateWorldMatrix( true, false );
  4336. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4337. }
  4338. lookAt( x, y, z ) {
  4339. // This method does not support objects having non-uniformly-scaled parent(s)
  4340. if ( x.isVector3 ) {
  4341. _target.copy( x );
  4342. } else {
  4343. _target.set( x, y, z );
  4344. }
  4345. const parent = this.parent;
  4346. this.updateWorldMatrix( true, false );
  4347. _position$3.setFromMatrixPosition( this.matrixWorld );
  4348. if ( this.isCamera || this.isLight ) {
  4349. _m1$1.lookAt( _position$3, _target, this.up );
  4350. } else {
  4351. _m1$1.lookAt( _target, _position$3, this.up );
  4352. }
  4353. this.quaternion.setFromRotationMatrix( _m1$1 );
  4354. if ( parent ) {
  4355. _m1$1.extractRotation( parent.matrixWorld );
  4356. _q1.setFromRotationMatrix( _m1$1 );
  4357. this.quaternion.premultiply( _q1.invert() );
  4358. }
  4359. }
  4360. add( object ) {
  4361. if ( arguments.length > 1 ) {
  4362. for ( let i = 0; i < arguments.length; i ++ ) {
  4363. this.add( arguments[ i ] );
  4364. }
  4365. return this;
  4366. }
  4367. if ( object === this ) {
  4368. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4369. return this;
  4370. }
  4371. if ( object && object.isObject3D ) {
  4372. if ( object.parent !== null ) {
  4373. object.parent.remove( object );
  4374. }
  4375. object.parent = this;
  4376. this.children.push( object );
  4377. object.dispatchEvent( _addedEvent );
  4378. } else {
  4379. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4380. }
  4381. return this;
  4382. }
  4383. remove( object ) {
  4384. if ( arguments.length > 1 ) {
  4385. for ( let i = 0; i < arguments.length; i ++ ) {
  4386. this.remove( arguments[ i ] );
  4387. }
  4388. return this;
  4389. }
  4390. const index = this.children.indexOf( object );
  4391. if ( index !== - 1 ) {
  4392. object.parent = null;
  4393. this.children.splice( index, 1 );
  4394. object.dispatchEvent( _removedEvent );
  4395. }
  4396. return this;
  4397. }
  4398. removeFromParent() {
  4399. const parent = this.parent;
  4400. if ( parent !== null ) {
  4401. parent.remove( this );
  4402. }
  4403. return this;
  4404. }
  4405. clear() {
  4406. for ( let i = 0; i < this.children.length; i ++ ) {
  4407. const object = this.children[ i ];
  4408. object.parent = null;
  4409. object.dispatchEvent( _removedEvent );
  4410. }
  4411. this.children.length = 0;
  4412. return this;
  4413. }
  4414. attach( object ) {
  4415. // adds object as a child of this, while maintaining the object's world transform
  4416. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4417. this.updateWorldMatrix( true, false );
  4418. _m1$1.copy( this.matrixWorld ).invert();
  4419. if ( object.parent !== null ) {
  4420. object.parent.updateWorldMatrix( true, false );
  4421. _m1$1.multiply( object.parent.matrixWorld );
  4422. }
  4423. object.applyMatrix4( _m1$1 );
  4424. this.add( object );
  4425. object.updateWorldMatrix( false, true );
  4426. return this;
  4427. }
  4428. getObjectById( id ) {
  4429. return this.getObjectByProperty( 'id', id );
  4430. }
  4431. getObjectByName( name ) {
  4432. return this.getObjectByProperty( 'name', name );
  4433. }
  4434. getObjectByProperty( name, value ) {
  4435. if ( this[ name ] === value ) return this;
  4436. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4437. const child = this.children[ i ];
  4438. const object = child.getObjectByProperty( name, value );
  4439. if ( object !== undefined ) {
  4440. return object;
  4441. }
  4442. }
  4443. return undefined;
  4444. }
  4445. getObjectsByProperty( name, value ) {
  4446. let result = [];
  4447. if ( this[ name ] === value ) result.push( this );
  4448. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4449. const childResult = this.children[ i ].getObjectsByProperty( name, value );
  4450. if ( childResult.length > 0 ) {
  4451. result = result.concat( childResult );
  4452. }
  4453. }
  4454. return result;
  4455. }
  4456. getWorldPosition( target ) {
  4457. this.updateWorldMatrix( true, false );
  4458. return target.setFromMatrixPosition( this.matrixWorld );
  4459. }
  4460. getWorldQuaternion( target ) {
  4461. this.updateWorldMatrix( true, false );
  4462. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4463. return target;
  4464. }
  4465. getWorldScale( target ) {
  4466. this.updateWorldMatrix( true, false );
  4467. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4468. return target;
  4469. }
  4470. getWorldDirection( target ) {
  4471. this.updateWorldMatrix( true, false );
  4472. const e = this.matrixWorld.elements;
  4473. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4474. }
  4475. raycast( /* raycaster, intersects */ ) {}
  4476. traverse( callback ) {
  4477. callback( this );
  4478. const children = this.children;
  4479. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4480. children[ i ].traverse( callback );
  4481. }
  4482. }
  4483. traverseVisible( callback ) {
  4484. if ( this.visible === false ) return;
  4485. callback( this );
  4486. const children = this.children;
  4487. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4488. children[ i ].traverseVisible( callback );
  4489. }
  4490. }
  4491. traverseAncestors( callback ) {
  4492. const parent = this.parent;
  4493. if ( parent !== null ) {
  4494. callback( parent );
  4495. parent.traverseAncestors( callback );
  4496. }
  4497. }
  4498. updateMatrix() {
  4499. this.matrix.compose( this.position, this.quaternion, this.scale );
  4500. this.matrixWorldNeedsUpdate = true;
  4501. }
  4502. updateMatrixWorld( force ) {
  4503. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4504. if ( this.matrixWorldNeedsUpdate || force ) {
  4505. if ( this.parent === null ) {
  4506. this.matrixWorld.copy( this.matrix );
  4507. } else {
  4508. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4509. }
  4510. this.matrixWorldNeedsUpdate = false;
  4511. force = true;
  4512. }
  4513. // update children
  4514. const children = this.children;
  4515. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4516. const child = children[ i ];
  4517. if ( child.matrixWorldAutoUpdate === true || force === true ) {
  4518. child.updateMatrixWorld( force );
  4519. }
  4520. }
  4521. }
  4522. updateWorldMatrix( updateParents, updateChildren ) {
  4523. const parent = this.parent;
  4524. if ( updateParents === true && parent !== null && parent.matrixWorldAutoUpdate === true ) {
  4525. parent.updateWorldMatrix( true, false );
  4526. }
  4527. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4528. if ( this.parent === null ) {
  4529. this.matrixWorld.copy( this.matrix );
  4530. } else {
  4531. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4532. }
  4533. // update children
  4534. if ( updateChildren === true ) {
  4535. const children = this.children;
  4536. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4537. const child = children[ i ];
  4538. if ( child.matrixWorldAutoUpdate === true ) {
  4539. child.updateWorldMatrix( false, true );
  4540. }
  4541. }
  4542. }
  4543. }
  4544. toJSON( meta ) {
  4545. // meta is a string when called from JSON.stringify
  4546. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4547. const output = {};
  4548. // meta is a hash used to collect geometries, materials.
  4549. // not providing it implies that this is the root object
  4550. // being serialized.
  4551. if ( isRootObject ) {
  4552. // initialize meta obj
  4553. meta = {
  4554. geometries: {},
  4555. materials: {},
  4556. textures: {},
  4557. images: {},
  4558. shapes: {},
  4559. skeletons: {},
  4560. animations: {},
  4561. nodes: {}
  4562. };
  4563. output.metadata = {
  4564. version: 4.5,
  4565. type: 'Object',
  4566. generator: 'Object3D.toJSON'
  4567. };
  4568. }
  4569. // standard Object3D serialization
  4570. const object = {};
  4571. object.uuid = this.uuid;
  4572. object.type = this.type;
  4573. if ( this.name !== '' ) object.name = this.name;
  4574. if ( this.castShadow === true ) object.castShadow = true;
  4575. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4576. if ( this.visible === false ) object.visible = false;
  4577. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4578. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4579. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  4580. object.layers = this.layers.mask;
  4581. object.matrix = this.matrix.toArray();
  4582. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4583. // object specific properties
  4584. if ( this.isInstancedMesh ) {
  4585. object.type = 'InstancedMesh';
  4586. object.count = this.count;
  4587. object.instanceMatrix = this.instanceMatrix.toJSON();
  4588. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4589. }
  4590. //
  4591. function serialize( library, element ) {
  4592. if ( library[ element.uuid ] === undefined ) {
  4593. library[ element.uuid ] = element.toJSON( meta );
  4594. }
  4595. return element.uuid;
  4596. }
  4597. if ( this.isScene ) {
  4598. if ( this.background ) {
  4599. if ( this.background.isColor ) {
  4600. object.background = this.background.toJSON();
  4601. } else if ( this.background.isTexture ) {
  4602. object.background = this.background.toJSON( meta ).uuid;
  4603. }
  4604. }
  4605. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4606. object.environment = this.environment.toJSON( meta ).uuid;
  4607. }
  4608. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4609. object.geometry = serialize( meta.geometries, this.geometry );
  4610. const parameters = this.geometry.parameters;
  4611. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4612. const shapes = parameters.shapes;
  4613. if ( Array.isArray( shapes ) ) {
  4614. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4615. const shape = shapes[ i ];
  4616. serialize( meta.shapes, shape );
  4617. }
  4618. } else {
  4619. serialize( meta.shapes, shapes );
  4620. }
  4621. }
  4622. }
  4623. if ( this.isSkinnedMesh ) {
  4624. object.bindMode = this.bindMode;
  4625. object.bindMatrix = this.bindMatrix.toArray();
  4626. if ( this.skeleton !== undefined ) {
  4627. serialize( meta.skeletons, this.skeleton );
  4628. object.skeleton = this.skeleton.uuid;
  4629. }
  4630. }
  4631. if ( this.material !== undefined ) {
  4632. if ( Array.isArray( this.material ) ) {
  4633. const uuids = [];
  4634. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4635. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4636. }
  4637. object.material = uuids;
  4638. } else {
  4639. object.material = serialize( meta.materials, this.material );
  4640. }
  4641. }
  4642. //
  4643. if ( this.children.length > 0 ) {
  4644. object.children = [];
  4645. for ( let i = 0; i < this.children.length; i ++ ) {
  4646. object.children.push( this.children[ i ].toJSON( meta ).object );
  4647. }
  4648. }
  4649. //
  4650. if ( this.animations.length > 0 ) {
  4651. object.animations = [];
  4652. for ( let i = 0; i < this.animations.length; i ++ ) {
  4653. const animation = this.animations[ i ];
  4654. object.animations.push( serialize( meta.animations, animation ) );
  4655. }
  4656. }
  4657. if ( isRootObject ) {
  4658. const geometries = extractFromCache( meta.geometries );
  4659. const materials = extractFromCache( meta.materials );
  4660. const textures = extractFromCache( meta.textures );
  4661. const images = extractFromCache( meta.images );
  4662. const shapes = extractFromCache( meta.shapes );
  4663. const skeletons = extractFromCache( meta.skeletons );
  4664. const animations = extractFromCache( meta.animations );
  4665. const nodes = extractFromCache( meta.nodes );
  4666. if ( geometries.length > 0 ) output.geometries = geometries;
  4667. if ( materials.length > 0 ) output.materials = materials;
  4668. if ( textures.length > 0 ) output.textures = textures;
  4669. if ( images.length > 0 ) output.images = images;
  4670. if ( shapes.length > 0 ) output.shapes = shapes;
  4671. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4672. if ( animations.length > 0 ) output.animations = animations;
  4673. if ( nodes.length > 0 ) output.nodes = nodes;
  4674. }
  4675. output.object = object;
  4676. return output;
  4677. // extract data from the cache hash
  4678. // remove metadata on each item
  4679. // and return as array
  4680. function extractFromCache( cache ) {
  4681. const values = [];
  4682. for ( const key in cache ) {
  4683. const data = cache[ key ];
  4684. delete data.metadata;
  4685. values.push( data );
  4686. }
  4687. return values;
  4688. }
  4689. }
  4690. clone( recursive ) {
  4691. return new this.constructor().copy( this, recursive );
  4692. }
  4693. copy( source, recursive = true ) {
  4694. this.name = source.name;
  4695. this.up.copy( source.up );
  4696. this.position.copy( source.position );
  4697. this.rotation.order = source.rotation.order;
  4698. this.quaternion.copy( source.quaternion );
  4699. this.scale.copy( source.scale );
  4700. this.matrix.copy( source.matrix );
  4701. this.matrixWorld.copy( source.matrixWorld );
  4702. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4703. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4704. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  4705. this.layers.mask = source.layers.mask;
  4706. this.visible = source.visible;
  4707. this.castShadow = source.castShadow;
  4708. this.receiveShadow = source.receiveShadow;
  4709. this.frustumCulled = source.frustumCulled;
  4710. this.renderOrder = source.renderOrder;
  4711. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4712. if ( recursive === true ) {
  4713. for ( let i = 0; i < source.children.length; i ++ ) {
  4714. const child = source.children[ i ];
  4715. this.add( child.clone() );
  4716. }
  4717. }
  4718. return this;
  4719. }
  4720. }
  4721. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4722. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  4723. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  4724. const _v0$1 = /*@__PURE__*/ new Vector3();
  4725. const _v1$3 = /*@__PURE__*/ new Vector3();
  4726. const _v2$2 = /*@__PURE__*/ new Vector3();
  4727. const _v3$1 = /*@__PURE__*/ new Vector3();
  4728. const _vab = /*@__PURE__*/ new Vector3();
  4729. const _vac = /*@__PURE__*/ new Vector3();
  4730. const _vbc = /*@__PURE__*/ new Vector3();
  4731. const _vap = /*@__PURE__*/ new Vector3();
  4732. const _vbp = /*@__PURE__*/ new Vector3();
  4733. const _vcp = /*@__PURE__*/ new Vector3();
  4734. class Triangle {
  4735. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  4736. this.a = a;
  4737. this.b = b;
  4738. this.c = c;
  4739. }
  4740. static getNormal( a, b, c, target ) {
  4741. target.subVectors( c, b );
  4742. _v0$1.subVectors( a, b );
  4743. target.cross( _v0$1 );
  4744. const targetLengthSq = target.lengthSq();
  4745. if ( targetLengthSq > 0 ) {
  4746. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  4747. }
  4748. return target.set( 0, 0, 0 );
  4749. }
  4750. // static/instance method to calculate barycentric coordinates
  4751. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4752. static getBarycoord( point, a, b, c, target ) {
  4753. _v0$1.subVectors( c, a );
  4754. _v1$3.subVectors( b, a );
  4755. _v2$2.subVectors( point, a );
  4756. const dot00 = _v0$1.dot( _v0$1 );
  4757. const dot01 = _v0$1.dot( _v1$3 );
  4758. const dot02 = _v0$1.dot( _v2$2 );
  4759. const dot11 = _v1$3.dot( _v1$3 );
  4760. const dot12 = _v1$3.dot( _v2$2 );
  4761. const denom = ( dot00 * dot11 - dot01 * dot01 );
  4762. // collinear or singular triangle
  4763. if ( denom === 0 ) {
  4764. // arbitrary location outside of triangle?
  4765. // not sure if this is the best idea, maybe should be returning undefined
  4766. return target.set( - 2, - 1, - 1 );
  4767. }
  4768. const invDenom = 1 / denom;
  4769. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4770. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4771. // barycentric coordinates must always sum to 1
  4772. return target.set( 1 - u - v, v, u );
  4773. }
  4774. static containsPoint( point, a, b, c ) {
  4775. this.getBarycoord( point, a, b, c, _v3$1 );
  4776. return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 );
  4777. }
  4778. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  4779. this.getBarycoord( point, p1, p2, p3, _v3$1 );
  4780. target.set( 0, 0 );
  4781. target.addScaledVector( uv1, _v3$1.x );
  4782. target.addScaledVector( uv2, _v3$1.y );
  4783. target.addScaledVector( uv3, _v3$1.z );
  4784. return target;
  4785. }
  4786. static isFrontFacing( a, b, c, direction ) {
  4787. _v0$1.subVectors( c, b );
  4788. _v1$3.subVectors( a, b );
  4789. // strictly front facing
  4790. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  4791. }
  4792. set( a, b, c ) {
  4793. this.a.copy( a );
  4794. this.b.copy( b );
  4795. this.c.copy( c );
  4796. return this;
  4797. }
  4798. setFromPointsAndIndices( points, i0, i1, i2 ) {
  4799. this.a.copy( points[ i0 ] );
  4800. this.b.copy( points[ i1 ] );
  4801. this.c.copy( points[ i2 ] );
  4802. return this;
  4803. }
  4804. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  4805. this.a.fromBufferAttribute( attribute, i0 );
  4806. this.b.fromBufferAttribute( attribute, i1 );
  4807. this.c.fromBufferAttribute( attribute, i2 );
  4808. return this;
  4809. }
  4810. clone() {
  4811. return new this.constructor().copy( this );
  4812. }
  4813. copy( triangle ) {
  4814. this.a.copy( triangle.a );
  4815. this.b.copy( triangle.b );
  4816. this.c.copy( triangle.c );
  4817. return this;
  4818. }
  4819. getArea() {
  4820. _v0$1.subVectors( this.c, this.b );
  4821. _v1$3.subVectors( this.a, this.b );
  4822. return _v0$1.cross( _v1$3 ).length() * 0.5;
  4823. }
  4824. getMidpoint( target ) {
  4825. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4826. }
  4827. getNormal( target ) {
  4828. return Triangle.getNormal( this.a, this.b, this.c, target );
  4829. }
  4830. getPlane( target ) {
  4831. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  4832. }
  4833. getBarycoord( point, target ) {
  4834. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  4835. }
  4836. getUV( point, uv1, uv2, uv3, target ) {
  4837. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  4838. }
  4839. containsPoint( point ) {
  4840. return Triangle.containsPoint( point, this.a, this.b, this.c );
  4841. }
  4842. isFrontFacing( direction ) {
  4843. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  4844. }
  4845. intersectsBox( box ) {
  4846. return box.intersectsTriangle( this );
  4847. }
  4848. closestPointToPoint( p, target ) {
  4849. const a = this.a, b = this.b, c = this.c;
  4850. let v, w;
  4851. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  4852. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  4853. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  4854. // basically, we're distinguishing which of the voronoi regions of the triangle
  4855. // the point lies in with the minimum amount of redundant computation.
  4856. _vab.subVectors( b, a );
  4857. _vac.subVectors( c, a );
  4858. _vap.subVectors( p, a );
  4859. const d1 = _vab.dot( _vap );
  4860. const d2 = _vac.dot( _vap );
  4861. if ( d1 <= 0 && d2 <= 0 ) {
  4862. // vertex region of A; barycentric coords (1, 0, 0)
  4863. return target.copy( a );
  4864. }
  4865. _vbp.subVectors( p, b );
  4866. const d3 = _vab.dot( _vbp );
  4867. const d4 = _vac.dot( _vbp );
  4868. if ( d3 >= 0 && d4 <= d3 ) {
  4869. // vertex region of B; barycentric coords (0, 1, 0)
  4870. return target.copy( b );
  4871. }
  4872. const vc = d1 * d4 - d3 * d2;
  4873. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  4874. v = d1 / ( d1 - d3 );
  4875. // edge region of AB; barycentric coords (1-v, v, 0)
  4876. return target.copy( a ).addScaledVector( _vab, v );
  4877. }
  4878. _vcp.subVectors( p, c );
  4879. const d5 = _vab.dot( _vcp );
  4880. const d6 = _vac.dot( _vcp );
  4881. if ( d6 >= 0 && d5 <= d6 ) {
  4882. // vertex region of C; barycentric coords (0, 0, 1)
  4883. return target.copy( c );
  4884. }
  4885. const vb = d5 * d2 - d1 * d6;
  4886. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  4887. w = d2 / ( d2 - d6 );
  4888. // edge region of AC; barycentric coords (1-w, 0, w)
  4889. return target.copy( a ).addScaledVector( _vac, w );
  4890. }
  4891. const va = d3 * d6 - d5 * d4;
  4892. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  4893. _vbc.subVectors( c, b );
  4894. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  4895. // edge region of BC; barycentric coords (0, 1-w, w)
  4896. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  4897. }
  4898. // face region
  4899. const denom = 1 / ( va + vb + vc );
  4900. // u = va * denom
  4901. v = vb * denom;
  4902. w = vc * denom;
  4903. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  4904. }
  4905. equals( triangle ) {
  4906. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4907. }
  4908. }
  4909. let materialId = 0;
  4910. class Material extends EventDispatcher {
  4911. constructor() {
  4912. super();
  4913. this.isMaterial = true;
  4914. Object.defineProperty( this, 'id', { value: materialId ++ } );
  4915. this.uuid = generateUUID();
  4916. this.name = '';
  4917. this.type = 'Material';
  4918. this.blending = NormalBlending;
  4919. this.side = FrontSide;
  4920. this.vertexColors = false;
  4921. this.opacity = 1;
  4922. this.transparent = false;
  4923. this.blendSrc = SrcAlphaFactor;
  4924. this.blendDst = OneMinusSrcAlphaFactor;
  4925. this.blendEquation = AddEquation;
  4926. this.blendSrcAlpha = null;
  4927. this.blendDstAlpha = null;
  4928. this.blendEquationAlpha = null;
  4929. this.depthFunc = LessEqualDepth;
  4930. this.depthTest = true;
  4931. this.depthWrite = true;
  4932. this.stencilWriteMask = 0xff;
  4933. this.stencilFunc = AlwaysStencilFunc;
  4934. this.stencilRef = 0;
  4935. this.stencilFuncMask = 0xff;
  4936. this.stencilFail = KeepStencilOp;
  4937. this.stencilZFail = KeepStencilOp;
  4938. this.stencilZPass = KeepStencilOp;
  4939. this.stencilWrite = false;
  4940. this.clippingPlanes = null;
  4941. this.clipIntersection = false;
  4942. this.clipShadows = false;
  4943. this.shadowSide = null;
  4944. this.colorWrite = true;
  4945. this.precision = null; // override the renderer's default precision for this material
  4946. this.polygonOffset = false;
  4947. this.polygonOffsetFactor = 0;
  4948. this.polygonOffsetUnits = 0;
  4949. this.dithering = false;
  4950. this.alphaToCoverage = false;
  4951. this.premultipliedAlpha = false;
  4952. this.forceSinglePass = false;
  4953. this.visible = true;
  4954. this.toneMapped = true;
  4955. this.userData = {};
  4956. this.version = 0;
  4957. this._alphaTest = 0;
  4958. }
  4959. get alphaTest() {
  4960. return this._alphaTest;
  4961. }
  4962. set alphaTest( value ) {
  4963. if ( this._alphaTest > 0 !== value > 0 ) {
  4964. this.version ++;
  4965. }
  4966. this._alphaTest = value;
  4967. }
  4968. onBuild( /* shaderobject, renderer */ ) {}
  4969. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  4970. onBeforeCompile( /* shaderobject, renderer */ ) {}
  4971. customProgramCacheKey() {
  4972. return this.onBeforeCompile.toString();
  4973. }
  4974. setValues( values ) {
  4975. if ( values === undefined ) return;
  4976. for ( const key in values ) {
  4977. const newValue = values[ key ];
  4978. if ( newValue === undefined ) {
  4979. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  4980. continue;
  4981. }
  4982. const currentValue = this[ key ];
  4983. if ( currentValue === undefined ) {
  4984. console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' );
  4985. continue;
  4986. }
  4987. if ( currentValue && currentValue.isColor ) {
  4988. currentValue.set( newValue );
  4989. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  4990. currentValue.copy( newValue );
  4991. } else {
  4992. this[ key ] = newValue;
  4993. }
  4994. }
  4995. }
  4996. toJSON( meta ) {
  4997. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4998. if ( isRootObject ) {
  4999. meta = {
  5000. textures: {},
  5001. images: {}
  5002. };
  5003. }
  5004. const data = {
  5005. metadata: {
  5006. version: 4.5,
  5007. type: 'Material',
  5008. generator: 'Material.toJSON'
  5009. }
  5010. };
  5011. // standard Material serialization
  5012. data.uuid = this.uuid;
  5013. data.type = this.type;
  5014. if ( this.name !== '' ) data.name = this.name;
  5015. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5016. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5017. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5018. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5019. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5020. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5021. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5022. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5023. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5024. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5025. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5026. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5027. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5028. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5029. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5030. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5031. }
  5032. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5033. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5034. }
  5035. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5036. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5037. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5038. }
  5039. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5040. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5041. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5042. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5043. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5044. }
  5045. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5046. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5047. }
  5048. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5049. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5050. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5051. if ( this.lightMap && this.lightMap.isTexture ) {
  5052. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5053. data.lightMapIntensity = this.lightMapIntensity;
  5054. }
  5055. if ( this.aoMap && this.aoMap.isTexture ) {
  5056. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5057. data.aoMapIntensity = this.aoMapIntensity;
  5058. }
  5059. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5060. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5061. data.bumpScale = this.bumpScale;
  5062. }
  5063. if ( this.normalMap && this.normalMap.isTexture ) {
  5064. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5065. data.normalMapType = this.normalMapType;
  5066. data.normalScale = this.normalScale.toArray();
  5067. }
  5068. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5069. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5070. data.displacementScale = this.displacementScale;
  5071. data.displacementBias = this.displacementBias;
  5072. }
  5073. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5074. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5075. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5076. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5077. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5078. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5079. if ( this.envMap && this.envMap.isTexture ) {
  5080. data.envMap = this.envMap.toJSON( meta ).uuid;
  5081. if ( this.combine !== undefined ) data.combine = this.combine;
  5082. }
  5083. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5084. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5085. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5086. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5087. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5088. }
  5089. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5090. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5091. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5092. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5093. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  5094. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5095. if ( this.size !== undefined ) data.size = this.size;
  5096. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5097. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5098. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5099. if ( this.side !== FrontSide ) data.side = this.side;
  5100. if ( this.vertexColors ) data.vertexColors = true;
  5101. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5102. if ( this.transparent === true ) data.transparent = this.transparent;
  5103. data.depthFunc = this.depthFunc;
  5104. data.depthTest = this.depthTest;
  5105. data.depthWrite = this.depthWrite;
  5106. data.colorWrite = this.colorWrite;
  5107. data.stencilWrite = this.stencilWrite;
  5108. data.stencilWriteMask = this.stencilWriteMask;
  5109. data.stencilFunc = this.stencilFunc;
  5110. data.stencilRef = this.stencilRef;
  5111. data.stencilFuncMask = this.stencilFuncMask;
  5112. data.stencilFail = this.stencilFail;
  5113. data.stencilZFail = this.stencilZFail;
  5114. data.stencilZPass = this.stencilZPass;
  5115. // rotation (SpriteMaterial)
  5116. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5117. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5118. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5119. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5120. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5121. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5122. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5123. if ( this.scale !== undefined ) data.scale = this.scale;
  5124. if ( this.dithering === true ) data.dithering = true;
  5125. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5126. if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage;
  5127. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  5128. if ( this.forceSinglePass === true ) data.forceSinglePass = this.forceSinglePass;
  5129. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  5130. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5131. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5132. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5133. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  5134. if ( this.visible === false ) data.visible = false;
  5135. if ( this.toneMapped === false ) data.toneMapped = false;
  5136. if ( this.fog === false ) data.fog = false;
  5137. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  5138. // TODO: Copied from Object3D.toJSON
  5139. function extractFromCache( cache ) {
  5140. const values = [];
  5141. for ( const key in cache ) {
  5142. const data = cache[ key ];
  5143. delete data.metadata;
  5144. values.push( data );
  5145. }
  5146. return values;
  5147. }
  5148. if ( isRootObject ) {
  5149. const textures = extractFromCache( meta.textures );
  5150. const images = extractFromCache( meta.images );
  5151. if ( textures.length > 0 ) data.textures = textures;
  5152. if ( images.length > 0 ) data.images = images;
  5153. }
  5154. return data;
  5155. }
  5156. clone() {
  5157. return new this.constructor().copy( this );
  5158. }
  5159. copy( source ) {
  5160. this.name = source.name;
  5161. this.blending = source.blending;
  5162. this.side = source.side;
  5163. this.vertexColors = source.vertexColors;
  5164. this.opacity = source.opacity;
  5165. this.transparent = source.transparent;
  5166. this.blendSrc = source.blendSrc;
  5167. this.blendDst = source.blendDst;
  5168. this.blendEquation = source.blendEquation;
  5169. this.blendSrcAlpha = source.blendSrcAlpha;
  5170. this.blendDstAlpha = source.blendDstAlpha;
  5171. this.blendEquationAlpha = source.blendEquationAlpha;
  5172. this.depthFunc = source.depthFunc;
  5173. this.depthTest = source.depthTest;
  5174. this.depthWrite = source.depthWrite;
  5175. this.stencilWriteMask = source.stencilWriteMask;
  5176. this.stencilFunc = source.stencilFunc;
  5177. this.stencilRef = source.stencilRef;
  5178. this.stencilFuncMask = source.stencilFuncMask;
  5179. this.stencilFail = source.stencilFail;
  5180. this.stencilZFail = source.stencilZFail;
  5181. this.stencilZPass = source.stencilZPass;
  5182. this.stencilWrite = source.stencilWrite;
  5183. const srcPlanes = source.clippingPlanes;
  5184. let dstPlanes = null;
  5185. if ( srcPlanes !== null ) {
  5186. const n = srcPlanes.length;
  5187. dstPlanes = new Array( n );
  5188. for ( let i = 0; i !== n; ++ i ) {
  5189. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5190. }
  5191. }
  5192. this.clippingPlanes = dstPlanes;
  5193. this.clipIntersection = source.clipIntersection;
  5194. this.clipShadows = source.clipShadows;
  5195. this.shadowSide = source.shadowSide;
  5196. this.colorWrite = source.colorWrite;
  5197. this.precision = source.precision;
  5198. this.polygonOffset = source.polygonOffset;
  5199. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5200. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5201. this.dithering = source.dithering;
  5202. this.alphaTest = source.alphaTest;
  5203. this.alphaToCoverage = source.alphaToCoverage;
  5204. this.premultipliedAlpha = source.premultipliedAlpha;
  5205. this.forceSinglePass = source.forceSinglePass;
  5206. this.visible = source.visible;
  5207. this.toneMapped = source.toneMapped;
  5208. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5209. return this;
  5210. }
  5211. dispose() {
  5212. this.dispatchEvent( { type: 'dispose' } );
  5213. }
  5214. set needsUpdate( value ) {
  5215. if ( value === true ) this.version ++;
  5216. }
  5217. }
  5218. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  5219. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  5220. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  5221. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  5222. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  5223. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  5224. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  5225. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  5226. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  5227. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  5228. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  5229. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  5230. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  5231. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  5232. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  5233. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  5234. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  5235. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  5236. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  5237. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  5238. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  5239. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  5240. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  5241. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  5242. const _hslA = { h: 0, s: 0, l: 0 };
  5243. const _hslB = { h: 0, s: 0, l: 0 };
  5244. function hue2rgb( p, q, t ) {
  5245. if ( t < 0 ) t += 1;
  5246. if ( t > 1 ) t -= 1;
  5247. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  5248. if ( t < 1 / 2 ) return q;
  5249. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  5250. return p;
  5251. }
  5252. class Color {
  5253. constructor( r, g, b ) {
  5254. this.isColor = true;
  5255. this.r = 1;
  5256. this.g = 1;
  5257. this.b = 1;
  5258. if ( g === undefined && b === undefined ) {
  5259. // r is THREE.Color, hex or string
  5260. return this.set( r );
  5261. }
  5262. return this.setRGB( r, g, b );
  5263. }
  5264. set( value ) {
  5265. if ( value && value.isColor ) {
  5266. this.copy( value );
  5267. } else if ( typeof value === 'number' ) {
  5268. this.setHex( value );
  5269. } else if ( typeof value === 'string' ) {
  5270. this.setStyle( value );
  5271. }
  5272. return this;
  5273. }
  5274. setScalar( scalar ) {
  5275. this.r = scalar;
  5276. this.g = scalar;
  5277. this.b = scalar;
  5278. return this;
  5279. }
  5280. setHex( hex, colorSpace = SRGBColorSpace ) {
  5281. hex = Math.floor( hex );
  5282. this.r = ( hex >> 16 & 255 ) / 255;
  5283. this.g = ( hex >> 8 & 255 ) / 255;
  5284. this.b = ( hex & 255 ) / 255;
  5285. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5286. return this;
  5287. }
  5288. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  5289. this.r = r;
  5290. this.g = g;
  5291. this.b = b;
  5292. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5293. return this;
  5294. }
  5295. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  5296. // h,s,l ranges are in 0.0 - 1.0
  5297. h = euclideanModulo( h, 1 );
  5298. s = clamp( s, 0, 1 );
  5299. l = clamp( l, 0, 1 );
  5300. if ( s === 0 ) {
  5301. this.r = this.g = this.b = l;
  5302. } else {
  5303. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  5304. const q = ( 2 * l ) - p;
  5305. this.r = hue2rgb( q, p, h + 1 / 3 );
  5306. this.g = hue2rgb( q, p, h );
  5307. this.b = hue2rgb( q, p, h - 1 / 3 );
  5308. }
  5309. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5310. return this;
  5311. }
  5312. setStyle( style, colorSpace = SRGBColorSpace ) {
  5313. function handleAlpha( string ) {
  5314. if ( string === undefined ) return;
  5315. if ( parseFloat( string ) < 1 ) {
  5316. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  5317. }
  5318. }
  5319. let m;
  5320. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  5321. // rgb / hsl
  5322. let color;
  5323. const name = m[ 1 ];
  5324. const components = m[ 2 ];
  5325. switch ( name ) {
  5326. case 'rgb':
  5327. case 'rgba':
  5328. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5329. // rgb(255,0,0) rgba(255,0,0,0.5)
  5330. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  5331. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  5332. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  5333. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5334. handleAlpha( color[ 4 ] );
  5335. return this;
  5336. }
  5337. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5338. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  5339. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  5340. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  5341. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  5342. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5343. handleAlpha( color[ 4 ] );
  5344. return this;
  5345. }
  5346. break;
  5347. case 'hsl':
  5348. case 'hsla':
  5349. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  5350. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  5351. const h = parseFloat( color[ 1 ] ) / 360;
  5352. const s = parseFloat( color[ 2 ] ) / 100;
  5353. const l = parseFloat( color[ 3 ] ) / 100;
  5354. handleAlpha( color[ 4 ] );
  5355. return this.setHSL( h, s, l, colorSpace );
  5356. }
  5357. break;
  5358. default:
  5359. console.warn( 'THREE.Color: Unknown color model ' + style );
  5360. }
  5361. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  5362. // hex color
  5363. const hex = m[ 1 ];
  5364. const size = hex.length;
  5365. if ( size === 3 ) {
  5366. // #ff0
  5367. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  5368. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  5369. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  5370. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5371. return this;
  5372. } else if ( size === 6 ) {
  5373. // #ff0000
  5374. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  5375. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  5376. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  5377. ColorManagement.toWorkingColorSpace( this, colorSpace );
  5378. return this;
  5379. } else {
  5380. console.warn( 'THREE.Color: Invalid hex color ' + style );
  5381. }
  5382. } else if ( style && style.length > 0 ) {
  5383. return this.setColorName( style, colorSpace );
  5384. }
  5385. return this;
  5386. }
  5387. setColorName( style, colorSpace = SRGBColorSpace ) {
  5388. // color keywords
  5389. const hex = _colorKeywords[ style.toLowerCase() ];
  5390. if ( hex !== undefined ) {
  5391. // red
  5392. this.setHex( hex, colorSpace );
  5393. } else {
  5394. // unknown color
  5395. console.warn( 'THREE.Color: Unknown color ' + style );
  5396. }
  5397. return this;
  5398. }
  5399. clone() {
  5400. return new this.constructor( this.r, this.g, this.b );
  5401. }
  5402. copy( color ) {
  5403. this.r = color.r;
  5404. this.g = color.g;
  5405. this.b = color.b;
  5406. return this;
  5407. }
  5408. copySRGBToLinear( color ) {
  5409. this.r = SRGBToLinear( color.r );
  5410. this.g = SRGBToLinear( color.g );
  5411. this.b = SRGBToLinear( color.b );
  5412. return this;
  5413. }
  5414. copyLinearToSRGB( color ) {
  5415. this.r = LinearToSRGB( color.r );
  5416. this.g = LinearToSRGB( color.g );
  5417. this.b = LinearToSRGB( color.b );
  5418. return this;
  5419. }
  5420. convertSRGBToLinear() {
  5421. this.copySRGBToLinear( this );
  5422. return this;
  5423. }
  5424. convertLinearToSRGB() {
  5425. this.copyLinearToSRGB( this );
  5426. return this;
  5427. }
  5428. getHex( colorSpace = SRGBColorSpace ) {
  5429. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5430. return clamp( _color.r * 255, 0, 255 ) << 16 ^ clamp( _color.g * 255, 0, 255 ) << 8 ^ clamp( _color.b * 255, 0, 255 ) << 0;
  5431. }
  5432. getHexString( colorSpace = SRGBColorSpace ) {
  5433. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  5434. }
  5435. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  5436. // h,s,l ranges are in 0.0 - 1.0
  5437. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5438. const r = _color.r, g = _color.g, b = _color.b;
  5439. const max = Math.max( r, g, b );
  5440. const min = Math.min( r, g, b );
  5441. let hue, saturation;
  5442. const lightness = ( min + max ) / 2.0;
  5443. if ( min === max ) {
  5444. hue = 0;
  5445. saturation = 0;
  5446. } else {
  5447. const delta = max - min;
  5448. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  5449. switch ( max ) {
  5450. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  5451. case g: hue = ( b - r ) / delta + 2; break;
  5452. case b: hue = ( r - g ) / delta + 4; break;
  5453. }
  5454. hue /= 6;
  5455. }
  5456. target.h = hue;
  5457. target.s = saturation;
  5458. target.l = lightness;
  5459. return target;
  5460. }
  5461. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  5462. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5463. target.r = _color.r;
  5464. target.g = _color.g;
  5465. target.b = _color.b;
  5466. return target;
  5467. }
  5468. getStyle( colorSpace = SRGBColorSpace ) {
  5469. ColorManagement.fromWorkingColorSpace( _color.copy( this ), colorSpace );
  5470. const r = _color.r, g = _color.g, b = _color.b;
  5471. if ( colorSpace !== SRGBColorSpace ) {
  5472. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  5473. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  5474. }
  5475. return `rgb(${( r * 255 ) | 0},${( g * 255 ) | 0},${( b * 255 ) | 0})`;
  5476. }
  5477. offsetHSL( h, s, l ) {
  5478. this.getHSL( _hslA );
  5479. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  5480. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  5481. return this;
  5482. }
  5483. add( color ) {
  5484. this.r += color.r;
  5485. this.g += color.g;
  5486. this.b += color.b;
  5487. return this;
  5488. }
  5489. addColors( color1, color2 ) {
  5490. this.r = color1.r + color2.r;
  5491. this.g = color1.g + color2.g;
  5492. this.b = color1.b + color2.b;
  5493. return this;
  5494. }
  5495. addScalar( s ) {
  5496. this.r += s;
  5497. this.g += s;
  5498. this.b += s;
  5499. return this;
  5500. }
  5501. sub( color ) {
  5502. this.r = Math.max( 0, this.r - color.r );
  5503. this.g = Math.max( 0, this.g - color.g );
  5504. this.b = Math.max( 0, this.b - color.b );
  5505. return this;
  5506. }
  5507. multiply( color ) {
  5508. this.r *= color.r;
  5509. this.g *= color.g;
  5510. this.b *= color.b;
  5511. return this;
  5512. }
  5513. multiplyScalar( s ) {
  5514. this.r *= s;
  5515. this.g *= s;
  5516. this.b *= s;
  5517. return this;
  5518. }
  5519. lerp( color, alpha ) {
  5520. this.r += ( color.r - this.r ) * alpha;
  5521. this.g += ( color.g - this.g ) * alpha;
  5522. this.b += ( color.b - this.b ) * alpha;
  5523. return this;
  5524. }
  5525. lerpColors( color1, color2, alpha ) {
  5526. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  5527. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  5528. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  5529. return this;
  5530. }
  5531. lerpHSL( color, alpha ) {
  5532. this.getHSL( _hslA );
  5533. color.getHSL( _hslB );
  5534. const h = lerp( _hslA.h, _hslB.h, alpha );
  5535. const s = lerp( _hslA.s, _hslB.s, alpha );
  5536. const l = lerp( _hslA.l, _hslB.l, alpha );
  5537. this.setHSL( h, s, l );
  5538. return this;
  5539. }
  5540. equals( c ) {
  5541. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  5542. }
  5543. fromArray( array, offset = 0 ) {
  5544. this.r = array[ offset ];
  5545. this.g = array[ offset + 1 ];
  5546. this.b = array[ offset + 2 ];
  5547. return this;
  5548. }
  5549. toArray( array = [], offset = 0 ) {
  5550. array[ offset ] = this.r;
  5551. array[ offset + 1 ] = this.g;
  5552. array[ offset + 2 ] = this.b;
  5553. return array;
  5554. }
  5555. fromBufferAttribute( attribute, index ) {
  5556. this.r = attribute.getX( index );
  5557. this.g = attribute.getY( index );
  5558. this.b = attribute.getZ( index );
  5559. return this;
  5560. }
  5561. toJSON() {
  5562. return this.getHex();
  5563. }
  5564. *[ Symbol.iterator ]() {
  5565. yield this.r;
  5566. yield this.g;
  5567. yield this.b;
  5568. }
  5569. }
  5570. const _color = new Color();
  5571. Color.NAMES = _colorKeywords;
  5572. class MeshBasicMaterial extends Material {
  5573. constructor( parameters ) {
  5574. super();
  5575. this.isMeshBasicMaterial = true;
  5576. this.type = 'MeshBasicMaterial';
  5577. this.color = new Color( 0xffffff ); // emissive
  5578. this.map = null;
  5579. this.lightMap = null;
  5580. this.lightMapIntensity = 1.0;
  5581. this.aoMap = null;
  5582. this.aoMapIntensity = 1.0;
  5583. this.specularMap = null;
  5584. this.alphaMap = null;
  5585. this.envMap = null;
  5586. this.combine = MultiplyOperation;
  5587. this.reflectivity = 1;
  5588. this.refractionRatio = 0.98;
  5589. this.wireframe = false;
  5590. this.wireframeLinewidth = 1;
  5591. this.wireframeLinecap = 'round';
  5592. this.wireframeLinejoin = 'round';
  5593. this.fog = true;
  5594. this.setValues( parameters );
  5595. }
  5596. copy( source ) {
  5597. super.copy( source );
  5598. this.color.copy( source.color );
  5599. this.map = source.map;
  5600. this.lightMap = source.lightMap;
  5601. this.lightMapIntensity = source.lightMapIntensity;
  5602. this.aoMap = source.aoMap;
  5603. this.aoMapIntensity = source.aoMapIntensity;
  5604. this.specularMap = source.specularMap;
  5605. this.alphaMap = source.alphaMap;
  5606. this.envMap = source.envMap;
  5607. this.combine = source.combine;
  5608. this.reflectivity = source.reflectivity;
  5609. this.refractionRatio = source.refractionRatio;
  5610. this.wireframe = source.wireframe;
  5611. this.wireframeLinewidth = source.wireframeLinewidth;
  5612. this.wireframeLinecap = source.wireframeLinecap;
  5613. this.wireframeLinejoin = source.wireframeLinejoin;
  5614. this.fog = source.fog;
  5615. return this;
  5616. }
  5617. }
  5618. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  5619. const _tables = /*@__PURE__*/ _generateTables();
  5620. function _generateTables() {
  5621. // float32 to float16 helpers
  5622. const buffer = new ArrayBuffer( 4 );
  5623. const floatView = new Float32Array( buffer );
  5624. const uint32View = new Uint32Array( buffer );
  5625. const baseTable = new Uint32Array( 512 );
  5626. const shiftTable = new Uint32Array( 512 );
  5627. for ( let i = 0; i < 256; ++ i ) {
  5628. const e = i - 127;
  5629. // very small number (0, -0)
  5630. if ( e < - 27 ) {
  5631. baseTable[ i ] = 0x0000;
  5632. baseTable[ i | 0x100 ] = 0x8000;
  5633. shiftTable[ i ] = 24;
  5634. shiftTable[ i | 0x100 ] = 24;
  5635. // small number (denorm)
  5636. } else if ( e < - 14 ) {
  5637. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  5638. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  5639. shiftTable[ i ] = - e - 1;
  5640. shiftTable[ i | 0x100 ] = - e - 1;
  5641. // normal number
  5642. } else if ( e <= 15 ) {
  5643. baseTable[ i ] = ( e + 15 ) << 10;
  5644. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  5645. shiftTable[ i ] = 13;
  5646. shiftTable[ i | 0x100 ] = 13;
  5647. // large number (Infinity, -Infinity)
  5648. } else if ( e < 128 ) {
  5649. baseTable[ i ] = 0x7c00;
  5650. baseTable[ i | 0x100 ] = 0xfc00;
  5651. shiftTable[ i ] = 24;
  5652. shiftTable[ i | 0x100 ] = 24;
  5653. // stay (NaN, Infinity, -Infinity)
  5654. } else {
  5655. baseTable[ i ] = 0x7c00;
  5656. baseTable[ i | 0x100 ] = 0xfc00;
  5657. shiftTable[ i ] = 13;
  5658. shiftTable[ i | 0x100 ] = 13;
  5659. }
  5660. }
  5661. // float16 to float32 helpers
  5662. const mantissaTable = new Uint32Array( 2048 );
  5663. const exponentTable = new Uint32Array( 64 );
  5664. const offsetTable = new Uint32Array( 64 );
  5665. for ( let i = 1; i < 1024; ++ i ) {
  5666. let m = i << 13; // zero pad mantissa bits
  5667. let e = 0; // zero exponent
  5668. // normalized
  5669. while ( ( m & 0x00800000 ) === 0 ) {
  5670. m <<= 1;
  5671. e -= 0x00800000; // decrement exponent
  5672. }
  5673. m &= ~ 0x00800000; // clear leading 1 bit
  5674. e += 0x38800000; // adjust bias
  5675. mantissaTable[ i ] = m | e;
  5676. }
  5677. for ( let i = 1024; i < 2048; ++ i ) {
  5678. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  5679. }
  5680. for ( let i = 1; i < 31; ++ i ) {
  5681. exponentTable[ i ] = i << 23;
  5682. }
  5683. exponentTable[ 31 ] = 0x47800000;
  5684. exponentTable[ 32 ] = 0x80000000;
  5685. for ( let i = 33; i < 63; ++ i ) {
  5686. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  5687. }
  5688. exponentTable[ 63 ] = 0xc7800000;
  5689. for ( let i = 1; i < 64; ++ i ) {
  5690. if ( i !== 32 ) {
  5691. offsetTable[ i ] = 1024;
  5692. }
  5693. }
  5694. return {
  5695. floatView: floatView,
  5696. uint32View: uint32View,
  5697. baseTable: baseTable,
  5698. shiftTable: shiftTable,
  5699. mantissaTable: mantissaTable,
  5700. exponentTable: exponentTable,
  5701. offsetTable: offsetTable
  5702. };
  5703. }
  5704. // float32 to float16
  5705. function toHalfFloat( val ) {
  5706. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  5707. val = clamp( val, - 65504, 65504 );
  5708. _tables.floatView[ 0 ] = val;
  5709. const f = _tables.uint32View[ 0 ];
  5710. const e = ( f >> 23 ) & 0x1ff;
  5711. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  5712. }
  5713. // float16 to float32
  5714. function fromHalfFloat( val ) {
  5715. const m = val >> 10;
  5716. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  5717. return _tables.floatView[ 0 ];
  5718. }
  5719. const DataUtils = {
  5720. toHalfFloat: toHalfFloat,
  5721. fromHalfFloat: fromHalfFloat,
  5722. };
  5723. const _vector$9 = /*@__PURE__*/ new Vector3();
  5724. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5725. class BufferAttribute {
  5726. constructor( array, itemSize, normalized = false ) {
  5727. if ( Array.isArray( array ) ) {
  5728. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5729. }
  5730. this.isBufferAttribute = true;
  5731. this.name = '';
  5732. this.array = array;
  5733. this.itemSize = itemSize;
  5734. this.count = array !== undefined ? array.length / itemSize : 0;
  5735. this.normalized = normalized;
  5736. this.usage = StaticDrawUsage;
  5737. this.updateRange = { offset: 0, count: - 1 };
  5738. this.version = 0;
  5739. }
  5740. onUploadCallback() {}
  5741. set needsUpdate( value ) {
  5742. if ( value === true ) this.version ++;
  5743. }
  5744. setUsage( value ) {
  5745. this.usage = value;
  5746. return this;
  5747. }
  5748. copy( source ) {
  5749. this.name = source.name;
  5750. this.array = new source.array.constructor( source.array );
  5751. this.itemSize = source.itemSize;
  5752. this.count = source.count;
  5753. this.normalized = source.normalized;
  5754. this.usage = source.usage;
  5755. return this;
  5756. }
  5757. copyAt( index1, attribute, index2 ) {
  5758. index1 *= this.itemSize;
  5759. index2 *= attribute.itemSize;
  5760. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5761. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5762. }
  5763. return this;
  5764. }
  5765. copyArray( array ) {
  5766. this.array.set( array );
  5767. return this;
  5768. }
  5769. applyMatrix3( m ) {
  5770. if ( this.itemSize === 2 ) {
  5771. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5772. _vector2$1.fromBufferAttribute( this, i );
  5773. _vector2$1.applyMatrix3( m );
  5774. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5775. }
  5776. } else if ( this.itemSize === 3 ) {
  5777. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5778. _vector$9.fromBufferAttribute( this, i );
  5779. _vector$9.applyMatrix3( m );
  5780. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5781. }
  5782. }
  5783. return this;
  5784. }
  5785. applyMatrix4( m ) {
  5786. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5787. _vector$9.fromBufferAttribute( this, i );
  5788. _vector$9.applyMatrix4( m );
  5789. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5790. }
  5791. return this;
  5792. }
  5793. applyNormalMatrix( m ) {
  5794. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5795. _vector$9.fromBufferAttribute( this, i );
  5796. _vector$9.applyNormalMatrix( m );
  5797. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5798. }
  5799. return this;
  5800. }
  5801. transformDirection( m ) {
  5802. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5803. _vector$9.fromBufferAttribute( this, i );
  5804. _vector$9.transformDirection( m );
  5805. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5806. }
  5807. return this;
  5808. }
  5809. set( value, offset = 0 ) {
  5810. // Matching BufferAttribute constructor, do not normalize the array.
  5811. this.array.set( value, offset );
  5812. return this;
  5813. }
  5814. getX( index ) {
  5815. let x = this.array[ index * this.itemSize ];
  5816. if ( this.normalized ) x = denormalize( x, this.array );
  5817. return x;
  5818. }
  5819. setX( index, x ) {
  5820. if ( this.normalized ) x = normalize( x, this.array );
  5821. this.array[ index * this.itemSize ] = x;
  5822. return this;
  5823. }
  5824. getY( index ) {
  5825. let y = this.array[ index * this.itemSize + 1 ];
  5826. if ( this.normalized ) y = denormalize( y, this.array );
  5827. return y;
  5828. }
  5829. setY( index, y ) {
  5830. if ( this.normalized ) y = normalize( y, this.array );
  5831. this.array[ index * this.itemSize + 1 ] = y;
  5832. return this;
  5833. }
  5834. getZ( index ) {
  5835. let z = this.array[ index * this.itemSize + 2 ];
  5836. if ( this.normalized ) z = denormalize( z, this.array );
  5837. return z;
  5838. }
  5839. setZ( index, z ) {
  5840. if ( this.normalized ) z = normalize( z, this.array );
  5841. this.array[ index * this.itemSize + 2 ] = z;
  5842. return this;
  5843. }
  5844. getW( index ) {
  5845. let w = this.array[ index * this.itemSize + 3 ];
  5846. if ( this.normalized ) w = denormalize( w, this.array );
  5847. return w;
  5848. }
  5849. setW( index, w ) {
  5850. if ( this.normalized ) w = normalize( w, this.array );
  5851. this.array[ index * this.itemSize + 3 ] = w;
  5852. return this;
  5853. }
  5854. setXY( index, x, y ) {
  5855. index *= this.itemSize;
  5856. if ( this.normalized ) {
  5857. x = normalize( x, this.array );
  5858. y = normalize( y, this.array );
  5859. }
  5860. this.array[ index + 0 ] = x;
  5861. this.array[ index + 1 ] = y;
  5862. return this;
  5863. }
  5864. setXYZ( index, x, y, z ) {
  5865. index *= this.itemSize;
  5866. if ( this.normalized ) {
  5867. x = normalize( x, this.array );
  5868. y = normalize( y, this.array );
  5869. z = normalize( z, this.array );
  5870. }
  5871. this.array[ index + 0 ] = x;
  5872. this.array[ index + 1 ] = y;
  5873. this.array[ index + 2 ] = z;
  5874. return this;
  5875. }
  5876. setXYZW( index, x, y, z, w ) {
  5877. index *= this.itemSize;
  5878. if ( this.normalized ) {
  5879. x = normalize( x, this.array );
  5880. y = normalize( y, this.array );
  5881. z = normalize( z, this.array );
  5882. w = normalize( w, this.array );
  5883. }
  5884. this.array[ index + 0 ] = x;
  5885. this.array[ index + 1 ] = y;
  5886. this.array[ index + 2 ] = z;
  5887. this.array[ index + 3 ] = w;
  5888. return this;
  5889. }
  5890. onUpload( callback ) {
  5891. this.onUploadCallback = callback;
  5892. return this;
  5893. }
  5894. clone() {
  5895. return new this.constructor( this.array, this.itemSize ).copy( this );
  5896. }
  5897. toJSON() {
  5898. const data = {
  5899. itemSize: this.itemSize,
  5900. type: this.array.constructor.name,
  5901. array: Array.from( this.array ),
  5902. normalized: this.normalized
  5903. };
  5904. if ( this.name !== '' ) data.name = this.name;
  5905. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  5906. if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange;
  5907. return data;
  5908. }
  5909. // @deprecated
  5910. copyColorsArray() {
  5911. console.error( 'THREE.BufferAttribute: copyColorsArray() was removed in r144.' );
  5912. }
  5913. copyVector2sArray() {
  5914. console.error( 'THREE.BufferAttribute: copyVector2sArray() was removed in r144.' );
  5915. }
  5916. copyVector3sArray() {
  5917. console.error( 'THREE.BufferAttribute: copyVector3sArray() was removed in r144.' );
  5918. }
  5919. copyVector4sArray() {
  5920. console.error( 'THREE.BufferAttribute: copyVector4sArray() was removed in r144.' );
  5921. }
  5922. }
  5923. //
  5924. class Int8BufferAttribute extends BufferAttribute {
  5925. constructor( array, itemSize, normalized ) {
  5926. super( new Int8Array( array ), itemSize, normalized );
  5927. }
  5928. }
  5929. class Uint8BufferAttribute extends BufferAttribute {
  5930. constructor( array, itemSize, normalized ) {
  5931. super( new Uint8Array( array ), itemSize, normalized );
  5932. }
  5933. }
  5934. class Uint8ClampedBufferAttribute extends BufferAttribute {
  5935. constructor( array, itemSize, normalized ) {
  5936. super( new Uint8ClampedArray( array ), itemSize, normalized );
  5937. }
  5938. }
  5939. class Int16BufferAttribute extends BufferAttribute {
  5940. constructor( array, itemSize, normalized ) {
  5941. super( new Int16Array( array ), itemSize, normalized );
  5942. }
  5943. }
  5944. class Uint16BufferAttribute extends BufferAttribute {
  5945. constructor( array, itemSize, normalized ) {
  5946. super( new Uint16Array( array ), itemSize, normalized );
  5947. }
  5948. }
  5949. class Int32BufferAttribute extends BufferAttribute {
  5950. constructor( array, itemSize, normalized ) {
  5951. super( new Int32Array( array ), itemSize, normalized );
  5952. }
  5953. }
  5954. class Uint32BufferAttribute extends BufferAttribute {
  5955. constructor( array, itemSize, normalized ) {
  5956. super( new Uint32Array( array ), itemSize, normalized );
  5957. }
  5958. }
  5959. class Float16BufferAttribute extends BufferAttribute {
  5960. constructor( array, itemSize, normalized ) {
  5961. super( new Uint16Array( array ), itemSize, normalized );
  5962. this.isFloat16BufferAttribute = true;
  5963. }
  5964. getX( index ) {
  5965. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  5966. if ( this.normalized ) x = denormalize( x, this.array );
  5967. return x;
  5968. }
  5969. setX( index, x ) {
  5970. if ( this.normalized ) x = normalize( x, this.array );
  5971. this.array[ index * this.itemSize ] = toHalfFloat( x );
  5972. return this;
  5973. }
  5974. getY( index ) {
  5975. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  5976. if ( this.normalized ) y = denormalize( y, this.array );
  5977. return y;
  5978. }
  5979. setY( index, y ) {
  5980. if ( this.normalized ) y = normalize( y, this.array );
  5981. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  5982. return this;
  5983. }
  5984. getZ( index ) {
  5985. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  5986. if ( this.normalized ) z = denormalize( z, this.array );
  5987. return z;
  5988. }
  5989. setZ( index, z ) {
  5990. if ( this.normalized ) z = normalize( z, this.array );
  5991. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  5992. return this;
  5993. }
  5994. getW( index ) {
  5995. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  5996. if ( this.normalized ) w = denormalize( w, this.array );
  5997. return w;
  5998. }
  5999. setW( index, w ) {
  6000. if ( this.normalized ) w = normalize( w, this.array );
  6001. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  6002. return this;
  6003. }
  6004. setXY( index, x, y ) {
  6005. index *= this.itemSize;
  6006. if ( this.normalized ) {
  6007. x = normalize( x, this.array );
  6008. y = normalize( y, this.array );
  6009. }
  6010. this.array[ index + 0 ] = toHalfFloat( x );
  6011. this.array[ index + 1 ] = toHalfFloat( y );
  6012. return this;
  6013. }
  6014. setXYZ( index, x, y, z ) {
  6015. index *= this.itemSize;
  6016. if ( this.normalized ) {
  6017. x = normalize( x, this.array );
  6018. y = normalize( y, this.array );
  6019. z = normalize( z, this.array );
  6020. }
  6021. this.array[ index + 0 ] = toHalfFloat( x );
  6022. this.array[ index + 1 ] = toHalfFloat( y );
  6023. this.array[ index + 2 ] = toHalfFloat( z );
  6024. return this;
  6025. }
  6026. setXYZW( index, x, y, z, w ) {
  6027. index *= this.itemSize;
  6028. if ( this.normalized ) {
  6029. x = normalize( x, this.array );
  6030. y = normalize( y, this.array );
  6031. z = normalize( z, this.array );
  6032. w = normalize( w, this.array );
  6033. }
  6034. this.array[ index + 0 ] = toHalfFloat( x );
  6035. this.array[ index + 1 ] = toHalfFloat( y );
  6036. this.array[ index + 2 ] = toHalfFloat( z );
  6037. this.array[ index + 3 ] = toHalfFloat( w );
  6038. return this;
  6039. }
  6040. }
  6041. class Float32BufferAttribute extends BufferAttribute {
  6042. constructor( array, itemSize, normalized ) {
  6043. super( new Float32Array( array ), itemSize, normalized );
  6044. }
  6045. }
  6046. class Float64BufferAttribute extends BufferAttribute {
  6047. constructor( array, itemSize, normalized ) {
  6048. super( new Float64Array( array ), itemSize, normalized );
  6049. }
  6050. }
  6051. let _id$1 = 0;
  6052. const _m1 = /*@__PURE__*/ new Matrix4();
  6053. const _obj = /*@__PURE__*/ new Object3D();
  6054. const _offset = /*@__PURE__*/ new Vector3();
  6055. const _box$1 = /*@__PURE__*/ new Box3();
  6056. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  6057. const _vector$8 = /*@__PURE__*/ new Vector3();
  6058. class BufferGeometry extends EventDispatcher {
  6059. constructor() {
  6060. super();
  6061. this.isBufferGeometry = true;
  6062. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  6063. this.uuid = generateUUID();
  6064. this.name = '';
  6065. this.type = 'BufferGeometry';
  6066. this.index = null;
  6067. this.attributes = {};
  6068. this.morphAttributes = {};
  6069. this.morphTargetsRelative = false;
  6070. this.groups = [];
  6071. this.boundingBox = null;
  6072. this.boundingSphere = null;
  6073. this.drawRange = { start: 0, count: Infinity };
  6074. this.userData = {};
  6075. }
  6076. getIndex() {
  6077. return this.index;
  6078. }
  6079. setIndex( index ) {
  6080. if ( Array.isArray( index ) ) {
  6081. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  6082. } else {
  6083. this.index = index;
  6084. }
  6085. return this;
  6086. }
  6087. getAttribute( name ) {
  6088. return this.attributes[ name ];
  6089. }
  6090. setAttribute( name, attribute ) {
  6091. this.attributes[ name ] = attribute;
  6092. return this;
  6093. }
  6094. deleteAttribute( name ) {
  6095. delete this.attributes[ name ];
  6096. return this;
  6097. }
  6098. hasAttribute( name ) {
  6099. return this.attributes[ name ] !== undefined;
  6100. }
  6101. addGroup( start, count, materialIndex = 0 ) {
  6102. this.groups.push( {
  6103. start: start,
  6104. count: count,
  6105. materialIndex: materialIndex
  6106. } );
  6107. }
  6108. clearGroups() {
  6109. this.groups = [];
  6110. }
  6111. setDrawRange( start, count ) {
  6112. this.drawRange.start = start;
  6113. this.drawRange.count = count;
  6114. }
  6115. applyMatrix4( matrix ) {
  6116. const position = this.attributes.position;
  6117. if ( position !== undefined ) {
  6118. position.applyMatrix4( matrix );
  6119. position.needsUpdate = true;
  6120. }
  6121. const normal = this.attributes.normal;
  6122. if ( normal !== undefined ) {
  6123. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  6124. normal.applyNormalMatrix( normalMatrix );
  6125. normal.needsUpdate = true;
  6126. }
  6127. const tangent = this.attributes.tangent;
  6128. if ( tangent !== undefined ) {
  6129. tangent.transformDirection( matrix );
  6130. tangent.needsUpdate = true;
  6131. }
  6132. if ( this.boundingBox !== null ) {
  6133. this.computeBoundingBox();
  6134. }
  6135. if ( this.boundingSphere !== null ) {
  6136. this.computeBoundingSphere();
  6137. }
  6138. return this;
  6139. }
  6140. applyQuaternion( q ) {
  6141. _m1.makeRotationFromQuaternion( q );
  6142. this.applyMatrix4( _m1 );
  6143. return this;
  6144. }
  6145. rotateX( angle ) {
  6146. // rotate geometry around world x-axis
  6147. _m1.makeRotationX( angle );
  6148. this.applyMatrix4( _m1 );
  6149. return this;
  6150. }
  6151. rotateY( angle ) {
  6152. // rotate geometry around world y-axis
  6153. _m1.makeRotationY( angle );
  6154. this.applyMatrix4( _m1 );
  6155. return this;
  6156. }
  6157. rotateZ( angle ) {
  6158. // rotate geometry around world z-axis
  6159. _m1.makeRotationZ( angle );
  6160. this.applyMatrix4( _m1 );
  6161. return this;
  6162. }
  6163. translate( x, y, z ) {
  6164. // translate geometry
  6165. _m1.makeTranslation( x, y, z );
  6166. this.applyMatrix4( _m1 );
  6167. return this;
  6168. }
  6169. scale( x, y, z ) {
  6170. // scale geometry
  6171. _m1.makeScale( x, y, z );
  6172. this.applyMatrix4( _m1 );
  6173. return this;
  6174. }
  6175. lookAt( vector ) {
  6176. _obj.lookAt( vector );
  6177. _obj.updateMatrix();
  6178. this.applyMatrix4( _obj.matrix );
  6179. return this;
  6180. }
  6181. center() {
  6182. this.computeBoundingBox();
  6183. this.boundingBox.getCenter( _offset ).negate();
  6184. this.translate( _offset.x, _offset.y, _offset.z );
  6185. return this;
  6186. }
  6187. setFromPoints( points ) {
  6188. const position = [];
  6189. for ( let i = 0, l = points.length; i < l; i ++ ) {
  6190. const point = points[ i ];
  6191. position.push( point.x, point.y, point.z || 0 );
  6192. }
  6193. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  6194. return this;
  6195. }
  6196. computeBoundingBox() {
  6197. if ( this.boundingBox === null ) {
  6198. this.boundingBox = new Box3();
  6199. }
  6200. const position = this.attributes.position;
  6201. const morphAttributesPosition = this.morphAttributes.position;
  6202. if ( position && position.isGLBufferAttribute ) {
  6203. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  6204. this.boundingBox.set(
  6205. new Vector3( - Infinity, - Infinity, - Infinity ),
  6206. new Vector3( + Infinity, + Infinity, + Infinity )
  6207. );
  6208. return;
  6209. }
  6210. if ( position !== undefined ) {
  6211. this.boundingBox.setFromBufferAttribute( position );
  6212. // process morph attributes if present
  6213. if ( morphAttributesPosition ) {
  6214. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6215. const morphAttribute = morphAttributesPosition[ i ];
  6216. _box$1.setFromBufferAttribute( morphAttribute );
  6217. if ( this.morphTargetsRelative ) {
  6218. _vector$8.addVectors( this.boundingBox.min, _box$1.min );
  6219. this.boundingBox.expandByPoint( _vector$8 );
  6220. _vector$8.addVectors( this.boundingBox.max, _box$1.max );
  6221. this.boundingBox.expandByPoint( _vector$8 );
  6222. } else {
  6223. this.boundingBox.expandByPoint( _box$1.min );
  6224. this.boundingBox.expandByPoint( _box$1.max );
  6225. }
  6226. }
  6227. }
  6228. } else {
  6229. this.boundingBox.makeEmpty();
  6230. }
  6231. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6232. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6233. }
  6234. }
  6235. computeBoundingSphere() {
  6236. if ( this.boundingSphere === null ) {
  6237. this.boundingSphere = new Sphere();
  6238. }
  6239. const position = this.attributes.position;
  6240. const morphAttributesPosition = this.morphAttributes.position;
  6241. if ( position && position.isGLBufferAttribute ) {
  6242. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  6243. this.boundingSphere.set( new Vector3(), Infinity );
  6244. return;
  6245. }
  6246. if ( position ) {
  6247. // first, find the center of the bounding sphere
  6248. const center = this.boundingSphere.center;
  6249. _box$1.setFromBufferAttribute( position );
  6250. // process morph attributes if present
  6251. if ( morphAttributesPosition ) {
  6252. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6253. const morphAttribute = morphAttributesPosition[ i ];
  6254. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6255. if ( this.morphTargetsRelative ) {
  6256. _vector$8.addVectors( _box$1.min, _boxMorphTargets.min );
  6257. _box$1.expandByPoint( _vector$8 );
  6258. _vector$8.addVectors( _box$1.max, _boxMorphTargets.max );
  6259. _box$1.expandByPoint( _vector$8 );
  6260. } else {
  6261. _box$1.expandByPoint( _boxMorphTargets.min );
  6262. _box$1.expandByPoint( _boxMorphTargets.max );
  6263. }
  6264. }
  6265. }
  6266. _box$1.getCenter( center );
  6267. // second, try to find a boundingSphere with a radius smaller than the
  6268. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6269. let maxRadiusSq = 0;
  6270. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6271. _vector$8.fromBufferAttribute( position, i );
  6272. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6273. }
  6274. // process morph attributes if present
  6275. if ( morphAttributesPosition ) {
  6276. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6277. const morphAttribute = morphAttributesPosition[ i ];
  6278. const morphTargetsRelative = this.morphTargetsRelative;
  6279. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6280. _vector$8.fromBufferAttribute( morphAttribute, j );
  6281. if ( morphTargetsRelative ) {
  6282. _offset.fromBufferAttribute( position, j );
  6283. _vector$8.add( _offset );
  6284. }
  6285. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6286. }
  6287. }
  6288. }
  6289. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6290. if ( isNaN( this.boundingSphere.radius ) ) {
  6291. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6292. }
  6293. }
  6294. }
  6295. computeTangents() {
  6296. const index = this.index;
  6297. const attributes = this.attributes;
  6298. // based on http://www.terathon.com/code/tangent.html
  6299. // (per vertex tangents)
  6300. if ( index === null ||
  6301. attributes.position === undefined ||
  6302. attributes.normal === undefined ||
  6303. attributes.uv === undefined ) {
  6304. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6305. return;
  6306. }
  6307. const indices = index.array;
  6308. const positions = attributes.position.array;
  6309. const normals = attributes.normal.array;
  6310. const uvs = attributes.uv.array;
  6311. const nVertices = positions.length / 3;
  6312. if ( this.hasAttribute( 'tangent' ) === false ) {
  6313. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  6314. }
  6315. const tangents = this.getAttribute( 'tangent' ).array;
  6316. const tan1 = [], tan2 = [];
  6317. for ( let i = 0; i < nVertices; i ++ ) {
  6318. tan1[ i ] = new Vector3();
  6319. tan2[ i ] = new Vector3();
  6320. }
  6321. const vA = new Vector3(),
  6322. vB = new Vector3(),
  6323. vC = new Vector3(),
  6324. uvA = new Vector2(),
  6325. uvB = new Vector2(),
  6326. uvC = new Vector2(),
  6327. sdir = new Vector3(),
  6328. tdir = new Vector3();
  6329. function handleTriangle( a, b, c ) {
  6330. vA.fromArray( positions, a * 3 );
  6331. vB.fromArray( positions, b * 3 );
  6332. vC.fromArray( positions, c * 3 );
  6333. uvA.fromArray( uvs, a * 2 );
  6334. uvB.fromArray( uvs, b * 2 );
  6335. uvC.fromArray( uvs, c * 2 );
  6336. vB.sub( vA );
  6337. vC.sub( vA );
  6338. uvB.sub( uvA );
  6339. uvC.sub( uvA );
  6340. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6341. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6342. if ( ! isFinite( r ) ) return;
  6343. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6344. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6345. tan1[ a ].add( sdir );
  6346. tan1[ b ].add( sdir );
  6347. tan1[ c ].add( sdir );
  6348. tan2[ a ].add( tdir );
  6349. tan2[ b ].add( tdir );
  6350. tan2[ c ].add( tdir );
  6351. }
  6352. let groups = this.groups;
  6353. if ( groups.length === 0 ) {
  6354. groups = [ {
  6355. start: 0,
  6356. count: indices.length
  6357. } ];
  6358. }
  6359. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6360. const group = groups[ i ];
  6361. const start = group.start;
  6362. const count = group.count;
  6363. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6364. handleTriangle(
  6365. indices[ j + 0 ],
  6366. indices[ j + 1 ],
  6367. indices[ j + 2 ]
  6368. );
  6369. }
  6370. }
  6371. const tmp = new Vector3(), tmp2 = new Vector3();
  6372. const n = new Vector3(), n2 = new Vector3();
  6373. function handleVertex( v ) {
  6374. n.fromArray( normals, v * 3 );
  6375. n2.copy( n );
  6376. const t = tan1[ v ];
  6377. // Gram-Schmidt orthogonalize
  6378. tmp.copy( t );
  6379. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6380. // Calculate handedness
  6381. tmp2.crossVectors( n2, t );
  6382. const test = tmp2.dot( tan2[ v ] );
  6383. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6384. tangents[ v * 4 ] = tmp.x;
  6385. tangents[ v * 4 + 1 ] = tmp.y;
  6386. tangents[ v * 4 + 2 ] = tmp.z;
  6387. tangents[ v * 4 + 3 ] = w;
  6388. }
  6389. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6390. const group = groups[ i ];
  6391. const start = group.start;
  6392. const count = group.count;
  6393. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6394. handleVertex( indices[ j + 0 ] );
  6395. handleVertex( indices[ j + 1 ] );
  6396. handleVertex( indices[ j + 2 ] );
  6397. }
  6398. }
  6399. }
  6400. computeVertexNormals() {
  6401. const index = this.index;
  6402. const positionAttribute = this.getAttribute( 'position' );
  6403. if ( positionAttribute !== undefined ) {
  6404. let normalAttribute = this.getAttribute( 'normal' );
  6405. if ( normalAttribute === undefined ) {
  6406. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6407. this.setAttribute( 'normal', normalAttribute );
  6408. } else {
  6409. // reset existing normals to zero
  6410. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6411. normalAttribute.setXYZ( i, 0, 0, 0 );
  6412. }
  6413. }
  6414. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6415. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6416. const cb = new Vector3(), ab = new Vector3();
  6417. // indexed elements
  6418. if ( index ) {
  6419. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6420. const vA = index.getX( i + 0 );
  6421. const vB = index.getX( i + 1 );
  6422. const vC = index.getX( i + 2 );
  6423. pA.fromBufferAttribute( positionAttribute, vA );
  6424. pB.fromBufferAttribute( positionAttribute, vB );
  6425. pC.fromBufferAttribute( positionAttribute, vC );
  6426. cb.subVectors( pC, pB );
  6427. ab.subVectors( pA, pB );
  6428. cb.cross( ab );
  6429. nA.fromBufferAttribute( normalAttribute, vA );
  6430. nB.fromBufferAttribute( normalAttribute, vB );
  6431. nC.fromBufferAttribute( normalAttribute, vC );
  6432. nA.add( cb );
  6433. nB.add( cb );
  6434. nC.add( cb );
  6435. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6436. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6437. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6438. }
  6439. } else {
  6440. // non-indexed elements (unconnected triangle soup)
  6441. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6442. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6443. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6444. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6445. cb.subVectors( pC, pB );
  6446. ab.subVectors( pA, pB );
  6447. cb.cross( ab );
  6448. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6449. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6450. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6451. }
  6452. }
  6453. this.normalizeNormals();
  6454. normalAttribute.needsUpdate = true;
  6455. }
  6456. }
  6457. // @deprecated since r144
  6458. merge() {
  6459. console.error( 'THREE.BufferGeometry.merge() has been removed. Use THREE.BufferGeometryUtils.mergeBufferGeometries() instead.' );
  6460. return this;
  6461. }
  6462. normalizeNormals() {
  6463. const normals = this.attributes.normal;
  6464. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6465. _vector$8.fromBufferAttribute( normals, i );
  6466. _vector$8.normalize();
  6467. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6468. }
  6469. }
  6470. toNonIndexed() {
  6471. function convertBufferAttribute( attribute, indices ) {
  6472. const array = attribute.array;
  6473. const itemSize = attribute.itemSize;
  6474. const normalized = attribute.normalized;
  6475. const array2 = new array.constructor( indices.length * itemSize );
  6476. let index = 0, index2 = 0;
  6477. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6478. if ( attribute.isInterleavedBufferAttribute ) {
  6479. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6480. } else {
  6481. index = indices[ i ] * itemSize;
  6482. }
  6483. for ( let j = 0; j < itemSize; j ++ ) {
  6484. array2[ index2 ++ ] = array[ index ++ ];
  6485. }
  6486. }
  6487. return new BufferAttribute( array2, itemSize, normalized );
  6488. }
  6489. //
  6490. if ( this.index === null ) {
  6491. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6492. return this;
  6493. }
  6494. const geometry2 = new BufferGeometry();
  6495. const indices = this.index.array;
  6496. const attributes = this.attributes;
  6497. // attributes
  6498. for ( const name in attributes ) {
  6499. const attribute = attributes[ name ];
  6500. const newAttribute = convertBufferAttribute( attribute, indices );
  6501. geometry2.setAttribute( name, newAttribute );
  6502. }
  6503. // morph attributes
  6504. const morphAttributes = this.morphAttributes;
  6505. for ( const name in morphAttributes ) {
  6506. const morphArray = [];
  6507. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6508. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6509. const attribute = morphAttribute[ i ];
  6510. const newAttribute = convertBufferAttribute( attribute, indices );
  6511. morphArray.push( newAttribute );
  6512. }
  6513. geometry2.morphAttributes[ name ] = morphArray;
  6514. }
  6515. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6516. // groups
  6517. const groups = this.groups;
  6518. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6519. const group = groups[ i ];
  6520. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6521. }
  6522. return geometry2;
  6523. }
  6524. toJSON() {
  6525. const data = {
  6526. metadata: {
  6527. version: 4.5,
  6528. type: 'BufferGeometry',
  6529. generator: 'BufferGeometry.toJSON'
  6530. }
  6531. };
  6532. // standard BufferGeometry serialization
  6533. data.uuid = this.uuid;
  6534. data.type = this.type;
  6535. if ( this.name !== '' ) data.name = this.name;
  6536. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6537. if ( this.parameters !== undefined ) {
  6538. const parameters = this.parameters;
  6539. for ( const key in parameters ) {
  6540. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6541. }
  6542. return data;
  6543. }
  6544. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6545. data.data = { attributes: {} };
  6546. const index = this.index;
  6547. if ( index !== null ) {
  6548. data.data.index = {
  6549. type: index.array.constructor.name,
  6550. array: Array.prototype.slice.call( index.array )
  6551. };
  6552. }
  6553. const attributes = this.attributes;
  6554. for ( const key in attributes ) {
  6555. const attribute = attributes[ key ];
  6556. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6557. }
  6558. const morphAttributes = {};
  6559. let hasMorphAttributes = false;
  6560. for ( const key in this.morphAttributes ) {
  6561. const attributeArray = this.morphAttributes[ key ];
  6562. const array = [];
  6563. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6564. const attribute = attributeArray[ i ];
  6565. array.push( attribute.toJSON( data.data ) );
  6566. }
  6567. if ( array.length > 0 ) {
  6568. morphAttributes[ key ] = array;
  6569. hasMorphAttributes = true;
  6570. }
  6571. }
  6572. if ( hasMorphAttributes ) {
  6573. data.data.morphAttributes = morphAttributes;
  6574. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6575. }
  6576. const groups = this.groups;
  6577. if ( groups.length > 0 ) {
  6578. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6579. }
  6580. const boundingSphere = this.boundingSphere;
  6581. if ( boundingSphere !== null ) {
  6582. data.data.boundingSphere = {
  6583. center: boundingSphere.center.toArray(),
  6584. radius: boundingSphere.radius
  6585. };
  6586. }
  6587. return data;
  6588. }
  6589. clone() {
  6590. return new this.constructor().copy( this );
  6591. }
  6592. copy( source ) {
  6593. // reset
  6594. this.index = null;
  6595. this.attributes = {};
  6596. this.morphAttributes = {};
  6597. this.groups = [];
  6598. this.boundingBox = null;
  6599. this.boundingSphere = null;
  6600. // used for storing cloned, shared data
  6601. const data = {};
  6602. // name
  6603. this.name = source.name;
  6604. // index
  6605. const index = source.index;
  6606. if ( index !== null ) {
  6607. this.setIndex( index.clone( data ) );
  6608. }
  6609. // attributes
  6610. const attributes = source.attributes;
  6611. for ( const name in attributes ) {
  6612. const attribute = attributes[ name ];
  6613. this.setAttribute( name, attribute.clone( data ) );
  6614. }
  6615. // morph attributes
  6616. const morphAttributes = source.morphAttributes;
  6617. for ( const name in morphAttributes ) {
  6618. const array = [];
  6619. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6620. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6621. array.push( morphAttribute[ i ].clone( data ) );
  6622. }
  6623. this.morphAttributes[ name ] = array;
  6624. }
  6625. this.morphTargetsRelative = source.morphTargetsRelative;
  6626. // groups
  6627. const groups = source.groups;
  6628. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6629. const group = groups[ i ];
  6630. this.addGroup( group.start, group.count, group.materialIndex );
  6631. }
  6632. // bounding box
  6633. const boundingBox = source.boundingBox;
  6634. if ( boundingBox !== null ) {
  6635. this.boundingBox = boundingBox.clone();
  6636. }
  6637. // bounding sphere
  6638. const boundingSphere = source.boundingSphere;
  6639. if ( boundingSphere !== null ) {
  6640. this.boundingSphere = boundingSphere.clone();
  6641. }
  6642. // draw range
  6643. this.drawRange.start = source.drawRange.start;
  6644. this.drawRange.count = source.drawRange.count;
  6645. // user data
  6646. this.userData = source.userData;
  6647. return this;
  6648. }
  6649. dispose() {
  6650. this.dispatchEvent( { type: 'dispose' } );
  6651. }
  6652. }
  6653. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  6654. const _ray$2 = /*@__PURE__*/ new Ray();
  6655. const _sphere$3 = /*@__PURE__*/ new Sphere();
  6656. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  6657. const _vA$1 = /*@__PURE__*/ new Vector3();
  6658. const _vB$1 = /*@__PURE__*/ new Vector3();
  6659. const _vC$1 = /*@__PURE__*/ new Vector3();
  6660. const _tempA = /*@__PURE__*/ new Vector3();
  6661. const _morphA = /*@__PURE__*/ new Vector3();
  6662. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6663. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6664. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6665. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6666. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6667. class Mesh extends Object3D {
  6668. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6669. super();
  6670. this.isMesh = true;
  6671. this.type = 'Mesh';
  6672. this.geometry = geometry;
  6673. this.material = material;
  6674. this.updateMorphTargets();
  6675. }
  6676. copy( source, recursive ) {
  6677. super.copy( source, recursive );
  6678. if ( source.morphTargetInfluences !== undefined ) {
  6679. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6680. }
  6681. if ( source.morphTargetDictionary !== undefined ) {
  6682. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6683. }
  6684. this.material = source.material;
  6685. this.geometry = source.geometry;
  6686. return this;
  6687. }
  6688. updateMorphTargets() {
  6689. const geometry = this.geometry;
  6690. const morphAttributes = geometry.morphAttributes;
  6691. const keys = Object.keys( morphAttributes );
  6692. if ( keys.length > 0 ) {
  6693. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6694. if ( morphAttribute !== undefined ) {
  6695. this.morphTargetInfluences = [];
  6696. this.morphTargetDictionary = {};
  6697. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6698. const name = morphAttribute[ m ].name || String( m );
  6699. this.morphTargetInfluences.push( 0 );
  6700. this.morphTargetDictionary[ name ] = m;
  6701. }
  6702. }
  6703. }
  6704. }
  6705. getVertexPosition( index, target ) {
  6706. const geometry = this.geometry;
  6707. const position = geometry.attributes.position;
  6708. const morphPosition = geometry.morphAttributes.position;
  6709. const morphTargetsRelative = geometry.morphTargetsRelative;
  6710. target.fromBufferAttribute( position, index );
  6711. const morphInfluences = this.morphTargetInfluences;
  6712. if ( morphPosition && morphInfluences ) {
  6713. _morphA.set( 0, 0, 0 );
  6714. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6715. const influence = morphInfluences[ i ];
  6716. const morphAttribute = morphPosition[ i ];
  6717. if ( influence === 0 ) continue;
  6718. _tempA.fromBufferAttribute( morphAttribute, index );
  6719. if ( morphTargetsRelative ) {
  6720. _morphA.addScaledVector( _tempA, influence );
  6721. } else {
  6722. _morphA.addScaledVector( _tempA.sub( target ), influence );
  6723. }
  6724. }
  6725. target.add( _morphA );
  6726. }
  6727. if ( this.isSkinnedMesh ) {
  6728. this.boneTransform( index, target );
  6729. }
  6730. return target;
  6731. }
  6732. raycast( raycaster, intersects ) {
  6733. const geometry = this.geometry;
  6734. const material = this.material;
  6735. const matrixWorld = this.matrixWorld;
  6736. if ( material === undefined ) return;
  6737. // Checking boundingSphere distance to ray
  6738. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6739. _sphere$3.copy( geometry.boundingSphere );
  6740. _sphere$3.applyMatrix4( matrixWorld );
  6741. _ray$2.copy( raycaster.ray ).recast( raycaster.near );
  6742. if ( _sphere$3.containsPoint( _ray$2.origin ) === false ) {
  6743. if ( _ray$2.intersectSphere( _sphere$3, _sphereHitAt ) === null ) return;
  6744. if ( _ray$2.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  6745. }
  6746. //
  6747. _inverseMatrix$2.copy( matrixWorld ).invert();
  6748. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  6749. // Check boundingBox before continuing
  6750. if ( geometry.boundingBox !== null ) {
  6751. if ( _ray$2.intersectsBox( geometry.boundingBox ) === false ) return;
  6752. }
  6753. let intersection;
  6754. const index = geometry.index;
  6755. const position = geometry.attributes.position;
  6756. const uv = geometry.attributes.uv;
  6757. const uv2 = geometry.attributes.uv2;
  6758. const groups = geometry.groups;
  6759. const drawRange = geometry.drawRange;
  6760. if ( index !== null ) {
  6761. // indexed buffer geometry
  6762. if ( Array.isArray( material ) ) {
  6763. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6764. const group = groups[ i ];
  6765. const groupMaterial = material[ group.materialIndex ];
  6766. const start = Math.max( group.start, drawRange.start );
  6767. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6768. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6769. const a = index.getX( j );
  6770. const b = index.getX( j + 1 );
  6771. const c = index.getX( j + 2 );
  6772. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, uv, uv2, a, b, c );
  6773. if ( intersection ) {
  6774. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6775. intersection.face.materialIndex = group.materialIndex;
  6776. intersects.push( intersection );
  6777. }
  6778. }
  6779. }
  6780. } else {
  6781. const start = Math.max( 0, drawRange.start );
  6782. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6783. for ( let i = start, il = end; i < il; i += 3 ) {
  6784. const a = index.getX( i );
  6785. const b = index.getX( i + 1 );
  6786. const c = index.getX( i + 2 );
  6787. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, uv, uv2, a, b, c );
  6788. if ( intersection ) {
  6789. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6790. intersects.push( intersection );
  6791. }
  6792. }
  6793. }
  6794. } else if ( position !== undefined ) {
  6795. // non-indexed buffer geometry
  6796. if ( Array.isArray( material ) ) {
  6797. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6798. const group = groups[ i ];
  6799. const groupMaterial = material[ group.materialIndex ];
  6800. const start = Math.max( group.start, drawRange.start );
  6801. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6802. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6803. const a = j;
  6804. const b = j + 1;
  6805. const c = j + 2;
  6806. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, uv, uv2, a, b, c );
  6807. if ( intersection ) {
  6808. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6809. intersection.face.materialIndex = group.materialIndex;
  6810. intersects.push( intersection );
  6811. }
  6812. }
  6813. }
  6814. } else {
  6815. const start = Math.max( 0, drawRange.start );
  6816. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6817. for ( let i = start, il = end; i < il; i += 3 ) {
  6818. const a = i;
  6819. const b = i + 1;
  6820. const c = i + 2;
  6821. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, uv, uv2, a, b, c );
  6822. if ( intersection ) {
  6823. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  6824. intersects.push( intersection );
  6825. }
  6826. }
  6827. }
  6828. }
  6829. }
  6830. }
  6831. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  6832. let intersect;
  6833. if ( material.side === BackSide ) {
  6834. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  6835. } else {
  6836. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  6837. }
  6838. if ( intersect === null ) return null;
  6839. _intersectionPointWorld.copy( point );
  6840. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  6841. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  6842. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  6843. return {
  6844. distance: distance,
  6845. point: _intersectionPointWorld.clone(),
  6846. object: object
  6847. };
  6848. }
  6849. function checkBufferGeometryIntersection( object, material, raycaster, ray, uv, uv2, a, b, c ) {
  6850. object.getVertexPosition( a, _vA$1 );
  6851. object.getVertexPosition( b, _vB$1 );
  6852. object.getVertexPosition( c, _vC$1 );
  6853. const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  6854. if ( intersection ) {
  6855. if ( uv ) {
  6856. _uvA$1.fromBufferAttribute( uv, a );
  6857. _uvB$1.fromBufferAttribute( uv, b );
  6858. _uvC$1.fromBufferAttribute( uv, c );
  6859. intersection.uv = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6860. }
  6861. if ( uv2 ) {
  6862. _uvA$1.fromBufferAttribute( uv2, a );
  6863. _uvB$1.fromBufferAttribute( uv2, b );
  6864. _uvC$1.fromBufferAttribute( uv2, c );
  6865. intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6866. }
  6867. const face = {
  6868. a: a,
  6869. b: b,
  6870. c: c,
  6871. normal: new Vector3(),
  6872. materialIndex: 0
  6873. };
  6874. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  6875. intersection.face = face;
  6876. }
  6877. return intersection;
  6878. }
  6879. class BoxGeometry extends BufferGeometry {
  6880. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  6881. super();
  6882. this.type = 'BoxGeometry';
  6883. this.parameters = {
  6884. width: width,
  6885. height: height,
  6886. depth: depth,
  6887. widthSegments: widthSegments,
  6888. heightSegments: heightSegments,
  6889. depthSegments: depthSegments
  6890. };
  6891. const scope = this;
  6892. // segments
  6893. widthSegments = Math.floor( widthSegments );
  6894. heightSegments = Math.floor( heightSegments );
  6895. depthSegments = Math.floor( depthSegments );
  6896. // buffers
  6897. const indices = [];
  6898. const vertices = [];
  6899. const normals = [];
  6900. const uvs = [];
  6901. // helper variables
  6902. let numberOfVertices = 0;
  6903. let groupStart = 0;
  6904. // build each side of the box geometry
  6905. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  6906. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  6907. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  6908. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  6909. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  6910. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  6911. // build geometry
  6912. this.setIndex( indices );
  6913. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  6914. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  6915. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  6916. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  6917. const segmentWidth = width / gridX;
  6918. const segmentHeight = height / gridY;
  6919. const widthHalf = width / 2;
  6920. const heightHalf = height / 2;
  6921. const depthHalf = depth / 2;
  6922. const gridX1 = gridX + 1;
  6923. const gridY1 = gridY + 1;
  6924. let vertexCounter = 0;
  6925. let groupCount = 0;
  6926. const vector = new Vector3();
  6927. // generate vertices, normals and uvs
  6928. for ( let iy = 0; iy < gridY1; iy ++ ) {
  6929. const y = iy * segmentHeight - heightHalf;
  6930. for ( let ix = 0; ix < gridX1; ix ++ ) {
  6931. const x = ix * segmentWidth - widthHalf;
  6932. // set values to correct vector component
  6933. vector[ u ] = x * udir;
  6934. vector[ v ] = y * vdir;
  6935. vector[ w ] = depthHalf;
  6936. // now apply vector to vertex buffer
  6937. vertices.push( vector.x, vector.y, vector.z );
  6938. // set values to correct vector component
  6939. vector[ u ] = 0;
  6940. vector[ v ] = 0;
  6941. vector[ w ] = depth > 0 ? 1 : - 1;
  6942. // now apply vector to normal buffer
  6943. normals.push( vector.x, vector.y, vector.z );
  6944. // uvs
  6945. uvs.push( ix / gridX );
  6946. uvs.push( 1 - ( iy / gridY ) );
  6947. // counters
  6948. vertexCounter += 1;
  6949. }
  6950. }
  6951. // indices
  6952. // 1. you need three indices to draw a single face
  6953. // 2. a single segment consists of two faces
  6954. // 3. so we need to generate six (2*3) indices per segment
  6955. for ( let iy = 0; iy < gridY; iy ++ ) {
  6956. for ( let ix = 0; ix < gridX; ix ++ ) {
  6957. const a = numberOfVertices + ix + gridX1 * iy;
  6958. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  6959. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  6960. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  6961. // faces
  6962. indices.push( a, b, d );
  6963. indices.push( b, c, d );
  6964. // increase counter
  6965. groupCount += 6;
  6966. }
  6967. }
  6968. // add a group to the geometry. this will ensure multi material support
  6969. scope.addGroup( groupStart, groupCount, materialIndex );
  6970. // calculate new start value for groups
  6971. groupStart += groupCount;
  6972. // update total number of vertices
  6973. numberOfVertices += vertexCounter;
  6974. }
  6975. }
  6976. copy( source ) {
  6977. super.copy( source );
  6978. this.parameters = Object.assign( {}, source.parameters );
  6979. return this;
  6980. }
  6981. static fromJSON( data ) {
  6982. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  6983. }
  6984. }
  6985. /**
  6986. * Uniform Utilities
  6987. */
  6988. function cloneUniforms( src ) {
  6989. const dst = {};
  6990. for ( const u in src ) {
  6991. dst[ u ] = {};
  6992. for ( const p in src[ u ] ) {
  6993. const property = src[ u ][ p ];
  6994. if ( property && ( property.isColor ||
  6995. property.isMatrix3 || property.isMatrix4 ||
  6996. property.isVector2 || property.isVector3 || property.isVector4 ||
  6997. property.isTexture || property.isQuaternion ) ) {
  6998. dst[ u ][ p ] = property.clone();
  6999. } else if ( Array.isArray( property ) ) {
  7000. dst[ u ][ p ] = property.slice();
  7001. } else {
  7002. dst[ u ][ p ] = property;
  7003. }
  7004. }
  7005. }
  7006. return dst;
  7007. }
  7008. function mergeUniforms( uniforms ) {
  7009. const merged = {};
  7010. for ( let u = 0; u < uniforms.length; u ++ ) {
  7011. const tmp = cloneUniforms( uniforms[ u ] );
  7012. for ( const p in tmp ) {
  7013. merged[ p ] = tmp[ p ];
  7014. }
  7015. }
  7016. return merged;
  7017. }
  7018. function cloneUniformsGroups( src ) {
  7019. const dst = [];
  7020. for ( let u = 0; u < src.length; u ++ ) {
  7021. dst.push( src[ u ].clone() );
  7022. }
  7023. return dst;
  7024. }
  7025. function getUnlitUniformColorSpace( renderer ) {
  7026. if ( renderer.getRenderTarget() === null ) {
  7027. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  7028. return renderer.outputEncoding === sRGBEncoding ? SRGBColorSpace : LinearSRGBColorSpace;
  7029. }
  7030. return LinearSRGBColorSpace;
  7031. }
  7032. // Legacy
  7033. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  7034. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  7035. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  7036. class ShaderMaterial extends Material {
  7037. constructor( parameters ) {
  7038. super();
  7039. this.isShaderMaterial = true;
  7040. this.type = 'ShaderMaterial';
  7041. this.defines = {};
  7042. this.uniforms = {};
  7043. this.uniformsGroups = [];
  7044. this.vertexShader = default_vertex;
  7045. this.fragmentShader = default_fragment;
  7046. this.linewidth = 1;
  7047. this.wireframe = false;
  7048. this.wireframeLinewidth = 1;
  7049. this.fog = false; // set to use scene fog
  7050. this.lights = false; // set to use scene lights
  7051. this.clipping = false; // set to use user-defined clipping planes
  7052. this.extensions = {
  7053. derivatives: false, // set to use derivatives
  7054. fragDepth: false, // set to use fragment depth values
  7055. drawBuffers: false, // set to use draw buffers
  7056. shaderTextureLOD: false // set to use shader texture LOD
  7057. };
  7058. // When rendered geometry doesn't include these attributes but the material does,
  7059. // use these default values in WebGL. This avoids errors when buffer data is missing.
  7060. this.defaultAttributeValues = {
  7061. 'color': [ 1, 1, 1 ],
  7062. 'uv': [ 0, 0 ],
  7063. 'uv2': [ 0, 0 ]
  7064. };
  7065. this.index0AttributeName = undefined;
  7066. this.uniformsNeedUpdate = false;
  7067. this.glslVersion = null;
  7068. if ( parameters !== undefined ) {
  7069. this.setValues( parameters );
  7070. }
  7071. }
  7072. copy( source ) {
  7073. super.copy( source );
  7074. this.fragmentShader = source.fragmentShader;
  7075. this.vertexShader = source.vertexShader;
  7076. this.uniforms = cloneUniforms( source.uniforms );
  7077. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  7078. this.defines = Object.assign( {}, source.defines );
  7079. this.wireframe = source.wireframe;
  7080. this.wireframeLinewidth = source.wireframeLinewidth;
  7081. this.fog = source.fog;
  7082. this.lights = source.lights;
  7083. this.clipping = source.clipping;
  7084. this.extensions = Object.assign( {}, source.extensions );
  7085. this.glslVersion = source.glslVersion;
  7086. return this;
  7087. }
  7088. toJSON( meta ) {
  7089. const data = super.toJSON( meta );
  7090. data.glslVersion = this.glslVersion;
  7091. data.uniforms = {};
  7092. for ( const name in this.uniforms ) {
  7093. const uniform = this.uniforms[ name ];
  7094. const value = uniform.value;
  7095. if ( value && value.isTexture ) {
  7096. data.uniforms[ name ] = {
  7097. type: 't',
  7098. value: value.toJSON( meta ).uuid
  7099. };
  7100. } else if ( value && value.isColor ) {
  7101. data.uniforms[ name ] = {
  7102. type: 'c',
  7103. value: value.getHex()
  7104. };
  7105. } else if ( value && value.isVector2 ) {
  7106. data.uniforms[ name ] = {
  7107. type: 'v2',
  7108. value: value.toArray()
  7109. };
  7110. } else if ( value && value.isVector3 ) {
  7111. data.uniforms[ name ] = {
  7112. type: 'v3',
  7113. value: value.toArray()
  7114. };
  7115. } else if ( value && value.isVector4 ) {
  7116. data.uniforms[ name ] = {
  7117. type: 'v4',
  7118. value: value.toArray()
  7119. };
  7120. } else if ( value && value.isMatrix3 ) {
  7121. data.uniforms[ name ] = {
  7122. type: 'm3',
  7123. value: value.toArray()
  7124. };
  7125. } else if ( value && value.isMatrix4 ) {
  7126. data.uniforms[ name ] = {
  7127. type: 'm4',
  7128. value: value.toArray()
  7129. };
  7130. } else {
  7131. data.uniforms[ name ] = {
  7132. value: value
  7133. };
  7134. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  7135. }
  7136. }
  7137. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  7138. data.vertexShader = this.vertexShader;
  7139. data.fragmentShader = this.fragmentShader;
  7140. const extensions = {};
  7141. for ( const key in this.extensions ) {
  7142. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  7143. }
  7144. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  7145. return data;
  7146. }
  7147. }
  7148. class Camera extends Object3D {
  7149. constructor() {
  7150. super();
  7151. this.isCamera = true;
  7152. this.type = 'Camera';
  7153. this.matrixWorldInverse = new Matrix4();
  7154. this.projectionMatrix = new Matrix4();
  7155. this.projectionMatrixInverse = new Matrix4();
  7156. }
  7157. copy( source, recursive ) {
  7158. super.copy( source, recursive );
  7159. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  7160. this.projectionMatrix.copy( source.projectionMatrix );
  7161. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  7162. return this;
  7163. }
  7164. getWorldDirection( target ) {
  7165. this.updateWorldMatrix( true, false );
  7166. const e = this.matrixWorld.elements;
  7167. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  7168. }
  7169. updateMatrixWorld( force ) {
  7170. super.updateMatrixWorld( force );
  7171. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7172. }
  7173. updateWorldMatrix( updateParents, updateChildren ) {
  7174. super.updateWorldMatrix( updateParents, updateChildren );
  7175. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  7176. }
  7177. clone() {
  7178. return new this.constructor().copy( this );
  7179. }
  7180. }
  7181. class PerspectiveCamera extends Camera {
  7182. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  7183. super();
  7184. this.isPerspectiveCamera = true;
  7185. this.type = 'PerspectiveCamera';
  7186. this.fov = fov;
  7187. this.zoom = 1;
  7188. this.near = near;
  7189. this.far = far;
  7190. this.focus = 10;
  7191. this.aspect = aspect;
  7192. this.view = null;
  7193. this.filmGauge = 35; // width of the film (default in millimeters)
  7194. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  7195. this.updateProjectionMatrix();
  7196. }
  7197. copy( source, recursive ) {
  7198. super.copy( source, recursive );
  7199. this.fov = source.fov;
  7200. this.zoom = source.zoom;
  7201. this.near = source.near;
  7202. this.far = source.far;
  7203. this.focus = source.focus;
  7204. this.aspect = source.aspect;
  7205. this.view = source.view === null ? null : Object.assign( {}, source.view );
  7206. this.filmGauge = source.filmGauge;
  7207. this.filmOffset = source.filmOffset;
  7208. return this;
  7209. }
  7210. /**
  7211. * Sets the FOV by focal length in respect to the current .filmGauge.
  7212. *
  7213. * The default film gauge is 35, so that the focal length can be specified for
  7214. * a 35mm (full frame) camera.
  7215. *
  7216. * Values for focal length and film gauge must have the same unit.
  7217. */
  7218. setFocalLength( focalLength ) {
  7219. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  7220. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  7221. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  7222. this.updateProjectionMatrix();
  7223. }
  7224. /**
  7225. * Calculates the focal length from the current .fov and .filmGauge.
  7226. */
  7227. getFocalLength() {
  7228. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  7229. return 0.5 * this.getFilmHeight() / vExtentSlope;
  7230. }
  7231. getEffectiveFOV() {
  7232. return RAD2DEG * 2 * Math.atan(
  7233. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  7234. }
  7235. getFilmWidth() {
  7236. // film not completely covered in portrait format (aspect < 1)
  7237. return this.filmGauge * Math.min( this.aspect, 1 );
  7238. }
  7239. getFilmHeight() {
  7240. // film not completely covered in landscape format (aspect > 1)
  7241. return this.filmGauge / Math.max( this.aspect, 1 );
  7242. }
  7243. /**
  7244. * Sets an offset in a larger frustum. This is useful for multi-window or
  7245. * multi-monitor/multi-machine setups.
  7246. *
  7247. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  7248. * the monitors are in grid like this
  7249. *
  7250. * +---+---+---+
  7251. * | A | B | C |
  7252. * +---+---+---+
  7253. * | D | E | F |
  7254. * +---+---+---+
  7255. *
  7256. * then for each monitor you would call it like this
  7257. *
  7258. * const w = 1920;
  7259. * const h = 1080;
  7260. * const fullWidth = w * 3;
  7261. * const fullHeight = h * 2;
  7262. *
  7263. * --A--
  7264. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7265. * --B--
  7266. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7267. * --C--
  7268. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7269. * --D--
  7270. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7271. * --E--
  7272. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7273. * --F--
  7274. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7275. *
  7276. * Note there is no reason monitors have to be the same size or in a grid.
  7277. */
  7278. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7279. this.aspect = fullWidth / fullHeight;
  7280. if ( this.view === null ) {
  7281. this.view = {
  7282. enabled: true,
  7283. fullWidth: 1,
  7284. fullHeight: 1,
  7285. offsetX: 0,
  7286. offsetY: 0,
  7287. width: 1,
  7288. height: 1
  7289. };
  7290. }
  7291. this.view.enabled = true;
  7292. this.view.fullWidth = fullWidth;
  7293. this.view.fullHeight = fullHeight;
  7294. this.view.offsetX = x;
  7295. this.view.offsetY = y;
  7296. this.view.width = width;
  7297. this.view.height = height;
  7298. this.updateProjectionMatrix();
  7299. }
  7300. clearViewOffset() {
  7301. if ( this.view !== null ) {
  7302. this.view.enabled = false;
  7303. }
  7304. this.updateProjectionMatrix();
  7305. }
  7306. updateProjectionMatrix() {
  7307. const near = this.near;
  7308. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7309. let height = 2 * top;
  7310. let width = this.aspect * height;
  7311. let left = - 0.5 * width;
  7312. const view = this.view;
  7313. if ( this.view !== null && this.view.enabled ) {
  7314. const fullWidth = view.fullWidth,
  7315. fullHeight = view.fullHeight;
  7316. left += view.offsetX * width / fullWidth;
  7317. top -= view.offsetY * height / fullHeight;
  7318. width *= view.width / fullWidth;
  7319. height *= view.height / fullHeight;
  7320. }
  7321. const skew = this.filmOffset;
  7322. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7323. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  7324. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7325. }
  7326. toJSON( meta ) {
  7327. const data = super.toJSON( meta );
  7328. data.object.fov = this.fov;
  7329. data.object.zoom = this.zoom;
  7330. data.object.near = this.near;
  7331. data.object.far = this.far;
  7332. data.object.focus = this.focus;
  7333. data.object.aspect = this.aspect;
  7334. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7335. data.object.filmGauge = this.filmGauge;
  7336. data.object.filmOffset = this.filmOffset;
  7337. return data;
  7338. }
  7339. }
  7340. const fov = - 90; // negative fov is not an error
  7341. const aspect = 1;
  7342. class CubeCamera extends Object3D {
  7343. constructor( near, far, renderTarget ) {
  7344. super();
  7345. this.type = 'CubeCamera';
  7346. this.renderTarget = renderTarget;
  7347. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7348. cameraPX.layers = this.layers;
  7349. cameraPX.up.set( 0, 1, 0 );
  7350. cameraPX.lookAt( 1, 0, 0 );
  7351. this.add( cameraPX );
  7352. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7353. cameraNX.layers = this.layers;
  7354. cameraNX.up.set( 0, 1, 0 );
  7355. cameraNX.lookAt( - 1, 0, 0 );
  7356. this.add( cameraNX );
  7357. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7358. cameraPY.layers = this.layers;
  7359. cameraPY.up.set( 0, 0, - 1 );
  7360. cameraPY.lookAt( 0, 1, 0 );
  7361. this.add( cameraPY );
  7362. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7363. cameraNY.layers = this.layers;
  7364. cameraNY.up.set( 0, 0, 1 );
  7365. cameraNY.lookAt( 0, - 1, 0 );
  7366. this.add( cameraNY );
  7367. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7368. cameraPZ.layers = this.layers;
  7369. cameraPZ.up.set( 0, 1, 0 );
  7370. cameraPZ.lookAt( 0, 0, 1 );
  7371. this.add( cameraPZ );
  7372. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7373. cameraNZ.layers = this.layers;
  7374. cameraNZ.up.set( 0, 1, 0 );
  7375. cameraNZ.lookAt( 0, 0, - 1 );
  7376. this.add( cameraNZ );
  7377. }
  7378. update( renderer, scene ) {
  7379. if ( this.parent === null ) this.updateMatrixWorld();
  7380. const renderTarget = this.renderTarget;
  7381. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7382. const currentRenderTarget = renderer.getRenderTarget();
  7383. const currentToneMapping = renderer.toneMapping;
  7384. const currentXrEnabled = renderer.xr.enabled;
  7385. renderer.toneMapping = NoToneMapping;
  7386. renderer.xr.enabled = false;
  7387. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7388. renderTarget.texture.generateMipmaps = false;
  7389. renderer.setRenderTarget( renderTarget, 0 );
  7390. renderer.render( scene, cameraPX );
  7391. renderer.setRenderTarget( renderTarget, 1 );
  7392. renderer.render( scene, cameraNX );
  7393. renderer.setRenderTarget( renderTarget, 2 );
  7394. renderer.render( scene, cameraPY );
  7395. renderer.setRenderTarget( renderTarget, 3 );
  7396. renderer.render( scene, cameraNY );
  7397. renderer.setRenderTarget( renderTarget, 4 );
  7398. renderer.render( scene, cameraPZ );
  7399. renderTarget.texture.generateMipmaps = generateMipmaps;
  7400. renderer.setRenderTarget( renderTarget, 5 );
  7401. renderer.render( scene, cameraNZ );
  7402. renderer.setRenderTarget( currentRenderTarget );
  7403. renderer.toneMapping = currentToneMapping;
  7404. renderer.xr.enabled = currentXrEnabled;
  7405. renderTarget.texture.needsPMREMUpdate = true;
  7406. }
  7407. }
  7408. class CubeTexture extends Texture {
  7409. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  7410. images = images !== undefined ? images : [];
  7411. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7412. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7413. this.isCubeTexture = true;
  7414. this.flipY = false;
  7415. }
  7416. get images() {
  7417. return this.image;
  7418. }
  7419. set images( value ) {
  7420. this.image = value;
  7421. }
  7422. }
  7423. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7424. constructor( size = 1, options = {} ) {
  7425. super( size, size, options );
  7426. this.isWebGLCubeRenderTarget = true;
  7427. const image = { width: size, height: size, depth: 1 };
  7428. const images = [ image, image, image, image, image, image ];
  7429. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  7430. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7431. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7432. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7433. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7434. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7435. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7436. this.texture.isRenderTargetTexture = true;
  7437. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7438. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7439. }
  7440. fromEquirectangularTexture( renderer, texture ) {
  7441. this.texture.type = texture.type;
  7442. this.texture.encoding = texture.encoding;
  7443. this.texture.generateMipmaps = texture.generateMipmaps;
  7444. this.texture.minFilter = texture.minFilter;
  7445. this.texture.magFilter = texture.magFilter;
  7446. const shader = {
  7447. uniforms: {
  7448. tEquirect: { value: null },
  7449. },
  7450. vertexShader: /* glsl */`
  7451. varying vec3 vWorldDirection;
  7452. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7453. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7454. }
  7455. void main() {
  7456. vWorldDirection = transformDirection( position, modelMatrix );
  7457. #include <begin_vertex>
  7458. #include <project_vertex>
  7459. }
  7460. `,
  7461. fragmentShader: /* glsl */`
  7462. uniform sampler2D tEquirect;
  7463. varying vec3 vWorldDirection;
  7464. #include <common>
  7465. void main() {
  7466. vec3 direction = normalize( vWorldDirection );
  7467. vec2 sampleUV = equirectUv( direction );
  7468. gl_FragColor = texture2D( tEquirect, sampleUV );
  7469. }
  7470. `
  7471. };
  7472. const geometry = new BoxGeometry( 5, 5, 5 );
  7473. const material = new ShaderMaterial( {
  7474. name: 'CubemapFromEquirect',
  7475. uniforms: cloneUniforms( shader.uniforms ),
  7476. vertexShader: shader.vertexShader,
  7477. fragmentShader: shader.fragmentShader,
  7478. side: BackSide,
  7479. blending: NoBlending
  7480. } );
  7481. material.uniforms.tEquirect.value = texture;
  7482. const mesh = new Mesh( geometry, material );
  7483. const currentMinFilter = texture.minFilter;
  7484. // Avoid blurred poles
  7485. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7486. const camera = new CubeCamera( 1, 10, this );
  7487. camera.update( renderer, mesh );
  7488. texture.minFilter = currentMinFilter;
  7489. mesh.geometry.dispose();
  7490. mesh.material.dispose();
  7491. return this;
  7492. }
  7493. clear( renderer, color, depth, stencil ) {
  7494. const currentRenderTarget = renderer.getRenderTarget();
  7495. for ( let i = 0; i < 6; i ++ ) {
  7496. renderer.setRenderTarget( this, i );
  7497. renderer.clear( color, depth, stencil );
  7498. }
  7499. renderer.setRenderTarget( currentRenderTarget );
  7500. }
  7501. }
  7502. const _vector1 = /*@__PURE__*/ new Vector3();
  7503. const _vector2 = /*@__PURE__*/ new Vector3();
  7504. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  7505. class Plane {
  7506. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  7507. this.isPlane = true;
  7508. // normal is assumed to be normalized
  7509. this.normal = normal;
  7510. this.constant = constant;
  7511. }
  7512. set( normal, constant ) {
  7513. this.normal.copy( normal );
  7514. this.constant = constant;
  7515. return this;
  7516. }
  7517. setComponents( x, y, z, w ) {
  7518. this.normal.set( x, y, z );
  7519. this.constant = w;
  7520. return this;
  7521. }
  7522. setFromNormalAndCoplanarPoint( normal, point ) {
  7523. this.normal.copy( normal );
  7524. this.constant = - point.dot( this.normal );
  7525. return this;
  7526. }
  7527. setFromCoplanarPoints( a, b, c ) {
  7528. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  7529. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7530. this.setFromNormalAndCoplanarPoint( normal, a );
  7531. return this;
  7532. }
  7533. copy( plane ) {
  7534. this.normal.copy( plane.normal );
  7535. this.constant = plane.constant;
  7536. return this;
  7537. }
  7538. normalize() {
  7539. // Note: will lead to a divide by zero if the plane is invalid.
  7540. const inverseNormalLength = 1.0 / this.normal.length();
  7541. this.normal.multiplyScalar( inverseNormalLength );
  7542. this.constant *= inverseNormalLength;
  7543. return this;
  7544. }
  7545. negate() {
  7546. this.constant *= - 1;
  7547. this.normal.negate();
  7548. return this;
  7549. }
  7550. distanceToPoint( point ) {
  7551. return this.normal.dot( point ) + this.constant;
  7552. }
  7553. distanceToSphere( sphere ) {
  7554. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7555. }
  7556. projectPoint( point, target ) {
  7557. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  7558. }
  7559. intersectLine( line, target ) {
  7560. const direction = line.delta( _vector1 );
  7561. const denominator = this.normal.dot( direction );
  7562. if ( denominator === 0 ) {
  7563. // line is coplanar, return origin
  7564. if ( this.distanceToPoint( line.start ) === 0 ) {
  7565. return target.copy( line.start );
  7566. }
  7567. // Unsure if this is the correct method to handle this case.
  7568. return null;
  7569. }
  7570. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7571. if ( t < 0 || t > 1 ) {
  7572. return null;
  7573. }
  7574. return target.copy( line.start ).addScaledVector( direction, t );
  7575. }
  7576. intersectsLine( line ) {
  7577. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7578. const startSign = this.distanceToPoint( line.start );
  7579. const endSign = this.distanceToPoint( line.end );
  7580. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7581. }
  7582. intersectsBox( box ) {
  7583. return box.intersectsPlane( this );
  7584. }
  7585. intersectsSphere( sphere ) {
  7586. return sphere.intersectsPlane( this );
  7587. }
  7588. coplanarPoint( target ) {
  7589. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7590. }
  7591. applyMatrix4( matrix, optionalNormalMatrix ) {
  7592. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  7593. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  7594. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7595. this.constant = - referencePoint.dot( normal );
  7596. return this;
  7597. }
  7598. translate( offset ) {
  7599. this.constant -= offset.dot( this.normal );
  7600. return this;
  7601. }
  7602. equals( plane ) {
  7603. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7604. }
  7605. clone() {
  7606. return new this.constructor().copy( this );
  7607. }
  7608. }
  7609. const _sphere$2 = /*@__PURE__*/ new Sphere();
  7610. const _vector$7 = /*@__PURE__*/ new Vector3();
  7611. class Frustum {
  7612. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7613. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7614. }
  7615. set( p0, p1, p2, p3, p4, p5 ) {
  7616. const planes = this.planes;
  7617. planes[ 0 ].copy( p0 );
  7618. planes[ 1 ].copy( p1 );
  7619. planes[ 2 ].copy( p2 );
  7620. planes[ 3 ].copy( p3 );
  7621. planes[ 4 ].copy( p4 );
  7622. planes[ 5 ].copy( p5 );
  7623. return this;
  7624. }
  7625. copy( frustum ) {
  7626. const planes = this.planes;
  7627. for ( let i = 0; i < 6; i ++ ) {
  7628. planes[ i ].copy( frustum.planes[ i ] );
  7629. }
  7630. return this;
  7631. }
  7632. setFromProjectionMatrix( m ) {
  7633. const planes = this.planes;
  7634. const me = m.elements;
  7635. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7636. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7637. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7638. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7639. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7640. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7641. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7642. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7643. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7644. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7645. return this;
  7646. }
  7647. intersectsObject( object ) {
  7648. const geometry = object.geometry;
  7649. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7650. _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7651. return this.intersectsSphere( _sphere$2 );
  7652. }
  7653. intersectsSprite( sprite ) {
  7654. _sphere$2.center.set( 0, 0, 0 );
  7655. _sphere$2.radius = 0.7071067811865476;
  7656. _sphere$2.applyMatrix4( sprite.matrixWorld );
  7657. return this.intersectsSphere( _sphere$2 );
  7658. }
  7659. intersectsSphere( sphere ) {
  7660. const planes = this.planes;
  7661. const center = sphere.center;
  7662. const negRadius = - sphere.radius;
  7663. for ( let i = 0; i < 6; i ++ ) {
  7664. const distance = planes[ i ].distanceToPoint( center );
  7665. if ( distance < negRadius ) {
  7666. return false;
  7667. }
  7668. }
  7669. return true;
  7670. }
  7671. intersectsBox( box ) {
  7672. const planes = this.planes;
  7673. for ( let i = 0; i < 6; i ++ ) {
  7674. const plane = planes[ i ];
  7675. // corner at max distance
  7676. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7677. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7678. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7679. if ( plane.distanceToPoint( _vector$7 ) < 0 ) {
  7680. return false;
  7681. }
  7682. }
  7683. return true;
  7684. }
  7685. containsPoint( point ) {
  7686. const planes = this.planes;
  7687. for ( let i = 0; i < 6; i ++ ) {
  7688. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7689. return false;
  7690. }
  7691. }
  7692. return true;
  7693. }
  7694. clone() {
  7695. return new this.constructor().copy( this );
  7696. }
  7697. }
  7698. function WebGLAnimation() {
  7699. let context = null;
  7700. let isAnimating = false;
  7701. let animationLoop = null;
  7702. let requestId = null;
  7703. function onAnimationFrame( time, frame ) {
  7704. animationLoop( time, frame );
  7705. requestId = context.requestAnimationFrame( onAnimationFrame );
  7706. }
  7707. return {
  7708. start: function () {
  7709. if ( isAnimating === true ) return;
  7710. if ( animationLoop === null ) return;
  7711. requestId = context.requestAnimationFrame( onAnimationFrame );
  7712. isAnimating = true;
  7713. },
  7714. stop: function () {
  7715. context.cancelAnimationFrame( requestId );
  7716. isAnimating = false;
  7717. },
  7718. setAnimationLoop: function ( callback ) {
  7719. animationLoop = callback;
  7720. },
  7721. setContext: function ( value ) {
  7722. context = value;
  7723. }
  7724. };
  7725. }
  7726. function WebGLAttributes( gl, capabilities ) {
  7727. const isWebGL2 = capabilities.isWebGL2;
  7728. const buffers = new WeakMap();
  7729. function createBuffer( attribute, bufferType ) {
  7730. const array = attribute.array;
  7731. const usage = attribute.usage;
  7732. const buffer = gl.createBuffer();
  7733. gl.bindBuffer( bufferType, buffer );
  7734. gl.bufferData( bufferType, array, usage );
  7735. attribute.onUploadCallback();
  7736. let type;
  7737. if ( array instanceof Float32Array ) {
  7738. type = 5126;
  7739. } else if ( array instanceof Uint16Array ) {
  7740. if ( attribute.isFloat16BufferAttribute ) {
  7741. if ( isWebGL2 ) {
  7742. type = 5131;
  7743. } else {
  7744. throw new Error( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  7745. }
  7746. } else {
  7747. type = 5123;
  7748. }
  7749. } else if ( array instanceof Int16Array ) {
  7750. type = 5122;
  7751. } else if ( array instanceof Uint32Array ) {
  7752. type = 5125;
  7753. } else if ( array instanceof Int32Array ) {
  7754. type = 5124;
  7755. } else if ( array instanceof Int8Array ) {
  7756. type = 5120;
  7757. } else if ( array instanceof Uint8Array ) {
  7758. type = 5121;
  7759. } else if ( array instanceof Uint8ClampedArray ) {
  7760. type = 5121;
  7761. } else {
  7762. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  7763. }
  7764. return {
  7765. buffer: buffer,
  7766. type: type,
  7767. bytesPerElement: array.BYTES_PER_ELEMENT,
  7768. version: attribute.version
  7769. };
  7770. }
  7771. function updateBuffer( buffer, attribute, bufferType ) {
  7772. const array = attribute.array;
  7773. const updateRange = attribute.updateRange;
  7774. gl.bindBuffer( bufferType, buffer );
  7775. if ( updateRange.count === - 1 ) {
  7776. // Not using update ranges
  7777. gl.bufferSubData( bufferType, 0, array );
  7778. } else {
  7779. if ( isWebGL2 ) {
  7780. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7781. array, updateRange.offset, updateRange.count );
  7782. } else {
  7783. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7784. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  7785. }
  7786. updateRange.count = - 1; // reset range
  7787. }
  7788. attribute.onUploadCallback();
  7789. }
  7790. //
  7791. function get( attribute ) {
  7792. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7793. return buffers.get( attribute );
  7794. }
  7795. function remove( attribute ) {
  7796. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7797. const data = buffers.get( attribute );
  7798. if ( data ) {
  7799. gl.deleteBuffer( data.buffer );
  7800. buffers.delete( attribute );
  7801. }
  7802. }
  7803. function update( attribute, bufferType ) {
  7804. if ( attribute.isGLBufferAttribute ) {
  7805. const cached = buffers.get( attribute );
  7806. if ( ! cached || cached.version < attribute.version ) {
  7807. buffers.set( attribute, {
  7808. buffer: attribute.buffer,
  7809. type: attribute.type,
  7810. bytesPerElement: attribute.elementSize,
  7811. version: attribute.version
  7812. } );
  7813. }
  7814. return;
  7815. }
  7816. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7817. const data = buffers.get( attribute );
  7818. if ( data === undefined ) {
  7819. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  7820. } else if ( data.version < attribute.version ) {
  7821. updateBuffer( data.buffer, attribute, bufferType );
  7822. data.version = attribute.version;
  7823. }
  7824. }
  7825. return {
  7826. get: get,
  7827. remove: remove,
  7828. update: update
  7829. };
  7830. }
  7831. class PlaneGeometry extends BufferGeometry {
  7832. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  7833. super();
  7834. this.type = 'PlaneGeometry';
  7835. this.parameters = {
  7836. width: width,
  7837. height: height,
  7838. widthSegments: widthSegments,
  7839. heightSegments: heightSegments
  7840. };
  7841. const width_half = width / 2;
  7842. const height_half = height / 2;
  7843. const gridX = Math.floor( widthSegments );
  7844. const gridY = Math.floor( heightSegments );
  7845. const gridX1 = gridX + 1;
  7846. const gridY1 = gridY + 1;
  7847. const segment_width = width / gridX;
  7848. const segment_height = height / gridY;
  7849. //
  7850. const indices = [];
  7851. const vertices = [];
  7852. const normals = [];
  7853. const uvs = [];
  7854. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7855. const y = iy * segment_height - height_half;
  7856. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7857. const x = ix * segment_width - width_half;
  7858. vertices.push( x, - y, 0 );
  7859. normals.push( 0, 0, 1 );
  7860. uvs.push( ix / gridX );
  7861. uvs.push( 1 - ( iy / gridY ) );
  7862. }
  7863. }
  7864. for ( let iy = 0; iy < gridY; iy ++ ) {
  7865. for ( let ix = 0; ix < gridX; ix ++ ) {
  7866. const a = ix + gridX1 * iy;
  7867. const b = ix + gridX1 * ( iy + 1 );
  7868. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  7869. const d = ( ix + 1 ) + gridX1 * iy;
  7870. indices.push( a, b, d );
  7871. indices.push( b, c, d );
  7872. }
  7873. }
  7874. this.setIndex( indices );
  7875. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7876. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7877. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7878. }
  7879. copy( source ) {
  7880. super.copy( source );
  7881. this.parameters = Object.assign( {}, source.parameters );
  7882. return this;
  7883. }
  7884. static fromJSON( data ) {
  7885. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  7886. }
  7887. }
  7888. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7889. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7890. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  7891. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  7892. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif";
  7893. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7894. var begin_vertex = "vec3 transformed = vec3( position );";
  7895. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7896. var bsdfs = "vec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( V * D );\n}\n#ifdef USE_IRIDESCENCE\n\tvec3 BRDF_GGX_Iridescence( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 f0, const in float f90, const in float iridescence, const in vec3 iridescenceFresnel, const in float roughness ) {\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = mix( F_Schlick( f0, f90, dotVH ), iridescenceFresnel, iridescence );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif";
  7897. 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";
  7898. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = dFdx( surf_pos.xyz );\n\t\tvec3 vSigmaY = dFdy( surf_pos.xyz );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif";
  7899. 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";
  7900. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7901. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7902. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7903. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7904. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7905. 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";
  7906. 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";
  7907. var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal;\n#endif\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nmat3 transposeMat3( const in mat3 m ) {\n\tmat3 tmp;\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\n\treturn tmp;\n}\nfloat luminance( const in vec3 rgb ) {\n\tconst vec3 weights = vec3( 0.2126729, 0.7151522, 0.0721750 );\n\treturn dot( weights, rgb );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}";
  7908. 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";
  7909. 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";
  7910. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7911. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7912. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7913. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7914. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7915. var encodings_pars_fragment = "vec4 LinearToLinear( in vec4 value ) {\n\treturn value;\n}\nvec4 LinearTosRGB( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}";
  7916. 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";
  7917. 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";
  7918. 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";
  7919. 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";
  7920. 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";
  7921. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  7922. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  7923. 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";
  7924. 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";
  7925. 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}";
  7926. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  7927. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7928. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  7929. 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";
  7930. 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";
  7931. var envmap_physical_pars_fragment = "#if defined( USE_ENVMAP )\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#if defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n#endif";
  7932. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7933. 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";
  7934. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7935. 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";
  7936. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nvec3 dxy = max( abs( dFdx( geometryNormal ) ), abs( dFdy( geometryNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULARINTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vUv ).a;\n\t\t#endif\n\t\t#ifdef USE_SPECULARCOLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vUv ).rgb;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vUv ).a;\n\t#endif\n#endif";
  7937. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat roughness;\n\tvec3 specularColor;\n\tfloat specularF90;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n};\nvec3 clearcoatSpecular = vec3( 0.0 );\nvec3 sheenSpecular = vec3( 0.0 );\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;\n\treturn fab;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometry.normal;\n\t\tvec3 viewDir = geometry.viewDir;\n\t\tvec3 position = geometry.position;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometry.clearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecular += ccIrradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.clearcoatNormal, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * BRDF_Sheen( directLight.direction, geometry.viewDir, geometry.normal, material.sheenColor, material.sheenRoughness );\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX_Iridescence( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness );\n\t#else\n\t\treflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometry.viewDir, geometry.normal, material.specularColor, material.specularF90, material.roughness );\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecular += clearcoatRadiance * EnvironmentBRDF( geometry.clearcoatNormal, geometry.viewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecular += irradiance * material.sheenColor * IBLSheenBRDF( geometry.normal, geometry.viewDir, material.sheenRoughness );\n\t#endif\n\tvec3 singleScattering = vec3( 0.0 );\n\tvec3 multiScattering = vec3( 0.0 );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );\n\t#else\n\t\tcomputeMultiscattering( geometry.normal, geometry.viewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );\n\t#endif\n\tvec3 totalScattering = singleScattering + multiScattering;\n\tvec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );\n\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  7938. 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";
  7939. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometry.normal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tradiance += getIBLRadiance( geometry.viewDir, geometry.normal, material.roughness );\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometry.viewDir, geometry.clearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
  7940. 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";
  7941. 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";
  7942. 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";
  7943. 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";
  7944. 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";
  7945. var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = vec4( mix( pow( sampledDiffuseColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), sampledDiffuseColor.rgb * 0.0773993808, vec3( lessThanEqual( sampledDiffuseColor.rgb, vec3( 0.04045 ) ) ) ), sampledDiffuseColor.w );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif";
  7946. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7947. var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
  7948. var map_particle_pars_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\tuniform mat3 uvTransform;\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7949. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7950. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7951. 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";
  7952. 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";
  7953. 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";
  7954. 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";
  7955. var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\t#ifdef USE_TANGENT\n\t\tvec3 tangent = normalize( vTangent );\n\t\tvec3 bitangent = normalize( vBitangent );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\ttangent = tangent * faceDirection;\n\t\t\tbitangent = bitangent * faceDirection;\n\t\t#endif\n\t\t#if defined( TANGENTSPACE_NORMALMAP ) || defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tmat3 vTBN = mat3( tangent, bitangent, normal );\n\t\t#endif\n\t#endif\n#endif\nvec3 geometryNormal = normal;";
  7956. var normal_fragment_maps = "#ifdef OBJECTSPACE_NORMALMAP\n\tnormal = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( TANGENTSPACE_NORMALMAP )\n\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\t#ifdef USE_TANGENT\n\t\tnormal = normalize( vTBN * mapN );\n\t#else\n\t\tnormal = perturbNormal2Arb( - vViewPosition, normal, mapN, faceDirection );\n\t#endif\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif";
  7957. 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";
  7958. 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";
  7959. 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";
  7960. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( TANGENTSPACE_NORMALMAP ) || defined ( USE_CLEARCOAT_NORMALMAP ) )\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec3 mapN, float faceDirection ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : faceDirection * inversesqrt( det );\n\t\treturn normalize( T * ( mapN.x * scale ) + B * ( mapN.y * scale ) + N * mapN.z );\n\t}\n#endif";
  7961. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7962. var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\t#ifdef USE_TANGENT\n\t\tclearcoatNormal = normalize( vTBN * clearcoatMapN );\n\t#else\n\t\tclearcoatNormal = perturbNormal2Arb( - vViewPosition, clearcoatNormal, clearcoatMapN, faceDirection );\n\t#endif\n#endif";
  7963. var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif";
  7964. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  7965. var output_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha + 0.1;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  7966. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nvec2 packDepthToRG( in highp float v ) {\n\treturn packDepthToRGBA( v ).yx;\n}\nfloat unpackRGToDepth( const in highp vec2 v ) {\n\treturn unpackRGBAToDepth( vec4( v.xy, 0.0, 0.0 ) );\n}\nvec4 pack2HalfToRGBA( vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n\treturn linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\n}";
  7967. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7968. 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;";
  7969. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7970. 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";
  7971. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7972. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7973. 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";
  7974. 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";
  7975. 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";
  7976. 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}";
  7977. 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";
  7978. 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";
  7979. 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";
  7980. 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";
  7981. var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
  7982. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7983. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7984. var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
  7985. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmission = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmission.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmission.rgb, material.transmission );\n#endif";
  7986. 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, vec2 fullSize, 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\t\n\t\tvec2 lodFudge = pow( 1.95, lod ) / fullSize;\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\tvec2 fullSize = vec2( textureSize( sampler, 0 ) );\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), fullSize, floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), fullSize, 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 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn radiance;\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance * radiance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\trefractionCoords += 1.0;\n\t\trefractionCoords /= 2.0;\n\t\tvec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\tvec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a );\n\t}\n#endif";
  7987. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7988. var uv_pars_vertex = "#ifdef USE_UV\n\t#ifdef UVS_VERTEX_ONLY\n\t\tvec2 vUv;\n\t#else\n\t\tvarying vec2 vUv;\n\t#endif\n\tuniform mat3 uvTransform;\n#endif";
  7989. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7990. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7991. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n\tuniform mat3 uv2Transform;\n#endif";
  7992. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7993. 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";
  7994. 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}";
  7995. const fragment$h = "uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7996. 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}";
  7997. const fragment$g = "#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7998. 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}";
  7999. const fragment$f = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  8000. 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}";
  8001. const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#endif\n}";
  8002. 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}";
  8003. const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = packDepthToRGBA( dist );\n}";
  8004. 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}";
  8005. const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  8006. const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  8007. const fragment$b = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8008. const vertex$a = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  8009. const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8010. const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8011. const fragment$9 = "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_lambert_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_lambert_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8012. 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}";
  8013. const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8014. const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  8015. const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( TANGENTSPACE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}";
  8016. const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8017. const fragment$6 = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8018. const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}";
  8019. const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULARINTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n\t#ifdef USE_SPECULARCOLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEENCOLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEENROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <bsdfs>\n#include <iridescence_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <iridescence_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecular;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometry.clearcoatNormal, geometry.viewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + clearcoatSpecular * material.clearcoat;\n\t#endif\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8020. const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  8021. const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  8022. const vertex$3 = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";
  8023. const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  8024. 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}";
  8025. const fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <logdepthbuf_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8026. 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}";
  8027. const fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <output_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  8028. const ShaderChunk = {
  8029. alphamap_fragment: alphamap_fragment,
  8030. alphamap_pars_fragment: alphamap_pars_fragment,
  8031. alphatest_fragment: alphatest_fragment,
  8032. alphatest_pars_fragment: alphatest_pars_fragment,
  8033. aomap_fragment: aomap_fragment,
  8034. aomap_pars_fragment: aomap_pars_fragment,
  8035. begin_vertex: begin_vertex,
  8036. beginnormal_vertex: beginnormal_vertex,
  8037. bsdfs: bsdfs,
  8038. iridescence_fragment: iridescence_fragment,
  8039. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8040. clipping_planes_fragment: clipping_planes_fragment,
  8041. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8042. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8043. clipping_planes_vertex: clipping_planes_vertex,
  8044. color_fragment: color_fragment,
  8045. color_pars_fragment: color_pars_fragment,
  8046. color_pars_vertex: color_pars_vertex,
  8047. color_vertex: color_vertex,
  8048. common: common,
  8049. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8050. defaultnormal_vertex: defaultnormal_vertex,
  8051. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8052. displacementmap_vertex: displacementmap_vertex,
  8053. emissivemap_fragment: emissivemap_fragment,
  8054. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8055. encodings_fragment: encodings_fragment,
  8056. encodings_pars_fragment: encodings_pars_fragment,
  8057. envmap_fragment: envmap_fragment,
  8058. envmap_common_pars_fragment: envmap_common_pars_fragment,
  8059. envmap_pars_fragment: envmap_pars_fragment,
  8060. envmap_pars_vertex: envmap_pars_vertex,
  8061. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  8062. envmap_vertex: envmap_vertex,
  8063. fog_vertex: fog_vertex,
  8064. fog_pars_vertex: fog_pars_vertex,
  8065. fog_fragment: fog_fragment,
  8066. fog_pars_fragment: fog_pars_fragment,
  8067. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8068. lightmap_fragment: lightmap_fragment,
  8069. lightmap_pars_fragment: lightmap_pars_fragment,
  8070. lights_lambert_fragment: lights_lambert_fragment,
  8071. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  8072. lights_pars_begin: lights_pars_begin,
  8073. lights_toon_fragment: lights_toon_fragment,
  8074. lights_toon_pars_fragment: lights_toon_pars_fragment,
  8075. lights_phong_fragment: lights_phong_fragment,
  8076. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8077. lights_physical_fragment: lights_physical_fragment,
  8078. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8079. lights_fragment_begin: lights_fragment_begin,
  8080. lights_fragment_maps: lights_fragment_maps,
  8081. lights_fragment_end: lights_fragment_end,
  8082. logdepthbuf_fragment: logdepthbuf_fragment,
  8083. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8084. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8085. logdepthbuf_vertex: logdepthbuf_vertex,
  8086. map_fragment: map_fragment,
  8087. map_pars_fragment: map_pars_fragment,
  8088. map_particle_fragment: map_particle_fragment,
  8089. map_particle_pars_fragment: map_particle_pars_fragment,
  8090. metalnessmap_fragment: metalnessmap_fragment,
  8091. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8092. morphcolor_vertex: morphcolor_vertex,
  8093. morphnormal_vertex: morphnormal_vertex,
  8094. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8095. morphtarget_vertex: morphtarget_vertex,
  8096. normal_fragment_begin: normal_fragment_begin,
  8097. normal_fragment_maps: normal_fragment_maps,
  8098. normal_pars_fragment: normal_pars_fragment,
  8099. normal_pars_vertex: normal_pars_vertex,
  8100. normal_vertex: normal_vertex,
  8101. normalmap_pars_fragment: normalmap_pars_fragment,
  8102. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  8103. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  8104. clearcoat_pars_fragment: clearcoat_pars_fragment,
  8105. iridescence_pars_fragment: iridescence_pars_fragment,
  8106. output_fragment: output_fragment,
  8107. packing: packing,
  8108. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8109. project_vertex: project_vertex,
  8110. dithering_fragment: dithering_fragment,
  8111. dithering_pars_fragment: dithering_pars_fragment,
  8112. roughnessmap_fragment: roughnessmap_fragment,
  8113. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8114. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8115. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8116. shadowmap_vertex: shadowmap_vertex,
  8117. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8118. skinbase_vertex: skinbase_vertex,
  8119. skinning_pars_vertex: skinning_pars_vertex,
  8120. skinning_vertex: skinning_vertex,
  8121. skinnormal_vertex: skinnormal_vertex,
  8122. specularmap_fragment: specularmap_fragment,
  8123. specularmap_pars_fragment: specularmap_pars_fragment,
  8124. tonemapping_fragment: tonemapping_fragment,
  8125. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8126. transmission_fragment: transmission_fragment,
  8127. transmission_pars_fragment: transmission_pars_fragment,
  8128. uv_pars_fragment: uv_pars_fragment,
  8129. uv_pars_vertex: uv_pars_vertex,
  8130. uv_vertex: uv_vertex,
  8131. uv2_pars_fragment: uv2_pars_fragment,
  8132. uv2_pars_vertex: uv2_pars_vertex,
  8133. uv2_vertex: uv2_vertex,
  8134. worldpos_vertex: worldpos_vertex,
  8135. background_vert: vertex$h,
  8136. background_frag: fragment$h,
  8137. backgroundCube_vert: vertex$g,
  8138. backgroundCube_frag: fragment$g,
  8139. cube_vert: vertex$f,
  8140. cube_frag: fragment$f,
  8141. depth_vert: vertex$e,
  8142. depth_frag: fragment$e,
  8143. distanceRGBA_vert: vertex$d,
  8144. distanceRGBA_frag: fragment$d,
  8145. equirect_vert: vertex$c,
  8146. equirect_frag: fragment$c,
  8147. linedashed_vert: vertex$b,
  8148. linedashed_frag: fragment$b,
  8149. meshbasic_vert: vertex$a,
  8150. meshbasic_frag: fragment$a,
  8151. meshlambert_vert: vertex$9,
  8152. meshlambert_frag: fragment$9,
  8153. meshmatcap_vert: vertex$8,
  8154. meshmatcap_frag: fragment$8,
  8155. meshnormal_vert: vertex$7,
  8156. meshnormal_frag: fragment$7,
  8157. meshphong_vert: vertex$6,
  8158. meshphong_frag: fragment$6,
  8159. meshphysical_vert: vertex$5,
  8160. meshphysical_frag: fragment$5,
  8161. meshtoon_vert: vertex$4,
  8162. meshtoon_frag: fragment$4,
  8163. points_vert: vertex$3,
  8164. points_frag: fragment$3,
  8165. shadow_vert: vertex$2,
  8166. shadow_frag: fragment$2,
  8167. sprite_vert: vertex$1,
  8168. sprite_frag: fragment$1
  8169. };
  8170. /**
  8171. * Uniforms library for shared webgl shaders
  8172. */
  8173. const UniformsLib = {
  8174. common: {
  8175. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8176. opacity: { value: 1.0 },
  8177. map: { value: null },
  8178. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  8179. uv2Transform: { value: /*@__PURE__*/ new Matrix3() },
  8180. alphaMap: { value: null },
  8181. alphaTest: { value: 0 }
  8182. },
  8183. specularmap: {
  8184. specularMap: { value: null },
  8185. },
  8186. envmap: {
  8187. envMap: { value: null },
  8188. flipEnvMap: { value: - 1 },
  8189. reflectivity: { value: 1.0 }, // basic, lambert, phong
  8190. ior: { value: 1.5 }, // physical
  8191. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  8192. },
  8193. aomap: {
  8194. aoMap: { value: null },
  8195. aoMapIntensity: { value: 1 }
  8196. },
  8197. lightmap: {
  8198. lightMap: { value: null },
  8199. lightMapIntensity: { value: 1 }
  8200. },
  8201. emissivemap: {
  8202. emissiveMap: { value: null }
  8203. },
  8204. bumpmap: {
  8205. bumpMap: { value: null },
  8206. bumpScale: { value: 1 }
  8207. },
  8208. normalmap: {
  8209. normalMap: { value: null },
  8210. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  8211. },
  8212. displacementmap: {
  8213. displacementMap: { value: null },
  8214. displacementScale: { value: 1 },
  8215. displacementBias: { value: 0 }
  8216. },
  8217. roughnessmap: {
  8218. roughnessMap: { value: null }
  8219. },
  8220. metalnessmap: {
  8221. metalnessMap: { value: null }
  8222. },
  8223. gradientmap: {
  8224. gradientMap: { value: null }
  8225. },
  8226. fog: {
  8227. fogDensity: { value: 0.00025 },
  8228. fogNear: { value: 1 },
  8229. fogFar: { value: 2000 },
  8230. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  8231. },
  8232. lights: {
  8233. ambientLightColor: { value: [] },
  8234. lightProbe: { value: [] },
  8235. directionalLights: { value: [], properties: {
  8236. direction: {},
  8237. color: {}
  8238. } },
  8239. directionalLightShadows: { value: [], properties: {
  8240. shadowBias: {},
  8241. shadowNormalBias: {},
  8242. shadowRadius: {},
  8243. shadowMapSize: {}
  8244. } },
  8245. directionalShadowMap: { value: [] },
  8246. directionalShadowMatrix: { value: [] },
  8247. spotLights: { value: [], properties: {
  8248. color: {},
  8249. position: {},
  8250. direction: {},
  8251. distance: {},
  8252. coneCos: {},
  8253. penumbraCos: {},
  8254. decay: {}
  8255. } },
  8256. spotLightShadows: { value: [], properties: {
  8257. shadowBias: {},
  8258. shadowNormalBias: {},
  8259. shadowRadius: {},
  8260. shadowMapSize: {}
  8261. } },
  8262. spotLightMap: { value: [] },
  8263. spotShadowMap: { value: [] },
  8264. spotLightMatrix: { value: [] },
  8265. pointLights: { value: [], properties: {
  8266. color: {},
  8267. position: {},
  8268. decay: {},
  8269. distance: {}
  8270. } },
  8271. pointLightShadows: { value: [], properties: {
  8272. shadowBias: {},
  8273. shadowNormalBias: {},
  8274. shadowRadius: {},
  8275. shadowMapSize: {},
  8276. shadowCameraNear: {},
  8277. shadowCameraFar: {}
  8278. } },
  8279. pointShadowMap: { value: [] },
  8280. pointShadowMatrix: { value: [] },
  8281. hemisphereLights: { value: [], properties: {
  8282. direction: {},
  8283. skyColor: {},
  8284. groundColor: {}
  8285. } },
  8286. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8287. rectAreaLights: { value: [], properties: {
  8288. color: {},
  8289. position: {},
  8290. width: {},
  8291. height: {}
  8292. } },
  8293. ltc_1: { value: null },
  8294. ltc_2: { value: null }
  8295. },
  8296. points: {
  8297. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8298. opacity: { value: 1.0 },
  8299. size: { value: 1.0 },
  8300. scale: { value: 1.0 },
  8301. map: { value: null },
  8302. alphaMap: { value: null },
  8303. alphaTest: { value: 0 },
  8304. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8305. },
  8306. sprite: {
  8307. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8308. opacity: { value: 1.0 },
  8309. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  8310. rotation: { value: 0.0 },
  8311. map: { value: null },
  8312. alphaMap: { value: null },
  8313. alphaTest: { value: 0 },
  8314. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8315. }
  8316. };
  8317. const ShaderLib = {
  8318. basic: {
  8319. uniforms: /*@__PURE__*/ mergeUniforms( [
  8320. UniformsLib.common,
  8321. UniformsLib.specularmap,
  8322. UniformsLib.envmap,
  8323. UniformsLib.aomap,
  8324. UniformsLib.lightmap,
  8325. UniformsLib.fog
  8326. ] ),
  8327. vertexShader: ShaderChunk.meshbasic_vert,
  8328. fragmentShader: ShaderChunk.meshbasic_frag
  8329. },
  8330. lambert: {
  8331. uniforms: /*@__PURE__*/ mergeUniforms( [
  8332. UniformsLib.common,
  8333. UniformsLib.specularmap,
  8334. UniformsLib.envmap,
  8335. UniformsLib.aomap,
  8336. UniformsLib.lightmap,
  8337. UniformsLib.emissivemap,
  8338. UniformsLib.bumpmap,
  8339. UniformsLib.normalmap,
  8340. UniformsLib.displacementmap,
  8341. UniformsLib.fog,
  8342. UniformsLib.lights,
  8343. {
  8344. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8345. }
  8346. ] ),
  8347. vertexShader: ShaderChunk.meshlambert_vert,
  8348. fragmentShader: ShaderChunk.meshlambert_frag
  8349. },
  8350. phong: {
  8351. uniforms: /*@__PURE__*/ mergeUniforms( [
  8352. UniformsLib.common,
  8353. UniformsLib.specularmap,
  8354. UniformsLib.envmap,
  8355. UniformsLib.aomap,
  8356. UniformsLib.lightmap,
  8357. UniformsLib.emissivemap,
  8358. UniformsLib.bumpmap,
  8359. UniformsLib.normalmap,
  8360. UniformsLib.displacementmap,
  8361. UniformsLib.fog,
  8362. UniformsLib.lights,
  8363. {
  8364. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8365. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  8366. shininess: { value: 30 }
  8367. }
  8368. ] ),
  8369. vertexShader: ShaderChunk.meshphong_vert,
  8370. fragmentShader: ShaderChunk.meshphong_frag
  8371. },
  8372. standard: {
  8373. uniforms: /*@__PURE__*/ mergeUniforms( [
  8374. UniformsLib.common,
  8375. UniformsLib.envmap,
  8376. UniformsLib.aomap,
  8377. UniformsLib.lightmap,
  8378. UniformsLib.emissivemap,
  8379. UniformsLib.bumpmap,
  8380. UniformsLib.normalmap,
  8381. UniformsLib.displacementmap,
  8382. UniformsLib.roughnessmap,
  8383. UniformsLib.metalnessmap,
  8384. UniformsLib.fog,
  8385. UniformsLib.lights,
  8386. {
  8387. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8388. roughness: { value: 1.0 },
  8389. metalness: { value: 0.0 },
  8390. envMapIntensity: { value: 1 } // temporary
  8391. }
  8392. ] ),
  8393. vertexShader: ShaderChunk.meshphysical_vert,
  8394. fragmentShader: ShaderChunk.meshphysical_frag
  8395. },
  8396. toon: {
  8397. uniforms: /*@__PURE__*/ mergeUniforms( [
  8398. UniformsLib.common,
  8399. UniformsLib.aomap,
  8400. UniformsLib.lightmap,
  8401. UniformsLib.emissivemap,
  8402. UniformsLib.bumpmap,
  8403. UniformsLib.normalmap,
  8404. UniformsLib.displacementmap,
  8405. UniformsLib.gradientmap,
  8406. UniformsLib.fog,
  8407. UniformsLib.lights,
  8408. {
  8409. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8410. }
  8411. ] ),
  8412. vertexShader: ShaderChunk.meshtoon_vert,
  8413. fragmentShader: ShaderChunk.meshtoon_frag
  8414. },
  8415. matcap: {
  8416. uniforms: /*@__PURE__*/ mergeUniforms( [
  8417. UniformsLib.common,
  8418. UniformsLib.bumpmap,
  8419. UniformsLib.normalmap,
  8420. UniformsLib.displacementmap,
  8421. UniformsLib.fog,
  8422. {
  8423. matcap: { value: null }
  8424. }
  8425. ] ),
  8426. vertexShader: ShaderChunk.meshmatcap_vert,
  8427. fragmentShader: ShaderChunk.meshmatcap_frag
  8428. },
  8429. points: {
  8430. uniforms: /*@__PURE__*/ mergeUniforms( [
  8431. UniformsLib.points,
  8432. UniformsLib.fog
  8433. ] ),
  8434. vertexShader: ShaderChunk.points_vert,
  8435. fragmentShader: ShaderChunk.points_frag
  8436. },
  8437. dashed: {
  8438. uniforms: /*@__PURE__*/ mergeUniforms( [
  8439. UniformsLib.common,
  8440. UniformsLib.fog,
  8441. {
  8442. scale: { value: 1 },
  8443. dashSize: { value: 1 },
  8444. totalSize: { value: 2 }
  8445. }
  8446. ] ),
  8447. vertexShader: ShaderChunk.linedashed_vert,
  8448. fragmentShader: ShaderChunk.linedashed_frag
  8449. },
  8450. depth: {
  8451. uniforms: /*@__PURE__*/ mergeUniforms( [
  8452. UniformsLib.common,
  8453. UniformsLib.displacementmap
  8454. ] ),
  8455. vertexShader: ShaderChunk.depth_vert,
  8456. fragmentShader: ShaderChunk.depth_frag
  8457. },
  8458. normal: {
  8459. uniforms: /*@__PURE__*/ mergeUniforms( [
  8460. UniformsLib.common,
  8461. UniformsLib.bumpmap,
  8462. UniformsLib.normalmap,
  8463. UniformsLib.displacementmap,
  8464. {
  8465. opacity: { value: 1.0 }
  8466. }
  8467. ] ),
  8468. vertexShader: ShaderChunk.meshnormal_vert,
  8469. fragmentShader: ShaderChunk.meshnormal_frag
  8470. },
  8471. sprite: {
  8472. uniforms: /*@__PURE__*/ mergeUniforms( [
  8473. UniformsLib.sprite,
  8474. UniformsLib.fog
  8475. ] ),
  8476. vertexShader: ShaderChunk.sprite_vert,
  8477. fragmentShader: ShaderChunk.sprite_frag
  8478. },
  8479. background: {
  8480. uniforms: {
  8481. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  8482. t2D: { value: null },
  8483. backgroundIntensity: { value: 1 }
  8484. },
  8485. vertexShader: ShaderChunk.background_vert,
  8486. fragmentShader: ShaderChunk.background_frag
  8487. },
  8488. backgroundCube: {
  8489. uniforms: {
  8490. envMap: { value: null },
  8491. flipEnvMap: { value: - 1 },
  8492. backgroundBlurriness: { value: 0 },
  8493. backgroundIntensity: { value: 1 }
  8494. },
  8495. vertexShader: ShaderChunk.backgroundCube_vert,
  8496. fragmentShader: ShaderChunk.backgroundCube_frag
  8497. },
  8498. cube: {
  8499. uniforms: {
  8500. tCube: { value: null },
  8501. tFlip: { value: - 1 },
  8502. opacity: { value: 1.0 }
  8503. },
  8504. vertexShader: ShaderChunk.cube_vert,
  8505. fragmentShader: ShaderChunk.cube_frag
  8506. },
  8507. equirect: {
  8508. uniforms: {
  8509. tEquirect: { value: null },
  8510. },
  8511. vertexShader: ShaderChunk.equirect_vert,
  8512. fragmentShader: ShaderChunk.equirect_frag
  8513. },
  8514. distanceRGBA: {
  8515. uniforms: /*@__PURE__*/ mergeUniforms( [
  8516. UniformsLib.common,
  8517. UniformsLib.displacementmap,
  8518. {
  8519. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  8520. nearDistance: { value: 1 },
  8521. farDistance: { value: 1000 }
  8522. }
  8523. ] ),
  8524. vertexShader: ShaderChunk.distanceRGBA_vert,
  8525. fragmentShader: ShaderChunk.distanceRGBA_frag
  8526. },
  8527. shadow: {
  8528. uniforms: /*@__PURE__*/ mergeUniforms( [
  8529. UniformsLib.lights,
  8530. UniformsLib.fog,
  8531. {
  8532. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  8533. opacity: { value: 1.0 }
  8534. },
  8535. ] ),
  8536. vertexShader: ShaderChunk.shadow_vert,
  8537. fragmentShader: ShaderChunk.shadow_frag
  8538. }
  8539. };
  8540. ShaderLib.physical = {
  8541. uniforms: /*@__PURE__*/ mergeUniforms( [
  8542. ShaderLib.standard.uniforms,
  8543. {
  8544. clearcoat: { value: 0 },
  8545. clearcoatMap: { value: null },
  8546. clearcoatRoughness: { value: 0 },
  8547. clearcoatRoughnessMap: { value: null },
  8548. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  8549. clearcoatNormalMap: { value: null },
  8550. iridescence: { value: 0 },
  8551. iridescenceMap: { value: null },
  8552. iridescenceIOR: { value: 1.3 },
  8553. iridescenceThicknessMinimum: { value: 100 },
  8554. iridescenceThicknessMaximum: { value: 400 },
  8555. iridescenceThicknessMap: { value: null },
  8556. sheen: { value: 0 },
  8557. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8558. sheenColorMap: { value: null },
  8559. sheenRoughness: { value: 1 },
  8560. sheenRoughnessMap: { value: null },
  8561. transmission: { value: 0 },
  8562. transmissionMap: { value: null },
  8563. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  8564. transmissionSamplerMap: { value: null },
  8565. thickness: { value: 0 },
  8566. thicknessMap: { value: null },
  8567. attenuationDistance: { value: 0 },
  8568. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8569. specularIntensity: { value: 1 },
  8570. specularIntensityMap: { value: null },
  8571. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  8572. specularColorMap: { value: null },
  8573. }
  8574. ] ),
  8575. vertexShader: ShaderChunk.meshphysical_vert,
  8576. fragmentShader: ShaderChunk.meshphysical_frag
  8577. };
  8578. const _rgb = { r: 0, b: 0, g: 0 };
  8579. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  8580. const clearColor = new Color( 0x000000 );
  8581. let clearAlpha = alpha === true ? 0 : 1;
  8582. let planeMesh;
  8583. let boxMesh;
  8584. let currentBackground = null;
  8585. let currentBackgroundVersion = 0;
  8586. let currentTonemapping = null;
  8587. function render( renderList, scene ) {
  8588. let forceClear = false;
  8589. let background = scene.isScene === true ? scene.background : null;
  8590. if ( background && background.isTexture ) {
  8591. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  8592. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  8593. }
  8594. // Ignore background in AR
  8595. // TODO: Reconsider this.
  8596. const xr = renderer.xr;
  8597. const session = xr.getSession && xr.getSession();
  8598. if ( session && session.environmentBlendMode === 'additive' ) {
  8599. background = null;
  8600. }
  8601. if ( background === null ) {
  8602. setClear( clearColor, clearAlpha );
  8603. } else if ( background && background.isColor ) {
  8604. setClear( background, 1 );
  8605. forceClear = true;
  8606. }
  8607. if ( renderer.autoClear || forceClear ) {
  8608. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8609. }
  8610. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8611. if ( boxMesh === undefined ) {
  8612. boxMesh = new Mesh(
  8613. new BoxGeometry( 1, 1, 1 ),
  8614. new ShaderMaterial( {
  8615. name: 'BackgroundCubeMaterial',
  8616. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  8617. vertexShader: ShaderLib.backgroundCube.vertexShader,
  8618. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  8619. side: BackSide,
  8620. depthTest: false,
  8621. depthWrite: false,
  8622. fog: false
  8623. } )
  8624. );
  8625. boxMesh.geometry.deleteAttribute( 'normal' );
  8626. boxMesh.geometry.deleteAttribute( 'uv' );
  8627. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8628. this.matrixWorld.copyPosition( camera.matrixWorld );
  8629. };
  8630. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  8631. Object.defineProperty( boxMesh.material, 'envMap', {
  8632. get: function () {
  8633. return this.uniforms.envMap.value;
  8634. }
  8635. } );
  8636. objects.update( boxMesh );
  8637. }
  8638. boxMesh.material.uniforms.envMap.value = background;
  8639. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  8640. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  8641. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8642. boxMesh.material.toneMapped = ( background.encoding === sRGBEncoding ) ? false : true;
  8643. if ( currentBackground !== background ||
  8644. currentBackgroundVersion !== background.version ||
  8645. currentTonemapping !== renderer.toneMapping ) {
  8646. boxMesh.material.needsUpdate = true;
  8647. currentBackground = background;
  8648. currentBackgroundVersion = background.version;
  8649. currentTonemapping = renderer.toneMapping;
  8650. }
  8651. boxMesh.layers.enableAll();
  8652. // push to the pre-sorted opaque render list
  8653. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  8654. } else if ( background && background.isTexture ) {
  8655. if ( planeMesh === undefined ) {
  8656. planeMesh = new Mesh(
  8657. new PlaneGeometry( 2, 2 ),
  8658. new ShaderMaterial( {
  8659. name: 'BackgroundMaterial',
  8660. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  8661. vertexShader: ShaderLib.background.vertexShader,
  8662. fragmentShader: ShaderLib.background.fragmentShader,
  8663. side: FrontSide,
  8664. depthTest: false,
  8665. depthWrite: false,
  8666. fog: false
  8667. } )
  8668. );
  8669. planeMesh.geometry.deleteAttribute( 'normal' );
  8670. // add "map" material property so the renderer can evaluate it like for built-in materials
  8671. Object.defineProperty( planeMesh.material, 'map', {
  8672. get: function () {
  8673. return this.uniforms.t2D.value;
  8674. }
  8675. } );
  8676. objects.update( planeMesh );
  8677. }
  8678. planeMesh.material.uniforms.t2D.value = background;
  8679. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  8680. planeMesh.material.toneMapped = ( background.encoding === sRGBEncoding ) ? false : true;
  8681. if ( background.matrixAutoUpdate === true ) {
  8682. background.updateMatrix();
  8683. }
  8684. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  8685. if ( currentBackground !== background ||
  8686. currentBackgroundVersion !== background.version ||
  8687. currentTonemapping !== renderer.toneMapping ) {
  8688. planeMesh.material.needsUpdate = true;
  8689. currentBackground = background;
  8690. currentBackgroundVersion = background.version;
  8691. currentTonemapping = renderer.toneMapping;
  8692. }
  8693. planeMesh.layers.enableAll();
  8694. // push to the pre-sorted opaque render list
  8695. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  8696. }
  8697. }
  8698. function setClear( color, alpha ) {
  8699. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  8700. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  8701. }
  8702. return {
  8703. getClearColor: function () {
  8704. return clearColor;
  8705. },
  8706. setClearColor: function ( color, alpha = 1 ) {
  8707. clearColor.set( color );
  8708. clearAlpha = alpha;
  8709. setClear( clearColor, clearAlpha );
  8710. },
  8711. getClearAlpha: function () {
  8712. return clearAlpha;
  8713. },
  8714. setClearAlpha: function ( alpha ) {
  8715. clearAlpha = alpha;
  8716. setClear( clearColor, clearAlpha );
  8717. },
  8718. render: render
  8719. };
  8720. }
  8721. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  8722. const maxVertexAttributes = gl.getParameter( 34921 );
  8723. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  8724. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8725. const bindingStates = {};
  8726. const defaultState = createBindingState( null );
  8727. let currentState = defaultState;
  8728. let forceUpdate = false;
  8729. function setup( object, material, program, geometry, index ) {
  8730. let updateBuffers = false;
  8731. if ( vaoAvailable ) {
  8732. const state = getBindingState( geometry, program, material );
  8733. if ( currentState !== state ) {
  8734. currentState = state;
  8735. bindVertexArrayObject( currentState.object );
  8736. }
  8737. updateBuffers = needsUpdate( object, geometry, program, index );
  8738. if ( updateBuffers ) saveCache( object, geometry, program, index );
  8739. } else {
  8740. const wireframe = ( material.wireframe === true );
  8741. if ( currentState.geometry !== geometry.id ||
  8742. currentState.program !== program.id ||
  8743. currentState.wireframe !== wireframe ) {
  8744. currentState.geometry = geometry.id;
  8745. currentState.program = program.id;
  8746. currentState.wireframe = wireframe;
  8747. updateBuffers = true;
  8748. }
  8749. }
  8750. if ( index !== null ) {
  8751. attributes.update( index, 34963 );
  8752. }
  8753. if ( updateBuffers || forceUpdate ) {
  8754. forceUpdate = false;
  8755. setupVertexAttributes( object, material, program, geometry );
  8756. if ( index !== null ) {
  8757. gl.bindBuffer( 34963, attributes.get( index ).buffer );
  8758. }
  8759. }
  8760. }
  8761. function createVertexArrayObject() {
  8762. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  8763. return extension.createVertexArrayOES();
  8764. }
  8765. function bindVertexArrayObject( vao ) {
  8766. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  8767. return extension.bindVertexArrayOES( vao );
  8768. }
  8769. function deleteVertexArrayObject( vao ) {
  8770. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  8771. return extension.deleteVertexArrayOES( vao );
  8772. }
  8773. function getBindingState( geometry, program, material ) {
  8774. const wireframe = ( material.wireframe === true );
  8775. let programMap = bindingStates[ geometry.id ];
  8776. if ( programMap === undefined ) {
  8777. programMap = {};
  8778. bindingStates[ geometry.id ] = programMap;
  8779. }
  8780. let stateMap = programMap[ program.id ];
  8781. if ( stateMap === undefined ) {
  8782. stateMap = {};
  8783. programMap[ program.id ] = stateMap;
  8784. }
  8785. let state = stateMap[ wireframe ];
  8786. if ( state === undefined ) {
  8787. state = createBindingState( createVertexArrayObject() );
  8788. stateMap[ wireframe ] = state;
  8789. }
  8790. return state;
  8791. }
  8792. function createBindingState( vao ) {
  8793. const newAttributes = [];
  8794. const enabledAttributes = [];
  8795. const attributeDivisors = [];
  8796. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  8797. newAttributes[ i ] = 0;
  8798. enabledAttributes[ i ] = 0;
  8799. attributeDivisors[ i ] = 0;
  8800. }
  8801. return {
  8802. // for backward compatibility on non-VAO support browser
  8803. geometry: null,
  8804. program: null,
  8805. wireframe: false,
  8806. newAttributes: newAttributes,
  8807. enabledAttributes: enabledAttributes,
  8808. attributeDivisors: attributeDivisors,
  8809. object: vao,
  8810. attributes: {},
  8811. index: null
  8812. };
  8813. }
  8814. function needsUpdate( object, geometry, program, index ) {
  8815. const cachedAttributes = currentState.attributes;
  8816. const geometryAttributes = geometry.attributes;
  8817. let attributesNum = 0;
  8818. const programAttributes = program.getAttributes();
  8819. for ( const name in programAttributes ) {
  8820. const programAttribute = programAttributes[ name ];
  8821. if ( programAttribute.location >= 0 ) {
  8822. const cachedAttribute = cachedAttributes[ name ];
  8823. let geometryAttribute = geometryAttributes[ name ];
  8824. if ( geometryAttribute === undefined ) {
  8825. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8826. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8827. }
  8828. if ( cachedAttribute === undefined ) return true;
  8829. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  8830. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  8831. attributesNum ++;
  8832. }
  8833. }
  8834. if ( currentState.attributesNum !== attributesNum ) return true;
  8835. if ( currentState.index !== index ) return true;
  8836. return false;
  8837. }
  8838. function saveCache( object, geometry, program, index ) {
  8839. const cache = {};
  8840. const attributes = geometry.attributes;
  8841. let attributesNum = 0;
  8842. const programAttributes = program.getAttributes();
  8843. for ( const name in programAttributes ) {
  8844. const programAttribute = programAttributes[ name ];
  8845. if ( programAttribute.location >= 0 ) {
  8846. let attribute = attributes[ name ];
  8847. if ( attribute === undefined ) {
  8848. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  8849. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  8850. }
  8851. const data = {};
  8852. data.attribute = attribute;
  8853. if ( attribute && attribute.data ) {
  8854. data.data = attribute.data;
  8855. }
  8856. cache[ name ] = data;
  8857. attributesNum ++;
  8858. }
  8859. }
  8860. currentState.attributes = cache;
  8861. currentState.attributesNum = attributesNum;
  8862. currentState.index = index;
  8863. }
  8864. function initAttributes() {
  8865. const newAttributes = currentState.newAttributes;
  8866. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  8867. newAttributes[ i ] = 0;
  8868. }
  8869. }
  8870. function enableAttribute( attribute ) {
  8871. enableAttributeAndDivisor( attribute, 0 );
  8872. }
  8873. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  8874. const newAttributes = currentState.newAttributes;
  8875. const enabledAttributes = currentState.enabledAttributes;
  8876. const attributeDivisors = currentState.attributeDivisors;
  8877. newAttributes[ attribute ] = 1;
  8878. if ( enabledAttributes[ attribute ] === 0 ) {
  8879. gl.enableVertexAttribArray( attribute );
  8880. enabledAttributes[ attribute ] = 1;
  8881. }
  8882. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  8883. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  8884. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  8885. attributeDivisors[ attribute ] = meshPerAttribute;
  8886. }
  8887. }
  8888. function disableUnusedAttributes() {
  8889. const newAttributes = currentState.newAttributes;
  8890. const enabledAttributes = currentState.enabledAttributes;
  8891. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  8892. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  8893. gl.disableVertexAttribArray( i );
  8894. enabledAttributes[ i ] = 0;
  8895. }
  8896. }
  8897. }
  8898. function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
  8899. if ( capabilities.isWebGL2 === true && ( type === 5124 || type === 5125 ) ) {
  8900. gl.vertexAttribIPointer( index, size, type, stride, offset );
  8901. } else {
  8902. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  8903. }
  8904. }
  8905. function setupVertexAttributes( object, material, program, geometry ) {
  8906. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  8907. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  8908. }
  8909. initAttributes();
  8910. const geometryAttributes = geometry.attributes;
  8911. const programAttributes = program.getAttributes();
  8912. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8913. for ( const name in programAttributes ) {
  8914. const programAttribute = programAttributes[ name ];
  8915. if ( programAttribute.location >= 0 ) {
  8916. let geometryAttribute = geometryAttributes[ name ];
  8917. if ( geometryAttribute === undefined ) {
  8918. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8919. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8920. }
  8921. if ( geometryAttribute !== undefined ) {
  8922. const normalized = geometryAttribute.normalized;
  8923. const size = geometryAttribute.itemSize;
  8924. const attribute = attributes.get( geometryAttribute );
  8925. // TODO Attribute may not be available on context restore
  8926. if ( attribute === undefined ) continue;
  8927. const buffer = attribute.buffer;
  8928. const type = attribute.type;
  8929. const bytesPerElement = attribute.bytesPerElement;
  8930. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  8931. const data = geometryAttribute.data;
  8932. const stride = data.stride;
  8933. const offset = geometryAttribute.offset;
  8934. if ( data.isInstancedInterleavedBuffer ) {
  8935. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8936. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  8937. }
  8938. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8939. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8940. }
  8941. } else {
  8942. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8943. enableAttribute( programAttribute.location + i );
  8944. }
  8945. }
  8946. gl.bindBuffer( 34962, buffer );
  8947. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8948. vertexAttribPointer(
  8949. programAttribute.location + i,
  8950. size / programAttribute.locationSize,
  8951. type,
  8952. normalized,
  8953. stride * bytesPerElement,
  8954. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement
  8955. );
  8956. }
  8957. } else {
  8958. if ( geometryAttribute.isInstancedBufferAttribute ) {
  8959. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8960. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  8961. }
  8962. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8963. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8964. }
  8965. } else {
  8966. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8967. enableAttribute( programAttribute.location + i );
  8968. }
  8969. }
  8970. gl.bindBuffer( 34962, buffer );
  8971. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8972. vertexAttribPointer(
  8973. programAttribute.location + i,
  8974. size / programAttribute.locationSize,
  8975. type,
  8976. normalized,
  8977. size * bytesPerElement,
  8978. ( size / programAttribute.locationSize ) * i * bytesPerElement
  8979. );
  8980. }
  8981. }
  8982. } else if ( materialDefaultAttributeValues !== undefined ) {
  8983. const value = materialDefaultAttributeValues[ name ];
  8984. if ( value !== undefined ) {
  8985. switch ( value.length ) {
  8986. case 2:
  8987. gl.vertexAttrib2fv( programAttribute.location, value );
  8988. break;
  8989. case 3:
  8990. gl.vertexAttrib3fv( programAttribute.location, value );
  8991. break;
  8992. case 4:
  8993. gl.vertexAttrib4fv( programAttribute.location, value );
  8994. break;
  8995. default:
  8996. gl.vertexAttrib1fv( programAttribute.location, value );
  8997. }
  8998. }
  8999. }
  9000. }
  9001. }
  9002. disableUnusedAttributes();
  9003. }
  9004. function dispose() {
  9005. reset();
  9006. for ( const geometryId in bindingStates ) {
  9007. const programMap = bindingStates[ geometryId ];
  9008. for ( const programId in programMap ) {
  9009. const stateMap = programMap[ programId ];
  9010. for ( const wireframe in stateMap ) {
  9011. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9012. delete stateMap[ wireframe ];
  9013. }
  9014. delete programMap[ programId ];
  9015. }
  9016. delete bindingStates[ geometryId ];
  9017. }
  9018. }
  9019. function releaseStatesOfGeometry( geometry ) {
  9020. if ( bindingStates[ geometry.id ] === undefined ) return;
  9021. const programMap = bindingStates[ geometry.id ];
  9022. for ( const programId in programMap ) {
  9023. const stateMap = programMap[ programId ];
  9024. for ( const wireframe in stateMap ) {
  9025. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9026. delete stateMap[ wireframe ];
  9027. }
  9028. delete programMap[ programId ];
  9029. }
  9030. delete bindingStates[ geometry.id ];
  9031. }
  9032. function releaseStatesOfProgram( program ) {
  9033. for ( const geometryId in bindingStates ) {
  9034. const programMap = bindingStates[ geometryId ];
  9035. if ( programMap[ program.id ] === undefined ) continue;
  9036. const stateMap = programMap[ program.id ];
  9037. for ( const wireframe in stateMap ) {
  9038. deleteVertexArrayObject( stateMap[ wireframe ].object );
  9039. delete stateMap[ wireframe ];
  9040. }
  9041. delete programMap[ program.id ];
  9042. }
  9043. }
  9044. function reset() {
  9045. resetDefaultState();
  9046. forceUpdate = true;
  9047. if ( currentState === defaultState ) return;
  9048. currentState = defaultState;
  9049. bindVertexArrayObject( currentState.object );
  9050. }
  9051. // for backward-compatibility
  9052. function resetDefaultState() {
  9053. defaultState.geometry = null;
  9054. defaultState.program = null;
  9055. defaultState.wireframe = false;
  9056. }
  9057. return {
  9058. setup: setup,
  9059. reset: reset,
  9060. resetDefaultState: resetDefaultState,
  9061. dispose: dispose,
  9062. releaseStatesOfGeometry: releaseStatesOfGeometry,
  9063. releaseStatesOfProgram: releaseStatesOfProgram,
  9064. initAttributes: initAttributes,
  9065. enableAttribute: enableAttribute,
  9066. disableUnusedAttributes: disableUnusedAttributes
  9067. };
  9068. }
  9069. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  9070. const isWebGL2 = capabilities.isWebGL2;
  9071. let mode;
  9072. function setMode( value ) {
  9073. mode = value;
  9074. }
  9075. function render( start, count ) {
  9076. gl.drawArrays( mode, start, count );
  9077. info.update( count, mode, 1 );
  9078. }
  9079. function renderInstances( start, count, primcount ) {
  9080. if ( primcount === 0 ) return;
  9081. let extension, methodName;
  9082. if ( isWebGL2 ) {
  9083. extension = gl;
  9084. methodName = 'drawArraysInstanced';
  9085. } else {
  9086. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9087. methodName = 'drawArraysInstancedANGLE';
  9088. if ( extension === null ) {
  9089. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9090. return;
  9091. }
  9092. }
  9093. extension[ methodName ]( mode, start, count, primcount );
  9094. info.update( count, mode, primcount );
  9095. }
  9096. //
  9097. this.setMode = setMode;
  9098. this.render = render;
  9099. this.renderInstances = renderInstances;
  9100. }
  9101. function WebGLCapabilities( gl, extensions, parameters ) {
  9102. let maxAnisotropy;
  9103. function getMaxAnisotropy() {
  9104. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  9105. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  9106. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  9107. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  9108. } else {
  9109. maxAnisotropy = 0;
  9110. }
  9111. return maxAnisotropy;
  9112. }
  9113. function getMaxPrecision( precision ) {
  9114. if ( precision === 'highp' ) {
  9115. if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
  9116. gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
  9117. return 'highp';
  9118. }
  9119. precision = 'mediump';
  9120. }
  9121. if ( precision === 'mediump' ) {
  9122. if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
  9123. gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
  9124. return 'mediump';
  9125. }
  9126. }
  9127. return 'lowp';
  9128. }
  9129. const isWebGL2 = typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext;
  9130. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  9131. const maxPrecision = getMaxPrecision( precision );
  9132. if ( maxPrecision !== precision ) {
  9133. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  9134. precision = maxPrecision;
  9135. }
  9136. const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' );
  9137. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  9138. const maxTextures = gl.getParameter( 34930 );
  9139. const maxVertexTextures = gl.getParameter( 35660 );
  9140. const maxTextureSize = gl.getParameter( 3379 );
  9141. const maxCubemapSize = gl.getParameter( 34076 );
  9142. const maxAttributes = gl.getParameter( 34921 );
  9143. const maxVertexUniforms = gl.getParameter( 36347 );
  9144. const maxVaryings = gl.getParameter( 36348 );
  9145. const maxFragmentUniforms = gl.getParameter( 36349 );
  9146. const vertexTextures = maxVertexTextures > 0;
  9147. const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );
  9148. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  9149. const maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;
  9150. return {
  9151. isWebGL2: isWebGL2,
  9152. drawBuffers: drawBuffers,
  9153. getMaxAnisotropy: getMaxAnisotropy,
  9154. getMaxPrecision: getMaxPrecision,
  9155. precision: precision,
  9156. logarithmicDepthBuffer: logarithmicDepthBuffer,
  9157. maxTextures: maxTextures,
  9158. maxVertexTextures: maxVertexTextures,
  9159. maxTextureSize: maxTextureSize,
  9160. maxCubemapSize: maxCubemapSize,
  9161. maxAttributes: maxAttributes,
  9162. maxVertexUniforms: maxVertexUniforms,
  9163. maxVaryings: maxVaryings,
  9164. maxFragmentUniforms: maxFragmentUniforms,
  9165. vertexTextures: vertexTextures,
  9166. floatFragmentTextures: floatFragmentTextures,
  9167. floatVertexTextures: floatVertexTextures,
  9168. maxSamples: maxSamples
  9169. };
  9170. }
  9171. function WebGLClipping( properties ) {
  9172. const scope = this;
  9173. let globalState = null,
  9174. numGlobalPlanes = 0,
  9175. localClippingEnabled = false,
  9176. renderingShadows = false;
  9177. const plane = new Plane(),
  9178. viewNormalMatrix = new Matrix3(),
  9179. uniform = { value: null, needsUpdate: false };
  9180. this.uniform = uniform;
  9181. this.numPlanes = 0;
  9182. this.numIntersection = 0;
  9183. this.init = function ( planes, enableLocalClipping ) {
  9184. const enabled =
  9185. planes.length !== 0 ||
  9186. enableLocalClipping ||
  9187. // enable state of previous frame - the clipping code has to
  9188. // run another frame in order to reset the state:
  9189. numGlobalPlanes !== 0 ||
  9190. localClippingEnabled;
  9191. localClippingEnabled = enableLocalClipping;
  9192. numGlobalPlanes = planes.length;
  9193. return enabled;
  9194. };
  9195. this.beginShadows = function () {
  9196. renderingShadows = true;
  9197. projectPlanes( null );
  9198. };
  9199. this.endShadows = function () {
  9200. renderingShadows = false;
  9201. };
  9202. this.setGlobalState = function ( planes, camera ) {
  9203. globalState = projectPlanes( planes, camera, 0 );
  9204. };
  9205. this.setState = function ( material, camera, useCache ) {
  9206. const planes = material.clippingPlanes,
  9207. clipIntersection = material.clipIntersection,
  9208. clipShadows = material.clipShadows;
  9209. const materialProperties = properties.get( material );
  9210. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  9211. // there's no local clipping
  9212. if ( renderingShadows ) {
  9213. // there's no global clipping
  9214. projectPlanes( null );
  9215. } else {
  9216. resetGlobalState();
  9217. }
  9218. } else {
  9219. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  9220. lGlobal = nGlobal * 4;
  9221. let dstArray = materialProperties.clippingState || null;
  9222. uniform.value = dstArray; // ensure unique state
  9223. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  9224. for ( let i = 0; i !== lGlobal; ++ i ) {
  9225. dstArray[ i ] = globalState[ i ];
  9226. }
  9227. materialProperties.clippingState = dstArray;
  9228. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  9229. this.numPlanes += nGlobal;
  9230. }
  9231. };
  9232. function resetGlobalState() {
  9233. if ( uniform.value !== globalState ) {
  9234. uniform.value = globalState;
  9235. uniform.needsUpdate = numGlobalPlanes > 0;
  9236. }
  9237. scope.numPlanes = numGlobalPlanes;
  9238. scope.numIntersection = 0;
  9239. }
  9240. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  9241. const nPlanes = planes !== null ? planes.length : 0;
  9242. let dstArray = null;
  9243. if ( nPlanes !== 0 ) {
  9244. dstArray = uniform.value;
  9245. if ( skipTransform !== true || dstArray === null ) {
  9246. const flatSize = dstOffset + nPlanes * 4,
  9247. viewMatrix = camera.matrixWorldInverse;
  9248. viewNormalMatrix.getNormalMatrix( viewMatrix );
  9249. if ( dstArray === null || dstArray.length < flatSize ) {
  9250. dstArray = new Float32Array( flatSize );
  9251. }
  9252. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  9253. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  9254. plane.normal.toArray( dstArray, i4 );
  9255. dstArray[ i4 + 3 ] = plane.constant;
  9256. }
  9257. }
  9258. uniform.value = dstArray;
  9259. uniform.needsUpdate = true;
  9260. }
  9261. scope.numPlanes = nPlanes;
  9262. scope.numIntersection = 0;
  9263. return dstArray;
  9264. }
  9265. }
  9266. function WebGLCubeMaps( renderer ) {
  9267. let cubemaps = new WeakMap();
  9268. function mapTextureMapping( texture, mapping ) {
  9269. if ( mapping === EquirectangularReflectionMapping ) {
  9270. texture.mapping = CubeReflectionMapping;
  9271. } else if ( mapping === EquirectangularRefractionMapping ) {
  9272. texture.mapping = CubeRefractionMapping;
  9273. }
  9274. return texture;
  9275. }
  9276. function get( texture ) {
  9277. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  9278. const mapping = texture.mapping;
  9279. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  9280. if ( cubemaps.has( texture ) ) {
  9281. const cubemap = cubemaps.get( texture ).texture;
  9282. return mapTextureMapping( cubemap, texture.mapping );
  9283. } else {
  9284. const image = texture.image;
  9285. if ( image && image.height > 0 ) {
  9286. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  9287. renderTarget.fromEquirectangularTexture( renderer, texture );
  9288. cubemaps.set( texture, renderTarget );
  9289. texture.addEventListener( 'dispose', onTextureDispose );
  9290. return mapTextureMapping( renderTarget.texture, texture.mapping );
  9291. } else {
  9292. // image not yet ready. try the conversion next frame
  9293. return null;
  9294. }
  9295. }
  9296. }
  9297. }
  9298. return texture;
  9299. }
  9300. function onTextureDispose( event ) {
  9301. const texture = event.target;
  9302. texture.removeEventListener( 'dispose', onTextureDispose );
  9303. const cubemap = cubemaps.get( texture );
  9304. if ( cubemap !== undefined ) {
  9305. cubemaps.delete( texture );
  9306. cubemap.dispose();
  9307. }
  9308. }
  9309. function dispose() {
  9310. cubemaps = new WeakMap();
  9311. }
  9312. return {
  9313. get: get,
  9314. dispose: dispose
  9315. };
  9316. }
  9317. class OrthographicCamera extends Camera {
  9318. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  9319. super();
  9320. this.isOrthographicCamera = true;
  9321. this.type = 'OrthographicCamera';
  9322. this.zoom = 1;
  9323. this.view = null;
  9324. this.left = left;
  9325. this.right = right;
  9326. this.top = top;
  9327. this.bottom = bottom;
  9328. this.near = near;
  9329. this.far = far;
  9330. this.updateProjectionMatrix();
  9331. }
  9332. copy( source, recursive ) {
  9333. super.copy( source, recursive );
  9334. this.left = source.left;
  9335. this.right = source.right;
  9336. this.top = source.top;
  9337. this.bottom = source.bottom;
  9338. this.near = source.near;
  9339. this.far = source.far;
  9340. this.zoom = source.zoom;
  9341. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9342. return this;
  9343. }
  9344. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  9345. if ( this.view === null ) {
  9346. this.view = {
  9347. enabled: true,
  9348. fullWidth: 1,
  9349. fullHeight: 1,
  9350. offsetX: 0,
  9351. offsetY: 0,
  9352. width: 1,
  9353. height: 1
  9354. };
  9355. }
  9356. this.view.enabled = true;
  9357. this.view.fullWidth = fullWidth;
  9358. this.view.fullHeight = fullHeight;
  9359. this.view.offsetX = x;
  9360. this.view.offsetY = y;
  9361. this.view.width = width;
  9362. this.view.height = height;
  9363. this.updateProjectionMatrix();
  9364. }
  9365. clearViewOffset() {
  9366. if ( this.view !== null ) {
  9367. this.view.enabled = false;
  9368. }
  9369. this.updateProjectionMatrix();
  9370. }
  9371. updateProjectionMatrix() {
  9372. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9373. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9374. const cx = ( this.right + this.left ) / 2;
  9375. const cy = ( this.top + this.bottom ) / 2;
  9376. let left = cx - dx;
  9377. let right = cx + dx;
  9378. let top = cy + dy;
  9379. let bottom = cy - dy;
  9380. if ( this.view !== null && this.view.enabled ) {
  9381. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  9382. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  9383. left += scaleW * this.view.offsetX;
  9384. right = left + scaleW * this.view.width;
  9385. top -= scaleH * this.view.offsetY;
  9386. bottom = top - scaleH * this.view.height;
  9387. }
  9388. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  9389. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  9390. }
  9391. toJSON( meta ) {
  9392. const data = super.toJSON( meta );
  9393. data.object.zoom = this.zoom;
  9394. data.object.left = this.left;
  9395. data.object.right = this.right;
  9396. data.object.top = this.top;
  9397. data.object.bottom = this.bottom;
  9398. data.object.near = this.near;
  9399. data.object.far = this.far;
  9400. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9401. return data;
  9402. }
  9403. }
  9404. const LOD_MIN = 4;
  9405. // The standard deviations (radians) associated with the extra mips. These are
  9406. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9407. // geometric shadowing function. These sigma values squared must match the
  9408. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9409. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  9410. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9411. // samples and exit early, but not recompile the shader.
  9412. const MAX_SAMPLES = 20;
  9413. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  9414. const _clearColor = /*@__PURE__*/ new Color();
  9415. let _oldTarget = null;
  9416. // Golden Ratio
  9417. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  9418. const INV_PHI = 1 / PHI;
  9419. // Vertices of a dodecahedron (except the opposites, which represent the
  9420. // same axis), used as axis directions evenly spread on a sphere.
  9421. const _axisDirections = [
  9422. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  9423. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  9424. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  9425. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  9426. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  9427. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  9428. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  9429. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  9430. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  9431. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  9432. /**
  9433. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9434. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9435. * blur to be quickly accessed based on material roughness. It is packed into a
  9436. * special CubeUV format that allows us to perform custom interpolation so that
  9437. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9438. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9439. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9440. * higher roughness levels. In this way we maintain resolution to smoothly
  9441. * interpolate diffuse lighting while limiting sampling computation.
  9442. *
  9443. * Paper: Fast, Accurate Image-Based Lighting
  9444. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9445. */
  9446. class PMREMGenerator {
  9447. constructor( renderer ) {
  9448. this._renderer = renderer;
  9449. this._pingPongRenderTarget = null;
  9450. this._lodMax = 0;
  9451. this._cubeSize = 0;
  9452. this._lodPlanes = [];
  9453. this._sizeLods = [];
  9454. this._sigmas = [];
  9455. this._blurMaterial = null;
  9456. this._cubemapMaterial = null;
  9457. this._equirectMaterial = null;
  9458. this._compileMaterial( this._blurMaterial );
  9459. }
  9460. /**
  9461. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9462. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9463. * in radians to be applied to the scene before PMREM generation. Optional near
  9464. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9465. * is placed at the origin).
  9466. */
  9467. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  9468. _oldTarget = this._renderer.getRenderTarget();
  9469. this._setSize( 256 );
  9470. const cubeUVRenderTarget = this._allocateTargets();
  9471. cubeUVRenderTarget.depthBuffer = true;
  9472. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  9473. if ( sigma > 0 ) {
  9474. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  9475. }
  9476. this._applyPMREM( cubeUVRenderTarget );
  9477. this._cleanup( cubeUVRenderTarget );
  9478. return cubeUVRenderTarget;
  9479. }
  9480. /**
  9481. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9482. * or HDR. The ideal input image size is 1k (1024 x 512),
  9483. * as this matches best with the 256 x 256 cubemap output.
  9484. */
  9485. fromEquirectangular( equirectangular, renderTarget = null ) {
  9486. return this._fromTexture( equirectangular, renderTarget );
  9487. }
  9488. /**
  9489. * Generates a PMREM from an cubemap texture, which can be either LDR
  9490. * or HDR. The ideal input cube size is 256 x 256,
  9491. * as this matches best with the 256 x 256 cubemap output.
  9492. */
  9493. fromCubemap( cubemap, renderTarget = null ) {
  9494. return this._fromTexture( cubemap, renderTarget );
  9495. }
  9496. /**
  9497. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9498. * your texture's network fetch for increased concurrency.
  9499. */
  9500. compileCubemapShader() {
  9501. if ( this._cubemapMaterial === null ) {
  9502. this._cubemapMaterial = _getCubemapMaterial();
  9503. this._compileMaterial( this._cubemapMaterial );
  9504. }
  9505. }
  9506. /**
  9507. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9508. * your texture's network fetch for increased concurrency.
  9509. */
  9510. compileEquirectangularShader() {
  9511. if ( this._equirectMaterial === null ) {
  9512. this._equirectMaterial = _getEquirectMaterial();
  9513. this._compileMaterial( this._equirectMaterial );
  9514. }
  9515. }
  9516. /**
  9517. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9518. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9519. * one of them will cause any others to also become unusable.
  9520. */
  9521. dispose() {
  9522. this._dispose();
  9523. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  9524. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  9525. }
  9526. // private interface
  9527. _setSize( cubeSize ) {
  9528. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  9529. this._cubeSize = Math.pow( 2, this._lodMax );
  9530. }
  9531. _dispose() {
  9532. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  9533. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  9534. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  9535. this._lodPlanes[ i ].dispose();
  9536. }
  9537. }
  9538. _cleanup( outputTarget ) {
  9539. this._renderer.setRenderTarget( _oldTarget );
  9540. outputTarget.scissorTest = false;
  9541. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  9542. }
  9543. _fromTexture( texture, renderTarget ) {
  9544. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  9545. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  9546. } else { // Equirectangular
  9547. this._setSize( texture.image.width / 4 );
  9548. }
  9549. _oldTarget = this._renderer.getRenderTarget();
  9550. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9551. this._textureToCubeUV( texture, cubeUVRenderTarget );
  9552. this._applyPMREM( cubeUVRenderTarget );
  9553. this._cleanup( cubeUVRenderTarget );
  9554. return cubeUVRenderTarget;
  9555. }
  9556. _allocateTargets() {
  9557. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  9558. const height = 4 * this._cubeSize;
  9559. const params = {
  9560. magFilter: LinearFilter,
  9561. minFilter: LinearFilter,
  9562. generateMipmaps: false,
  9563. type: HalfFloatType,
  9564. format: RGBAFormat,
  9565. encoding: LinearEncoding,
  9566. depthBuffer: false
  9567. };
  9568. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  9569. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  9570. if ( this._pingPongRenderTarget !== null ) {
  9571. this._dispose();
  9572. }
  9573. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  9574. const { _lodMax } = this;
  9575. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  9576. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  9577. }
  9578. return cubeUVRenderTarget;
  9579. }
  9580. _compileMaterial( material ) {
  9581. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  9582. this._renderer.compile( tmpMesh, _flatCamera );
  9583. }
  9584. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  9585. const fov = 90;
  9586. const aspect = 1;
  9587. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  9588. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  9589. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  9590. const renderer = this._renderer;
  9591. const originalAutoClear = renderer.autoClear;
  9592. const toneMapping = renderer.toneMapping;
  9593. renderer.getClearColor( _clearColor );
  9594. renderer.toneMapping = NoToneMapping;
  9595. renderer.autoClear = false;
  9596. const backgroundMaterial = new MeshBasicMaterial( {
  9597. name: 'PMREM.Background',
  9598. side: BackSide,
  9599. depthWrite: false,
  9600. depthTest: false,
  9601. } );
  9602. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  9603. let useSolidColor = false;
  9604. const background = scene.background;
  9605. if ( background ) {
  9606. if ( background.isColor ) {
  9607. backgroundMaterial.color.copy( background );
  9608. scene.background = null;
  9609. useSolidColor = true;
  9610. }
  9611. } else {
  9612. backgroundMaterial.color.copy( _clearColor );
  9613. useSolidColor = true;
  9614. }
  9615. for ( let i = 0; i < 6; i ++ ) {
  9616. const col = i % 3;
  9617. if ( col === 0 ) {
  9618. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9619. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  9620. } else if ( col === 1 ) {
  9621. cubeCamera.up.set( 0, 0, upSign[ i ] );
  9622. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  9623. } else {
  9624. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9625. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  9626. }
  9627. const size = this._cubeSize;
  9628. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  9629. renderer.setRenderTarget( cubeUVRenderTarget );
  9630. if ( useSolidColor ) {
  9631. renderer.render( backgroundBox, cubeCamera );
  9632. }
  9633. renderer.render( scene, cubeCamera );
  9634. }
  9635. backgroundBox.geometry.dispose();
  9636. backgroundBox.material.dispose();
  9637. renderer.toneMapping = toneMapping;
  9638. renderer.autoClear = originalAutoClear;
  9639. scene.background = background;
  9640. }
  9641. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  9642. const renderer = this._renderer;
  9643. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  9644. if ( isCubeTexture ) {
  9645. if ( this._cubemapMaterial === null ) {
  9646. this._cubemapMaterial = _getCubemapMaterial();
  9647. }
  9648. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;
  9649. } else {
  9650. if ( this._equirectMaterial === null ) {
  9651. this._equirectMaterial = _getEquirectMaterial();
  9652. }
  9653. }
  9654. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  9655. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  9656. const uniforms = material.uniforms;
  9657. uniforms[ 'envMap' ].value = texture;
  9658. const size = this._cubeSize;
  9659. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  9660. renderer.setRenderTarget( cubeUVRenderTarget );
  9661. renderer.render( mesh, _flatCamera );
  9662. }
  9663. _applyPMREM( cubeUVRenderTarget ) {
  9664. const renderer = this._renderer;
  9665. const autoClear = renderer.autoClear;
  9666. renderer.autoClear = false;
  9667. for ( let i = 1; i < this._lodPlanes.length; i ++ ) {
  9668. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  9669. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  9670. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  9671. }
  9672. renderer.autoClear = autoClear;
  9673. }
  9674. /**
  9675. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9676. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9677. * the blur latitudinally (around the poles), and then longitudinally (towards
  9678. * the poles) to approximate the orthogonally-separable blur. It is least
  9679. * accurate at the poles, but still does a decent job.
  9680. */
  9681. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  9682. const pingPongRenderTarget = this._pingPongRenderTarget;
  9683. this._halfBlur(
  9684. cubeUVRenderTarget,
  9685. pingPongRenderTarget,
  9686. lodIn,
  9687. lodOut,
  9688. sigma,
  9689. 'latitudinal',
  9690. poleAxis );
  9691. this._halfBlur(
  9692. pingPongRenderTarget,
  9693. cubeUVRenderTarget,
  9694. lodOut,
  9695. lodOut,
  9696. sigma,
  9697. 'longitudinal',
  9698. poleAxis );
  9699. }
  9700. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  9701. const renderer = this._renderer;
  9702. const blurMaterial = this._blurMaterial;
  9703. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  9704. console.error(
  9705. 'blur direction must be either latitudinal or longitudinal!' );
  9706. }
  9707. // Number of standard deviations at which to cut off the discrete approximation.
  9708. const STANDARD_DEVIATIONS = 3;
  9709. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  9710. const blurUniforms = blurMaterial.uniforms;
  9711. const pixels = this._sizeLods[ lodIn ] - 1;
  9712. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  9713. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9714. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  9715. if ( samples > MAX_SAMPLES ) {
  9716. console.warn( `sigmaRadians, ${
  9717. sigmaRadians}, is too large and will clip, as it requested ${
  9718. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  9719. }
  9720. const weights = [];
  9721. let sum = 0;
  9722. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  9723. const x = i / sigmaPixels;
  9724. const weight = Math.exp( - x * x / 2 );
  9725. weights.push( weight );
  9726. if ( i === 0 ) {
  9727. sum += weight;
  9728. } else if ( i < samples ) {
  9729. sum += 2 * weight;
  9730. }
  9731. }
  9732. for ( let i = 0; i < weights.length; i ++ ) {
  9733. weights[ i ] = weights[ i ] / sum;
  9734. }
  9735. blurUniforms[ 'envMap' ].value = targetIn.texture;
  9736. blurUniforms[ 'samples' ].value = samples;
  9737. blurUniforms[ 'weights' ].value = weights;
  9738. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  9739. if ( poleAxis ) {
  9740. blurUniforms[ 'poleAxis' ].value = poleAxis;
  9741. }
  9742. const { _lodMax } = this;
  9743. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  9744. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  9745. const outputSize = this._sizeLods[ lodOut ];
  9746. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  9747. const y = 4 * ( this._cubeSize - outputSize );
  9748. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  9749. renderer.setRenderTarget( targetOut );
  9750. renderer.render( blurMesh, _flatCamera );
  9751. }
  9752. }
  9753. function _createPlanes( lodMax ) {
  9754. const lodPlanes = [];
  9755. const sizeLods = [];
  9756. const sigmas = [];
  9757. let lod = lodMax;
  9758. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  9759. for ( let i = 0; i < totalLods; i ++ ) {
  9760. const sizeLod = Math.pow( 2, lod );
  9761. sizeLods.push( sizeLod );
  9762. let sigma = 1.0 / sizeLod;
  9763. if ( i > lodMax - LOD_MIN ) {
  9764. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  9765. } else if ( i === 0 ) {
  9766. sigma = 0;
  9767. }
  9768. sigmas.push( sigma );
  9769. const texelSize = 1.0 / ( sizeLod - 2 );
  9770. const min = - texelSize;
  9771. const max = 1 + texelSize;
  9772. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  9773. const cubeFaces = 6;
  9774. const vertices = 6;
  9775. const positionSize = 3;
  9776. const uvSize = 2;
  9777. const faceIndexSize = 1;
  9778. const position = new Float32Array( positionSize * vertices * cubeFaces );
  9779. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  9780. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  9781. for ( let face = 0; face < cubeFaces; face ++ ) {
  9782. const x = ( face % 3 ) * 2 / 3 - 1;
  9783. const y = face > 2 ? 0 : - 1;
  9784. const coordinates = [
  9785. x, y, 0,
  9786. x + 2 / 3, y, 0,
  9787. x + 2 / 3, y + 1, 0,
  9788. x, y, 0,
  9789. x + 2 / 3, y + 1, 0,
  9790. x, y + 1, 0
  9791. ];
  9792. position.set( coordinates, positionSize * vertices * face );
  9793. uv.set( uv1, uvSize * vertices * face );
  9794. const fill = [ face, face, face, face, face, face ];
  9795. faceIndex.set( fill, faceIndexSize * vertices * face );
  9796. }
  9797. const planes = new BufferGeometry();
  9798. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  9799. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  9800. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  9801. lodPlanes.push( planes );
  9802. if ( lod > LOD_MIN ) {
  9803. lod --;
  9804. }
  9805. }
  9806. return { lodPlanes, sizeLods, sigmas };
  9807. }
  9808. function _createRenderTarget( width, height, params ) {
  9809. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  9810. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9811. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9812. cubeUVRenderTarget.scissorTest = true;
  9813. return cubeUVRenderTarget;
  9814. }
  9815. function _setViewport( target, x, y, width, height ) {
  9816. target.viewport.set( x, y, width, height );
  9817. target.scissor.set( x, y, width, height );
  9818. }
  9819. function _getBlurShader( lodMax, width, height ) {
  9820. const weights = new Float32Array( MAX_SAMPLES );
  9821. const poleAxis = new Vector3( 0, 1, 0 );
  9822. const shaderMaterial = new ShaderMaterial( {
  9823. name: 'SphericalGaussianBlur',
  9824. defines: {
  9825. 'n': MAX_SAMPLES,
  9826. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  9827. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  9828. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  9829. },
  9830. uniforms: {
  9831. 'envMap': { value: null },
  9832. 'samples': { value: 1 },
  9833. 'weights': { value: weights },
  9834. 'latitudinal': { value: false },
  9835. 'dTheta': { value: 0 },
  9836. 'mipInt': { value: 0 },
  9837. 'poleAxis': { value: poleAxis }
  9838. },
  9839. vertexShader: _getCommonVertexShader(),
  9840. fragmentShader: /* glsl */`
  9841. precision mediump float;
  9842. precision mediump int;
  9843. varying vec3 vOutputDirection;
  9844. uniform sampler2D envMap;
  9845. uniform int samples;
  9846. uniform float weights[ n ];
  9847. uniform bool latitudinal;
  9848. uniform float dTheta;
  9849. uniform float mipInt;
  9850. uniform vec3 poleAxis;
  9851. #define ENVMAP_TYPE_CUBE_UV
  9852. #include <cube_uv_reflection_fragment>
  9853. vec3 getSample( float theta, vec3 axis ) {
  9854. float cosTheta = cos( theta );
  9855. // Rodrigues' axis-angle rotation
  9856. vec3 sampleDirection = vOutputDirection * cosTheta
  9857. + cross( axis, vOutputDirection ) * sin( theta )
  9858. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9859. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  9860. }
  9861. void main() {
  9862. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  9863. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  9864. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  9865. }
  9866. axis = normalize( axis );
  9867. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9868. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  9869. for ( int i = 1; i < n; i++ ) {
  9870. if ( i >= samples ) {
  9871. break;
  9872. }
  9873. float theta = dTheta * float( i );
  9874. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  9875. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  9876. }
  9877. }
  9878. `,
  9879. blending: NoBlending,
  9880. depthTest: false,
  9881. depthWrite: false
  9882. } );
  9883. return shaderMaterial;
  9884. }
  9885. function _getEquirectMaterial() {
  9886. return new ShaderMaterial( {
  9887. name: 'EquirectangularToCubeUV',
  9888. uniforms: {
  9889. 'envMap': { value: null }
  9890. },
  9891. vertexShader: _getCommonVertexShader(),
  9892. fragmentShader: /* glsl */`
  9893. precision mediump float;
  9894. precision mediump int;
  9895. varying vec3 vOutputDirection;
  9896. uniform sampler2D envMap;
  9897. #include <common>
  9898. void main() {
  9899. vec3 outputDirection = normalize( vOutputDirection );
  9900. vec2 uv = equirectUv( outputDirection );
  9901. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  9902. }
  9903. `,
  9904. blending: NoBlending,
  9905. depthTest: false,
  9906. depthWrite: false
  9907. } );
  9908. }
  9909. function _getCubemapMaterial() {
  9910. return new ShaderMaterial( {
  9911. name: 'CubemapToCubeUV',
  9912. uniforms: {
  9913. 'envMap': { value: null },
  9914. 'flipEnvMap': { value: - 1 }
  9915. },
  9916. vertexShader: _getCommonVertexShader(),
  9917. fragmentShader: /* glsl */`
  9918. precision mediump float;
  9919. precision mediump int;
  9920. uniform float flipEnvMap;
  9921. varying vec3 vOutputDirection;
  9922. uniform samplerCube envMap;
  9923. void main() {
  9924. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  9925. }
  9926. `,
  9927. blending: NoBlending,
  9928. depthTest: false,
  9929. depthWrite: false
  9930. } );
  9931. }
  9932. function _getCommonVertexShader() {
  9933. return /* glsl */`
  9934. precision mediump float;
  9935. precision mediump int;
  9936. attribute float faceIndex;
  9937. varying vec3 vOutputDirection;
  9938. // RH coordinate system; PMREM face-indexing convention
  9939. vec3 getDirection( vec2 uv, float face ) {
  9940. uv = 2.0 * uv - 1.0;
  9941. vec3 direction = vec3( uv, 1.0 );
  9942. if ( face == 0.0 ) {
  9943. direction = direction.zyx; // ( 1, v, u ) pos x
  9944. } else if ( face == 1.0 ) {
  9945. direction = direction.xzy;
  9946. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  9947. } else if ( face == 2.0 ) {
  9948. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  9949. } else if ( face == 3.0 ) {
  9950. direction = direction.zyx;
  9951. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  9952. } else if ( face == 4.0 ) {
  9953. direction = direction.xzy;
  9954. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  9955. } else if ( face == 5.0 ) {
  9956. direction.z *= -1.0; // ( u, v, -1 ) neg z
  9957. }
  9958. return direction;
  9959. }
  9960. void main() {
  9961. vOutputDirection = getDirection( uv, faceIndex );
  9962. gl_Position = vec4( position, 1.0 );
  9963. }
  9964. `;
  9965. }
  9966. function WebGLCubeUVMaps( renderer ) {
  9967. let cubeUVmaps = new WeakMap();
  9968. let pmremGenerator = null;
  9969. function get( texture ) {
  9970. if ( texture && texture.isTexture ) {
  9971. const mapping = texture.mapping;
  9972. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  9973. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  9974. // equirect/cube map to cubeUV conversion
  9975. if ( isEquirectMap || isCubeMap ) {
  9976. if ( texture.isRenderTargetTexture && texture.needsPMREMUpdate === true ) {
  9977. texture.needsPMREMUpdate = false;
  9978. let renderTarget = cubeUVmaps.get( texture );
  9979. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  9980. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  9981. cubeUVmaps.set( texture, renderTarget );
  9982. return renderTarget.texture;
  9983. } else {
  9984. if ( cubeUVmaps.has( texture ) ) {
  9985. return cubeUVmaps.get( texture ).texture;
  9986. } else {
  9987. const image = texture.image;
  9988. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  9989. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  9990. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  9991. cubeUVmaps.set( texture, renderTarget );
  9992. texture.addEventListener( 'dispose', onTextureDispose );
  9993. return renderTarget.texture;
  9994. } else {
  9995. // image not yet ready. try the conversion next frame
  9996. return null;
  9997. }
  9998. }
  9999. }
  10000. }
  10001. }
  10002. return texture;
  10003. }
  10004. function isCubeTextureComplete( image ) {
  10005. let count = 0;
  10006. const length = 6;
  10007. for ( let i = 0; i < length; i ++ ) {
  10008. if ( image[ i ] !== undefined ) count ++;
  10009. }
  10010. return count === length;
  10011. }
  10012. function onTextureDispose( event ) {
  10013. const texture = event.target;
  10014. texture.removeEventListener( 'dispose', onTextureDispose );
  10015. const cubemapUV = cubeUVmaps.get( texture );
  10016. if ( cubemapUV !== undefined ) {
  10017. cubeUVmaps.delete( texture );
  10018. cubemapUV.dispose();
  10019. }
  10020. }
  10021. function dispose() {
  10022. cubeUVmaps = new WeakMap();
  10023. if ( pmremGenerator !== null ) {
  10024. pmremGenerator.dispose();
  10025. pmremGenerator = null;
  10026. }
  10027. }
  10028. return {
  10029. get: get,
  10030. dispose: dispose
  10031. };
  10032. }
  10033. function WebGLExtensions( gl ) {
  10034. const extensions = {};
  10035. function getExtension( name ) {
  10036. if ( extensions[ name ] !== undefined ) {
  10037. return extensions[ name ];
  10038. }
  10039. let extension;
  10040. switch ( name ) {
  10041. case 'WEBGL_depth_texture':
  10042. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  10043. break;
  10044. case 'EXT_texture_filter_anisotropic':
  10045. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  10046. break;
  10047. case 'WEBGL_compressed_texture_s3tc':
  10048. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  10049. break;
  10050. case 'WEBGL_compressed_texture_pvrtc':
  10051. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  10052. break;
  10053. default:
  10054. extension = gl.getExtension( name );
  10055. }
  10056. extensions[ name ] = extension;
  10057. return extension;
  10058. }
  10059. return {
  10060. has: function ( name ) {
  10061. return getExtension( name ) !== null;
  10062. },
  10063. init: function ( capabilities ) {
  10064. if ( capabilities.isWebGL2 ) {
  10065. getExtension( 'EXT_color_buffer_float' );
  10066. } else {
  10067. getExtension( 'WEBGL_depth_texture' );
  10068. getExtension( 'OES_texture_float' );
  10069. getExtension( 'OES_texture_half_float' );
  10070. getExtension( 'OES_texture_half_float_linear' );
  10071. getExtension( 'OES_standard_derivatives' );
  10072. getExtension( 'OES_element_index_uint' );
  10073. getExtension( 'OES_vertex_array_object' );
  10074. getExtension( 'ANGLE_instanced_arrays' );
  10075. }
  10076. getExtension( 'OES_texture_float_linear' );
  10077. getExtension( 'EXT_color_buffer_half_float' );
  10078. getExtension( 'WEBGL_multisampled_render_to_texture' );
  10079. },
  10080. get: function ( name ) {
  10081. const extension = getExtension( name );
  10082. if ( extension === null ) {
  10083. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  10084. }
  10085. return extension;
  10086. }
  10087. };
  10088. }
  10089. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  10090. const geometries = {};
  10091. const wireframeAttributes = new WeakMap();
  10092. function onGeometryDispose( event ) {
  10093. const geometry = event.target;
  10094. if ( geometry.index !== null ) {
  10095. attributes.remove( geometry.index );
  10096. }
  10097. for ( const name in geometry.attributes ) {
  10098. attributes.remove( geometry.attributes[ name ] );
  10099. }
  10100. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10101. delete geometries[ geometry.id ];
  10102. const attribute = wireframeAttributes.get( geometry );
  10103. if ( attribute ) {
  10104. attributes.remove( attribute );
  10105. wireframeAttributes.delete( geometry );
  10106. }
  10107. bindingStates.releaseStatesOfGeometry( geometry );
  10108. if ( geometry.isInstancedBufferGeometry === true ) {
  10109. delete geometry._maxInstanceCount;
  10110. }
  10111. //
  10112. info.memory.geometries --;
  10113. }
  10114. function get( object, geometry ) {
  10115. if ( geometries[ geometry.id ] === true ) return geometry;
  10116. geometry.addEventListener( 'dispose', onGeometryDispose );
  10117. geometries[ geometry.id ] = true;
  10118. info.memory.geometries ++;
  10119. return geometry;
  10120. }
  10121. function update( geometry ) {
  10122. const geometryAttributes = geometry.attributes;
  10123. // Updating index buffer in VAO now. See WebGLBindingStates.
  10124. for ( const name in geometryAttributes ) {
  10125. attributes.update( geometryAttributes[ name ], 34962 );
  10126. }
  10127. // morph targets
  10128. const morphAttributes = geometry.morphAttributes;
  10129. for ( const name in morphAttributes ) {
  10130. const array = morphAttributes[ name ];
  10131. for ( let i = 0, l = array.length; i < l; i ++ ) {
  10132. attributes.update( array[ i ], 34962 );
  10133. }
  10134. }
  10135. }
  10136. function updateWireframeAttribute( geometry ) {
  10137. const indices = [];
  10138. const geometryIndex = geometry.index;
  10139. const geometryPosition = geometry.attributes.position;
  10140. let version = 0;
  10141. if ( geometryIndex !== null ) {
  10142. const array = geometryIndex.array;
  10143. version = geometryIndex.version;
  10144. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  10145. const a = array[ i + 0 ];
  10146. const b = array[ i + 1 ];
  10147. const c = array[ i + 2 ];
  10148. indices.push( a, b, b, c, c, a );
  10149. }
  10150. } else {
  10151. const array = geometryPosition.array;
  10152. version = geometryPosition.version;
  10153. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  10154. const a = i + 0;
  10155. const b = i + 1;
  10156. const c = i + 2;
  10157. indices.push( a, b, b, c, c, a );
  10158. }
  10159. }
  10160. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  10161. attribute.version = version;
  10162. // Updating index buffer in VAO now. See WebGLBindingStates
  10163. //
  10164. const previousAttribute = wireframeAttributes.get( geometry );
  10165. if ( previousAttribute ) attributes.remove( previousAttribute );
  10166. //
  10167. wireframeAttributes.set( geometry, attribute );
  10168. }
  10169. function getWireframeAttribute( geometry ) {
  10170. const currentAttribute = wireframeAttributes.get( geometry );
  10171. if ( currentAttribute ) {
  10172. const geometryIndex = geometry.index;
  10173. if ( geometryIndex !== null ) {
  10174. // if the attribute is obsolete, create a new one
  10175. if ( currentAttribute.version < geometryIndex.version ) {
  10176. updateWireframeAttribute( geometry );
  10177. }
  10178. }
  10179. } else {
  10180. updateWireframeAttribute( geometry );
  10181. }
  10182. return wireframeAttributes.get( geometry );
  10183. }
  10184. return {
  10185. get: get,
  10186. update: update,
  10187. getWireframeAttribute: getWireframeAttribute
  10188. };
  10189. }
  10190. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  10191. const isWebGL2 = capabilities.isWebGL2;
  10192. let mode;
  10193. function setMode( value ) {
  10194. mode = value;
  10195. }
  10196. let type, bytesPerElement;
  10197. function setIndex( value ) {
  10198. type = value.type;
  10199. bytesPerElement = value.bytesPerElement;
  10200. }
  10201. function render( start, count ) {
  10202. gl.drawElements( mode, count, type, start * bytesPerElement );
  10203. info.update( count, mode, 1 );
  10204. }
  10205. function renderInstances( start, count, primcount ) {
  10206. if ( primcount === 0 ) return;
  10207. let extension, methodName;
  10208. if ( isWebGL2 ) {
  10209. extension = gl;
  10210. methodName = 'drawElementsInstanced';
  10211. } else {
  10212. extension = extensions.get( 'ANGLE_instanced_arrays' );
  10213. methodName = 'drawElementsInstancedANGLE';
  10214. if ( extension === null ) {
  10215. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  10216. return;
  10217. }
  10218. }
  10219. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  10220. info.update( count, mode, primcount );
  10221. }
  10222. //
  10223. this.setMode = setMode;
  10224. this.setIndex = setIndex;
  10225. this.render = render;
  10226. this.renderInstances = renderInstances;
  10227. }
  10228. function WebGLInfo( gl ) {
  10229. const memory = {
  10230. geometries: 0,
  10231. textures: 0
  10232. };
  10233. const render = {
  10234. frame: 0,
  10235. calls: 0,
  10236. triangles: 0,
  10237. points: 0,
  10238. lines: 0
  10239. };
  10240. function update( count, mode, instanceCount ) {
  10241. render.calls ++;
  10242. switch ( mode ) {
  10243. case 4:
  10244. render.triangles += instanceCount * ( count / 3 );
  10245. break;
  10246. case 1:
  10247. render.lines += instanceCount * ( count / 2 );
  10248. break;
  10249. case 3:
  10250. render.lines += instanceCount * ( count - 1 );
  10251. break;
  10252. case 2:
  10253. render.lines += instanceCount * count;
  10254. break;
  10255. case 0:
  10256. render.points += instanceCount * count;
  10257. break;
  10258. default:
  10259. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  10260. break;
  10261. }
  10262. }
  10263. function reset() {
  10264. render.frame ++;
  10265. render.calls = 0;
  10266. render.triangles = 0;
  10267. render.points = 0;
  10268. render.lines = 0;
  10269. }
  10270. return {
  10271. memory: memory,
  10272. render: render,
  10273. programs: null,
  10274. autoReset: true,
  10275. reset: reset,
  10276. update: update
  10277. };
  10278. }
  10279. function numericalSort( a, b ) {
  10280. return a[ 0 ] - b[ 0 ];
  10281. }
  10282. function absNumericalSort( a, b ) {
  10283. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  10284. }
  10285. function WebGLMorphtargets( gl, capabilities, textures ) {
  10286. const influencesList = {};
  10287. const morphInfluences = new Float32Array( 8 );
  10288. const morphTextures = new WeakMap();
  10289. const morph = new Vector4();
  10290. const workInfluences = [];
  10291. for ( let i = 0; i < 8; i ++ ) {
  10292. workInfluences[ i ] = [ i, 0 ];
  10293. }
  10294. function update( object, geometry, program ) {
  10295. const objectInfluences = object.morphTargetInfluences;
  10296. if ( capabilities.isWebGL2 === true ) {
  10297. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10298. // into an array of data textures. Each layer represents a single morph target.
  10299. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10300. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10301. let entry = morphTextures.get( geometry );
  10302. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10303. if ( entry !== undefined ) entry.texture.dispose();
  10304. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10305. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10306. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10307. const morphTargets = geometry.morphAttributes.position || [];
  10308. const morphNormals = geometry.morphAttributes.normal || [];
  10309. const morphColors = geometry.morphAttributes.color || [];
  10310. let vertexDataCount = 0;
  10311. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10312. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10313. if ( hasMorphColors === true ) vertexDataCount = 3;
  10314. let width = geometry.attributes.position.count * vertexDataCount;
  10315. let height = 1;
  10316. if ( width > capabilities.maxTextureSize ) {
  10317. height = Math.ceil( width / capabilities.maxTextureSize );
  10318. width = capabilities.maxTextureSize;
  10319. }
  10320. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10321. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10322. texture.type = FloatType;
  10323. texture.needsUpdate = true;
  10324. // fill buffer
  10325. const vertexDataStride = vertexDataCount * 4;
  10326. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10327. const morphTarget = morphTargets[ i ];
  10328. const morphNormal = morphNormals[ i ];
  10329. const morphColor = morphColors[ i ];
  10330. const offset = width * height * 4 * i;
  10331. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10332. const stride = j * vertexDataStride;
  10333. if ( hasMorphPosition === true ) {
  10334. morph.fromBufferAttribute( morphTarget, j );
  10335. buffer[ offset + stride + 0 ] = morph.x;
  10336. buffer[ offset + stride + 1 ] = morph.y;
  10337. buffer[ offset + stride + 2 ] = morph.z;
  10338. buffer[ offset + stride + 3 ] = 0;
  10339. }
  10340. if ( hasMorphNormals === true ) {
  10341. morph.fromBufferAttribute( morphNormal, j );
  10342. buffer[ offset + stride + 4 ] = morph.x;
  10343. buffer[ offset + stride + 5 ] = morph.y;
  10344. buffer[ offset + stride + 6 ] = morph.z;
  10345. buffer[ offset + stride + 7 ] = 0;
  10346. }
  10347. if ( hasMorphColors === true ) {
  10348. morph.fromBufferAttribute( morphColor, j );
  10349. buffer[ offset + stride + 8 ] = morph.x;
  10350. buffer[ offset + stride + 9 ] = morph.y;
  10351. buffer[ offset + stride + 10 ] = morph.z;
  10352. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  10353. }
  10354. }
  10355. }
  10356. entry = {
  10357. count: morphTargetsCount,
  10358. texture: texture,
  10359. size: new Vector2( width, height )
  10360. };
  10361. morphTextures.set( geometry, entry );
  10362. function disposeTexture() {
  10363. texture.dispose();
  10364. morphTextures.delete( geometry );
  10365. geometry.removeEventListener( 'dispose', disposeTexture );
  10366. }
  10367. geometry.addEventListener( 'dispose', disposeTexture );
  10368. }
  10369. //
  10370. let morphInfluencesSum = 0;
  10371. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10372. morphInfluencesSum += objectInfluences[ i ];
  10373. }
  10374. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10375. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10376. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  10377. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  10378. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  10379. } else {
  10380. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10381. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10382. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10383. let influences = influencesList[ geometry.id ];
  10384. if ( influences === undefined || influences.length !== length ) {
  10385. // initialise list
  10386. influences = [];
  10387. for ( let i = 0; i < length; i ++ ) {
  10388. influences[ i ] = [ i, 0 ];
  10389. }
  10390. influencesList[ geometry.id ] = influences;
  10391. }
  10392. // Collect influences
  10393. for ( let i = 0; i < length; i ++ ) {
  10394. const influence = influences[ i ];
  10395. influence[ 0 ] = i;
  10396. influence[ 1 ] = objectInfluences[ i ];
  10397. }
  10398. influences.sort( absNumericalSort );
  10399. for ( let i = 0; i < 8; i ++ ) {
  10400. if ( i < length && influences[ i ][ 1 ] ) {
  10401. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  10402. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  10403. } else {
  10404. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  10405. workInfluences[ i ][ 1 ] = 0;
  10406. }
  10407. }
  10408. workInfluences.sort( numericalSort );
  10409. const morphTargets = geometry.morphAttributes.position;
  10410. const morphNormals = geometry.morphAttributes.normal;
  10411. let morphInfluencesSum = 0;
  10412. for ( let i = 0; i < 8; i ++ ) {
  10413. const influence = workInfluences[ i ];
  10414. const index = influence[ 0 ];
  10415. const value = influence[ 1 ];
  10416. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  10417. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  10418. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  10419. }
  10420. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  10421. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  10422. }
  10423. morphInfluences[ i ] = value;
  10424. morphInfluencesSum += value;
  10425. } else {
  10426. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  10427. geometry.deleteAttribute( 'morphTarget' + i );
  10428. }
  10429. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  10430. geometry.deleteAttribute( 'morphNormal' + i );
  10431. }
  10432. morphInfluences[ i ] = 0;
  10433. }
  10434. }
  10435. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10436. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10437. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10438. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10439. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10440. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  10441. }
  10442. }
  10443. return {
  10444. update: update
  10445. };
  10446. }
  10447. function WebGLObjects( gl, geometries, attributes, info ) {
  10448. let updateMap = new WeakMap();
  10449. function update( object ) {
  10450. const frame = info.render.frame;
  10451. const geometry = object.geometry;
  10452. const buffergeometry = geometries.get( object, geometry );
  10453. // Update once per frame
  10454. if ( updateMap.get( buffergeometry ) !== frame ) {
  10455. geometries.update( buffergeometry );
  10456. updateMap.set( buffergeometry, frame );
  10457. }
  10458. if ( object.isInstancedMesh ) {
  10459. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10460. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10461. }
  10462. attributes.update( object.instanceMatrix, 34962 );
  10463. if ( object.instanceColor !== null ) {
  10464. attributes.update( object.instanceColor, 34962 );
  10465. }
  10466. }
  10467. return buffergeometry;
  10468. }
  10469. function dispose() {
  10470. updateMap = new WeakMap();
  10471. }
  10472. function onInstancedMeshDispose( event ) {
  10473. const instancedMesh = event.target;
  10474. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10475. attributes.remove( instancedMesh.instanceMatrix );
  10476. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10477. }
  10478. return {
  10479. update: update,
  10480. dispose: dispose
  10481. };
  10482. }
  10483. /**
  10484. * Uniforms of a program.
  10485. * Those form a tree structure with a special top-level container for the root,
  10486. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10487. *
  10488. *
  10489. * Properties of inner nodes including the top-level container:
  10490. *
  10491. * .seq - array of nested uniforms
  10492. * .map - nested uniforms by name
  10493. *
  10494. *
  10495. * Methods of all nodes except the top-level container:
  10496. *
  10497. * .setValue( gl, value, [textures] )
  10498. *
  10499. * uploads a uniform value(s)
  10500. * the 'textures' parameter is needed for sampler uniforms
  10501. *
  10502. *
  10503. * Static methods of the top-level container (textures factorizations):
  10504. *
  10505. * .upload( gl, seq, values, textures )
  10506. *
  10507. * sets uniforms in 'seq' to 'values[id].value'
  10508. *
  10509. * .seqWithValue( seq, values ) : filteredSeq
  10510. *
  10511. * filters 'seq' entries with corresponding entry in values
  10512. *
  10513. *
  10514. * Methods of the top-level container (textures factorizations):
  10515. *
  10516. * .setValue( gl, name, value, textures )
  10517. *
  10518. * sets uniform with name 'name' to 'value'
  10519. *
  10520. * .setOptional( gl, obj, prop )
  10521. *
  10522. * like .set for an optional property of the object
  10523. *
  10524. */
  10525. const emptyTexture = /*@__PURE__*/ new Texture();
  10526. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  10527. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  10528. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  10529. // --- Utilities ---
  10530. // Array Caches (provide typed arrays for temporary by size)
  10531. const arrayCacheF32 = [];
  10532. const arrayCacheI32 = [];
  10533. // Float32Array caches used for uploading Matrix uniforms
  10534. const mat4array = new Float32Array( 16 );
  10535. const mat3array = new Float32Array( 9 );
  10536. const mat2array = new Float32Array( 4 );
  10537. // Flattening for arrays of vectors and matrices
  10538. function flatten( array, nBlocks, blockSize ) {
  10539. const firstElem = array[ 0 ];
  10540. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10541. // unoptimized: ! isNaN( firstElem )
  10542. // see http://jacksondunstan.com/articles/983
  10543. const n = nBlocks * blockSize;
  10544. let r = arrayCacheF32[ n ];
  10545. if ( r === undefined ) {
  10546. r = new Float32Array( n );
  10547. arrayCacheF32[ n ] = r;
  10548. }
  10549. if ( nBlocks !== 0 ) {
  10550. firstElem.toArray( r, 0 );
  10551. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10552. offset += blockSize;
  10553. array[ i ].toArray( r, offset );
  10554. }
  10555. }
  10556. return r;
  10557. }
  10558. function arraysEqual( a, b ) {
  10559. if ( a.length !== b.length ) return false;
  10560. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10561. if ( a[ i ] !== b[ i ] ) return false;
  10562. }
  10563. return true;
  10564. }
  10565. function copyArray( a, b ) {
  10566. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10567. a[ i ] = b[ i ];
  10568. }
  10569. }
  10570. // Texture unit allocation
  10571. function allocTexUnits( textures, n ) {
  10572. let r = arrayCacheI32[ n ];
  10573. if ( r === undefined ) {
  10574. r = new Int32Array( n );
  10575. arrayCacheI32[ n ] = r;
  10576. }
  10577. for ( let i = 0; i !== n; ++ i ) {
  10578. r[ i ] = textures.allocateTextureUnit();
  10579. }
  10580. return r;
  10581. }
  10582. // --- Setters ---
  10583. // Note: Defining these methods externally, because they come in a bunch
  10584. // and this way their names minify.
  10585. // Single scalar
  10586. function setValueV1f( gl, v ) {
  10587. const cache = this.cache;
  10588. if ( cache[ 0 ] === v ) return;
  10589. gl.uniform1f( this.addr, v );
  10590. cache[ 0 ] = v;
  10591. }
  10592. // Single float vector (from flat array or THREE.VectorN)
  10593. function setValueV2f( gl, v ) {
  10594. const cache = this.cache;
  10595. if ( v.x !== undefined ) {
  10596. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10597. gl.uniform2f( this.addr, v.x, v.y );
  10598. cache[ 0 ] = v.x;
  10599. cache[ 1 ] = v.y;
  10600. }
  10601. } else {
  10602. if ( arraysEqual( cache, v ) ) return;
  10603. gl.uniform2fv( this.addr, v );
  10604. copyArray( cache, v );
  10605. }
  10606. }
  10607. function setValueV3f( gl, v ) {
  10608. const cache = this.cache;
  10609. if ( v.x !== undefined ) {
  10610. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10611. gl.uniform3f( this.addr, v.x, v.y, v.z );
  10612. cache[ 0 ] = v.x;
  10613. cache[ 1 ] = v.y;
  10614. cache[ 2 ] = v.z;
  10615. }
  10616. } else if ( v.r !== undefined ) {
  10617. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  10618. gl.uniform3f( this.addr, v.r, v.g, v.b );
  10619. cache[ 0 ] = v.r;
  10620. cache[ 1 ] = v.g;
  10621. cache[ 2 ] = v.b;
  10622. }
  10623. } else {
  10624. if ( arraysEqual( cache, v ) ) return;
  10625. gl.uniform3fv( this.addr, v );
  10626. copyArray( cache, v );
  10627. }
  10628. }
  10629. function setValueV4f( gl, v ) {
  10630. const cache = this.cache;
  10631. if ( v.x !== undefined ) {
  10632. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10633. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  10634. cache[ 0 ] = v.x;
  10635. cache[ 1 ] = v.y;
  10636. cache[ 2 ] = v.z;
  10637. cache[ 3 ] = v.w;
  10638. }
  10639. } else {
  10640. if ( arraysEqual( cache, v ) ) return;
  10641. gl.uniform4fv( this.addr, v );
  10642. copyArray( cache, v );
  10643. }
  10644. }
  10645. // Single matrix (from flat array or THREE.MatrixN)
  10646. function setValueM2( gl, v ) {
  10647. const cache = this.cache;
  10648. const elements = v.elements;
  10649. if ( elements === undefined ) {
  10650. if ( arraysEqual( cache, v ) ) return;
  10651. gl.uniformMatrix2fv( this.addr, false, v );
  10652. copyArray( cache, v );
  10653. } else {
  10654. if ( arraysEqual( cache, elements ) ) return;
  10655. mat2array.set( elements );
  10656. gl.uniformMatrix2fv( this.addr, false, mat2array );
  10657. copyArray( cache, elements );
  10658. }
  10659. }
  10660. function setValueM3( gl, v ) {
  10661. const cache = this.cache;
  10662. const elements = v.elements;
  10663. if ( elements === undefined ) {
  10664. if ( arraysEqual( cache, v ) ) return;
  10665. gl.uniformMatrix3fv( this.addr, false, v );
  10666. copyArray( cache, v );
  10667. } else {
  10668. if ( arraysEqual( cache, elements ) ) return;
  10669. mat3array.set( elements );
  10670. gl.uniformMatrix3fv( this.addr, false, mat3array );
  10671. copyArray( cache, elements );
  10672. }
  10673. }
  10674. function setValueM4( gl, v ) {
  10675. const cache = this.cache;
  10676. const elements = v.elements;
  10677. if ( elements === undefined ) {
  10678. if ( arraysEqual( cache, v ) ) return;
  10679. gl.uniformMatrix4fv( this.addr, false, v );
  10680. copyArray( cache, v );
  10681. } else {
  10682. if ( arraysEqual( cache, elements ) ) return;
  10683. mat4array.set( elements );
  10684. gl.uniformMatrix4fv( this.addr, false, mat4array );
  10685. copyArray( cache, elements );
  10686. }
  10687. }
  10688. // Single integer / boolean
  10689. function setValueV1i( gl, v ) {
  10690. const cache = this.cache;
  10691. if ( cache[ 0 ] === v ) return;
  10692. gl.uniform1i( this.addr, v );
  10693. cache[ 0 ] = v;
  10694. }
  10695. // Single integer / boolean vector (from flat array or THREE.VectorN)
  10696. function setValueV2i( gl, v ) {
  10697. const cache = this.cache;
  10698. if ( v.x !== undefined ) {
  10699. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10700. gl.uniform2i( this.addr, v.x, v.y );
  10701. cache[ 0 ] = v.x;
  10702. cache[ 1 ] = v.y;
  10703. }
  10704. } else {
  10705. if ( arraysEqual( cache, v ) ) return;
  10706. gl.uniform2iv( this.addr, v );
  10707. copyArray( cache, v );
  10708. }
  10709. }
  10710. function setValueV3i( gl, v ) {
  10711. const cache = this.cache;
  10712. if ( v.x !== undefined ) {
  10713. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10714. gl.uniform3i( this.addr, v.x, v.y, v.z );
  10715. cache[ 0 ] = v.x;
  10716. cache[ 1 ] = v.y;
  10717. cache[ 2 ] = v.z;
  10718. }
  10719. } else {
  10720. if ( arraysEqual( cache, v ) ) return;
  10721. gl.uniform3iv( this.addr, v );
  10722. copyArray( cache, v );
  10723. }
  10724. }
  10725. function setValueV4i( gl, v ) {
  10726. const cache = this.cache;
  10727. if ( v.x !== undefined ) {
  10728. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10729. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  10730. cache[ 0 ] = v.x;
  10731. cache[ 1 ] = v.y;
  10732. cache[ 2 ] = v.z;
  10733. cache[ 3 ] = v.w;
  10734. }
  10735. } else {
  10736. if ( arraysEqual( cache, v ) ) return;
  10737. gl.uniform4iv( this.addr, v );
  10738. copyArray( cache, v );
  10739. }
  10740. }
  10741. // Single unsigned integer
  10742. function setValueV1ui( gl, v ) {
  10743. const cache = this.cache;
  10744. if ( cache[ 0 ] === v ) return;
  10745. gl.uniform1ui( this.addr, v );
  10746. cache[ 0 ] = v;
  10747. }
  10748. // Single unsigned integer vector (from flat array or THREE.VectorN)
  10749. function setValueV2ui( gl, v ) {
  10750. const cache = this.cache;
  10751. if ( v.x !== undefined ) {
  10752. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10753. gl.uniform2ui( this.addr, v.x, v.y );
  10754. cache[ 0 ] = v.x;
  10755. cache[ 1 ] = v.y;
  10756. }
  10757. } else {
  10758. if ( arraysEqual( cache, v ) ) return;
  10759. gl.uniform2uiv( this.addr, v );
  10760. copyArray( cache, v );
  10761. }
  10762. }
  10763. function setValueV3ui( gl, v ) {
  10764. const cache = this.cache;
  10765. if ( v.x !== undefined ) {
  10766. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10767. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  10768. cache[ 0 ] = v.x;
  10769. cache[ 1 ] = v.y;
  10770. cache[ 2 ] = v.z;
  10771. }
  10772. } else {
  10773. if ( arraysEqual( cache, v ) ) return;
  10774. gl.uniform3uiv( this.addr, v );
  10775. copyArray( cache, v );
  10776. }
  10777. }
  10778. function setValueV4ui( gl, v ) {
  10779. const cache = this.cache;
  10780. if ( v.x !== undefined ) {
  10781. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10782. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  10783. cache[ 0 ] = v.x;
  10784. cache[ 1 ] = v.y;
  10785. cache[ 2 ] = v.z;
  10786. cache[ 3 ] = v.w;
  10787. }
  10788. } else {
  10789. if ( arraysEqual( cache, v ) ) return;
  10790. gl.uniform4uiv( this.addr, v );
  10791. copyArray( cache, v );
  10792. }
  10793. }
  10794. // Single texture (2D / Cube)
  10795. function setValueT1( gl, v, textures ) {
  10796. const cache = this.cache;
  10797. const unit = textures.allocateTextureUnit();
  10798. if ( cache[ 0 ] !== unit ) {
  10799. gl.uniform1i( this.addr, unit );
  10800. cache[ 0 ] = unit;
  10801. }
  10802. textures.setTexture2D( v || emptyTexture, unit );
  10803. }
  10804. function setValueT3D1( gl, v, textures ) {
  10805. const cache = this.cache;
  10806. const unit = textures.allocateTextureUnit();
  10807. if ( cache[ 0 ] !== unit ) {
  10808. gl.uniform1i( this.addr, unit );
  10809. cache[ 0 ] = unit;
  10810. }
  10811. textures.setTexture3D( v || empty3dTexture, unit );
  10812. }
  10813. function setValueT6( gl, v, textures ) {
  10814. const cache = this.cache;
  10815. const unit = textures.allocateTextureUnit();
  10816. if ( cache[ 0 ] !== unit ) {
  10817. gl.uniform1i( this.addr, unit );
  10818. cache[ 0 ] = unit;
  10819. }
  10820. textures.setTextureCube( v || emptyCubeTexture, unit );
  10821. }
  10822. function setValueT2DArray1( gl, v, textures ) {
  10823. const cache = this.cache;
  10824. const unit = textures.allocateTextureUnit();
  10825. if ( cache[ 0 ] !== unit ) {
  10826. gl.uniform1i( this.addr, unit );
  10827. cache[ 0 ] = unit;
  10828. }
  10829. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  10830. }
  10831. // Helper to pick the right setter for the singular case
  10832. function getSingularSetter( type ) {
  10833. switch ( type ) {
  10834. case 0x1406: return setValueV1f; // FLOAT
  10835. case 0x8b50: return setValueV2f; // _VEC2
  10836. case 0x8b51: return setValueV3f; // _VEC3
  10837. case 0x8b52: return setValueV4f; // _VEC4
  10838. case 0x8b5a: return setValueM2; // _MAT2
  10839. case 0x8b5b: return setValueM3; // _MAT3
  10840. case 0x8b5c: return setValueM4; // _MAT4
  10841. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  10842. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  10843. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  10844. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  10845. case 0x1405: return setValueV1ui; // UINT
  10846. case 0x8dc6: return setValueV2ui; // _VEC2
  10847. case 0x8dc7: return setValueV3ui; // _VEC3
  10848. case 0x8dc8: return setValueV4ui; // _VEC4
  10849. case 0x8b5e: // SAMPLER_2D
  10850. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10851. case 0x8dca: // INT_SAMPLER_2D
  10852. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10853. case 0x8b62: // SAMPLER_2D_SHADOW
  10854. return setValueT1;
  10855. case 0x8b5f: // SAMPLER_3D
  10856. case 0x8dcb: // INT_SAMPLER_3D
  10857. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10858. return setValueT3D1;
  10859. case 0x8b60: // SAMPLER_CUBE
  10860. case 0x8dcc: // INT_SAMPLER_CUBE
  10861. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10862. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10863. return setValueT6;
  10864. case 0x8dc1: // SAMPLER_2D_ARRAY
  10865. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10866. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10867. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10868. return setValueT2DArray1;
  10869. }
  10870. }
  10871. // Array of scalars
  10872. function setValueV1fArray( gl, v ) {
  10873. gl.uniform1fv( this.addr, v );
  10874. }
  10875. // Array of vectors (from flat array or array of THREE.VectorN)
  10876. function setValueV2fArray( gl, v ) {
  10877. const data = flatten( v, this.size, 2 );
  10878. gl.uniform2fv( this.addr, data );
  10879. }
  10880. function setValueV3fArray( gl, v ) {
  10881. const data = flatten( v, this.size, 3 );
  10882. gl.uniform3fv( this.addr, data );
  10883. }
  10884. function setValueV4fArray( gl, v ) {
  10885. const data = flatten( v, this.size, 4 );
  10886. gl.uniform4fv( this.addr, data );
  10887. }
  10888. // Array of matrices (from flat array or array of THREE.MatrixN)
  10889. function setValueM2Array( gl, v ) {
  10890. const data = flatten( v, this.size, 4 );
  10891. gl.uniformMatrix2fv( this.addr, false, data );
  10892. }
  10893. function setValueM3Array( gl, v ) {
  10894. const data = flatten( v, this.size, 9 );
  10895. gl.uniformMatrix3fv( this.addr, false, data );
  10896. }
  10897. function setValueM4Array( gl, v ) {
  10898. const data = flatten( v, this.size, 16 );
  10899. gl.uniformMatrix4fv( this.addr, false, data );
  10900. }
  10901. // Array of integer / boolean
  10902. function setValueV1iArray( gl, v ) {
  10903. gl.uniform1iv( this.addr, v );
  10904. }
  10905. // Array of integer / boolean vectors (from flat array)
  10906. function setValueV2iArray( gl, v ) {
  10907. gl.uniform2iv( this.addr, v );
  10908. }
  10909. function setValueV3iArray( gl, v ) {
  10910. gl.uniform3iv( this.addr, v );
  10911. }
  10912. function setValueV4iArray( gl, v ) {
  10913. gl.uniform4iv( this.addr, v );
  10914. }
  10915. // Array of unsigned integer
  10916. function setValueV1uiArray( gl, v ) {
  10917. gl.uniform1uiv( this.addr, v );
  10918. }
  10919. // Array of unsigned integer vectors (from flat array)
  10920. function setValueV2uiArray( gl, v ) {
  10921. gl.uniform2uiv( this.addr, v );
  10922. }
  10923. function setValueV3uiArray( gl, v ) {
  10924. gl.uniform3uiv( this.addr, v );
  10925. }
  10926. function setValueV4uiArray( gl, v ) {
  10927. gl.uniform4uiv( this.addr, v );
  10928. }
  10929. // Array of textures (2D / 3D / Cube / 2DArray)
  10930. function setValueT1Array( gl, v, textures ) {
  10931. const cache = this.cache;
  10932. const n = v.length;
  10933. const units = allocTexUnits( textures, n );
  10934. if ( ! arraysEqual( cache, units ) ) {
  10935. gl.uniform1iv( this.addr, units );
  10936. copyArray( cache, units );
  10937. }
  10938. for ( let i = 0; i !== n; ++ i ) {
  10939. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  10940. }
  10941. }
  10942. function setValueT3DArray( gl, v, textures ) {
  10943. const cache = this.cache;
  10944. const n = v.length;
  10945. const units = allocTexUnits( textures, n );
  10946. if ( ! arraysEqual( cache, units ) ) {
  10947. gl.uniform1iv( this.addr, units );
  10948. copyArray( cache, units );
  10949. }
  10950. for ( let i = 0; i !== n; ++ i ) {
  10951. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  10952. }
  10953. }
  10954. function setValueT6Array( gl, v, textures ) {
  10955. const cache = this.cache;
  10956. const n = v.length;
  10957. const units = allocTexUnits( textures, n );
  10958. if ( ! arraysEqual( cache, units ) ) {
  10959. gl.uniform1iv( this.addr, units );
  10960. copyArray( cache, units );
  10961. }
  10962. for ( let i = 0; i !== n; ++ i ) {
  10963. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  10964. }
  10965. }
  10966. function setValueT2DArrayArray( gl, v, textures ) {
  10967. const cache = this.cache;
  10968. const n = v.length;
  10969. const units = allocTexUnits( textures, n );
  10970. if ( ! arraysEqual( cache, units ) ) {
  10971. gl.uniform1iv( this.addr, units );
  10972. copyArray( cache, units );
  10973. }
  10974. for ( let i = 0; i !== n; ++ i ) {
  10975. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  10976. }
  10977. }
  10978. // Helper to pick the right setter for a pure (bottom-level) array
  10979. function getPureArraySetter( type ) {
  10980. switch ( type ) {
  10981. case 0x1406: return setValueV1fArray; // FLOAT
  10982. case 0x8b50: return setValueV2fArray; // _VEC2
  10983. case 0x8b51: return setValueV3fArray; // _VEC3
  10984. case 0x8b52: return setValueV4fArray; // _VEC4
  10985. case 0x8b5a: return setValueM2Array; // _MAT2
  10986. case 0x8b5b: return setValueM3Array; // _MAT3
  10987. case 0x8b5c: return setValueM4Array; // _MAT4
  10988. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  10989. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  10990. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  10991. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  10992. case 0x1405: return setValueV1uiArray; // UINT
  10993. case 0x8dc6: return setValueV2uiArray; // _VEC2
  10994. case 0x8dc7: return setValueV3uiArray; // _VEC3
  10995. case 0x8dc8: return setValueV4uiArray; // _VEC4
  10996. case 0x8b5e: // SAMPLER_2D
  10997. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10998. case 0x8dca: // INT_SAMPLER_2D
  10999. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  11000. case 0x8b62: // SAMPLER_2D_SHADOW
  11001. return setValueT1Array;
  11002. case 0x8b5f: // SAMPLER_3D
  11003. case 0x8dcb: // INT_SAMPLER_3D
  11004. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  11005. return setValueT3DArray;
  11006. case 0x8b60: // SAMPLER_CUBE
  11007. case 0x8dcc: // INT_SAMPLER_CUBE
  11008. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  11009. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  11010. return setValueT6Array;
  11011. case 0x8dc1: // SAMPLER_2D_ARRAY
  11012. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  11013. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  11014. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  11015. return setValueT2DArrayArray;
  11016. }
  11017. }
  11018. // --- Uniform Classes ---
  11019. class SingleUniform {
  11020. constructor( id, activeInfo, addr ) {
  11021. this.id = id;
  11022. this.addr = addr;
  11023. this.cache = [];
  11024. this.setValue = getSingularSetter( activeInfo.type );
  11025. // this.path = activeInfo.name; // DEBUG
  11026. }
  11027. }
  11028. class PureArrayUniform {
  11029. constructor( id, activeInfo, addr ) {
  11030. this.id = id;
  11031. this.addr = addr;
  11032. this.cache = [];
  11033. this.size = activeInfo.size;
  11034. this.setValue = getPureArraySetter( activeInfo.type );
  11035. // this.path = activeInfo.name; // DEBUG
  11036. }
  11037. }
  11038. class StructuredUniform {
  11039. constructor( id ) {
  11040. this.id = id;
  11041. this.seq = [];
  11042. this.map = {};
  11043. }
  11044. setValue( gl, value, textures ) {
  11045. const seq = this.seq;
  11046. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11047. const u = seq[ i ];
  11048. u.setValue( gl, value[ u.id ], textures );
  11049. }
  11050. }
  11051. }
  11052. // --- Top-level ---
  11053. // Parser - builds up the property tree from the path strings
  11054. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  11055. // extracts
  11056. // - the identifier (member name or array index)
  11057. // - followed by an optional right bracket (found when array index)
  11058. // - followed by an optional left bracket or dot (type of subscript)
  11059. //
  11060. // Note: These portions can be read in a non-overlapping fashion and
  11061. // allow straightforward parsing of the hierarchy that WebGL encodes
  11062. // in the uniform names.
  11063. function addUniform( container, uniformObject ) {
  11064. container.seq.push( uniformObject );
  11065. container.map[ uniformObject.id ] = uniformObject;
  11066. }
  11067. function parseUniform( activeInfo, addr, container ) {
  11068. const path = activeInfo.name,
  11069. pathLength = path.length;
  11070. // reset RegExp object, because of the early exit of a previous run
  11071. RePathPart.lastIndex = 0;
  11072. while ( true ) {
  11073. const match = RePathPart.exec( path ),
  11074. matchEnd = RePathPart.lastIndex;
  11075. let id = match[ 1 ];
  11076. const idIsIndex = match[ 2 ] === ']',
  11077. subscript = match[ 3 ];
  11078. if ( idIsIndex ) id = id | 0; // convert to integer
  11079. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  11080. // bare name or "pure" bottom-level array "[0]" suffix
  11081. addUniform( container, subscript === undefined ?
  11082. new SingleUniform( id, activeInfo, addr ) :
  11083. new PureArrayUniform( id, activeInfo, addr ) );
  11084. break;
  11085. } else {
  11086. // step into inner node / create it in case it doesn't exist
  11087. const map = container.map;
  11088. let next = map[ id ];
  11089. if ( next === undefined ) {
  11090. next = new StructuredUniform( id );
  11091. addUniform( container, next );
  11092. }
  11093. container = next;
  11094. }
  11095. }
  11096. }
  11097. // Root Container
  11098. class WebGLUniforms {
  11099. constructor( gl, program ) {
  11100. this.seq = [];
  11101. this.map = {};
  11102. const n = gl.getProgramParameter( program, 35718 );
  11103. for ( let i = 0; i < n; ++ i ) {
  11104. const info = gl.getActiveUniform( program, i ),
  11105. addr = gl.getUniformLocation( program, info.name );
  11106. parseUniform( info, addr, this );
  11107. }
  11108. }
  11109. setValue( gl, name, value, textures ) {
  11110. const u = this.map[ name ];
  11111. if ( u !== undefined ) u.setValue( gl, value, textures );
  11112. }
  11113. setOptional( gl, object, name ) {
  11114. const v = object[ name ];
  11115. if ( v !== undefined ) this.setValue( gl, name, v );
  11116. }
  11117. static upload( gl, seq, values, textures ) {
  11118. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11119. const u = seq[ i ],
  11120. v = values[ u.id ];
  11121. if ( v.needsUpdate !== false ) {
  11122. // note: always updating when .needsUpdate is undefined
  11123. u.setValue( gl, v.value, textures );
  11124. }
  11125. }
  11126. }
  11127. static seqWithValue( seq, values ) {
  11128. const r = [];
  11129. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  11130. const u = seq[ i ];
  11131. if ( u.id in values ) r.push( u );
  11132. }
  11133. return r;
  11134. }
  11135. }
  11136. function WebGLShader( gl, type, string ) {
  11137. const shader = gl.createShader( type );
  11138. gl.shaderSource( shader, string );
  11139. gl.compileShader( shader );
  11140. return shader;
  11141. }
  11142. let programIdCount = 0;
  11143. function handleSource( string, errorLine ) {
  11144. const lines = string.split( '\n' );
  11145. const lines2 = [];
  11146. const from = Math.max( errorLine - 6, 0 );
  11147. const to = Math.min( errorLine + 6, lines.length );
  11148. for ( let i = from; i < to; i ++ ) {
  11149. const line = i + 1;
  11150. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  11151. }
  11152. return lines2.join( '\n' );
  11153. }
  11154. function getEncodingComponents( encoding ) {
  11155. switch ( encoding ) {
  11156. case LinearEncoding:
  11157. return [ 'Linear', '( value )' ];
  11158. case sRGBEncoding:
  11159. return [ 'sRGB', '( value )' ];
  11160. default:
  11161. console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding );
  11162. return [ 'Linear', '( value )' ];
  11163. }
  11164. }
  11165. function getShaderErrors( gl, shader, type ) {
  11166. const status = gl.getShaderParameter( shader, 35713 );
  11167. const errors = gl.getShaderInfoLog( shader ).trim();
  11168. if ( status && errors === '' ) return '';
  11169. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  11170. if ( errorMatches ) {
  11171. // --enable-privileged-webgl-extension
  11172. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  11173. const errorLine = parseInt( errorMatches[ 1 ] );
  11174. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  11175. } else {
  11176. return errors;
  11177. }
  11178. }
  11179. function getTexelEncodingFunction( functionName, encoding ) {
  11180. const components = getEncodingComponents( encoding );
  11181. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  11182. }
  11183. function getToneMappingFunction( functionName, toneMapping ) {
  11184. let toneMappingName;
  11185. switch ( toneMapping ) {
  11186. case LinearToneMapping:
  11187. toneMappingName = 'Linear';
  11188. break;
  11189. case ReinhardToneMapping:
  11190. toneMappingName = 'Reinhard';
  11191. break;
  11192. case CineonToneMapping:
  11193. toneMappingName = 'OptimizedCineon';
  11194. break;
  11195. case ACESFilmicToneMapping:
  11196. toneMappingName = 'ACESFilmic';
  11197. break;
  11198. case CustomToneMapping:
  11199. toneMappingName = 'Custom';
  11200. break;
  11201. default:
  11202. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  11203. toneMappingName = 'Linear';
  11204. }
  11205. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  11206. }
  11207. function generateExtensions( parameters ) {
  11208. const chunks = [
  11209. ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  11210. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  11211. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  11212. ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  11213. ];
  11214. return chunks.filter( filterEmptyLine ).join( '\n' );
  11215. }
  11216. function generateDefines( defines ) {
  11217. const chunks = [];
  11218. for ( const name in defines ) {
  11219. const value = defines[ name ];
  11220. if ( value === false ) continue;
  11221. chunks.push( '#define ' + name + ' ' + value );
  11222. }
  11223. return chunks.join( '\n' );
  11224. }
  11225. function fetchAttributeLocations( gl, program ) {
  11226. const attributes = {};
  11227. const n = gl.getProgramParameter( program, 35721 );
  11228. for ( let i = 0; i < n; i ++ ) {
  11229. const info = gl.getActiveAttrib( program, i );
  11230. const name = info.name;
  11231. let locationSize = 1;
  11232. if ( info.type === 35674 ) locationSize = 2;
  11233. if ( info.type === 35675 ) locationSize = 3;
  11234. if ( info.type === 35676 ) locationSize = 4;
  11235. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  11236. attributes[ name ] = {
  11237. type: info.type,
  11238. location: gl.getAttribLocation( program, name ),
  11239. locationSize: locationSize
  11240. };
  11241. }
  11242. return attributes;
  11243. }
  11244. function filterEmptyLine( string ) {
  11245. return string !== '';
  11246. }
  11247. function replaceLightNums( string, parameters ) {
  11248. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  11249. return string
  11250. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  11251. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  11252. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  11253. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  11254. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  11255. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  11256. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  11257. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  11258. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  11259. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  11260. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  11261. }
  11262. function replaceClippingPlaneNums( string, parameters ) {
  11263. return string
  11264. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  11265. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  11266. }
  11267. // Resolve Includes
  11268. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  11269. function resolveIncludes( string ) {
  11270. return string.replace( includePattern, includeReplacer );
  11271. }
  11272. function includeReplacer( match, include ) {
  11273. const string = ShaderChunk[ include ];
  11274. if ( string === undefined ) {
  11275. throw new Error( 'Can not resolve #include <' + include + '>' );
  11276. }
  11277. return resolveIncludes( string );
  11278. }
  11279. // Unroll Loops
  11280. 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;
  11281. function unrollLoops( string ) {
  11282. return string.replace( unrollLoopPattern, loopReplacer );
  11283. }
  11284. function loopReplacer( match, start, end, snippet ) {
  11285. let string = '';
  11286. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  11287. string += snippet
  11288. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  11289. .replace( /UNROLLED_LOOP_INDEX/g, i );
  11290. }
  11291. return string;
  11292. }
  11293. //
  11294. function generatePrecision( parameters ) {
  11295. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  11296. if ( parameters.precision === 'highp' ) {
  11297. precisionstring += '\n#define HIGH_PRECISION';
  11298. } else if ( parameters.precision === 'mediump' ) {
  11299. precisionstring += '\n#define MEDIUM_PRECISION';
  11300. } else if ( parameters.precision === 'lowp' ) {
  11301. precisionstring += '\n#define LOW_PRECISION';
  11302. }
  11303. return precisionstring;
  11304. }
  11305. function generateShadowMapTypeDefine( parameters ) {
  11306. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  11307. if ( parameters.shadowMapType === PCFShadowMap ) {
  11308. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  11309. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  11310. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  11311. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  11312. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  11313. }
  11314. return shadowMapTypeDefine;
  11315. }
  11316. function generateEnvMapTypeDefine( parameters ) {
  11317. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11318. if ( parameters.envMap ) {
  11319. switch ( parameters.envMapMode ) {
  11320. case CubeReflectionMapping:
  11321. case CubeRefractionMapping:
  11322. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  11323. break;
  11324. case CubeUVReflectionMapping:
  11325. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  11326. break;
  11327. }
  11328. }
  11329. return envMapTypeDefine;
  11330. }
  11331. function generateEnvMapModeDefine( parameters ) {
  11332. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  11333. if ( parameters.envMap ) {
  11334. switch ( parameters.envMapMode ) {
  11335. case CubeRefractionMapping:
  11336. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  11337. break;
  11338. }
  11339. }
  11340. return envMapModeDefine;
  11341. }
  11342. function generateEnvMapBlendingDefine( parameters ) {
  11343. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11344. if ( parameters.envMap ) {
  11345. switch ( parameters.combine ) {
  11346. case MultiplyOperation:
  11347. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11348. break;
  11349. case MixOperation:
  11350. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11351. break;
  11352. case AddOperation:
  11353. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11354. break;
  11355. }
  11356. }
  11357. return envMapBlendingDefine;
  11358. }
  11359. function generateCubeUVSize( parameters ) {
  11360. const imageHeight = parameters.envMapCubeUVHeight;
  11361. if ( imageHeight === null ) return null;
  11362. const maxMip = Math.log2( imageHeight ) - 2;
  11363. const texelHeight = 1.0 / imageHeight;
  11364. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  11365. return { texelWidth, texelHeight, maxMip };
  11366. }
  11367. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  11368. // TODO Send this event to Three.js DevTools
  11369. // console.log( 'WebGLProgram', cacheKey );
  11370. const gl = renderer.getContext();
  11371. const defines = parameters.defines;
  11372. let vertexShader = parameters.vertexShader;
  11373. let fragmentShader = parameters.fragmentShader;
  11374. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  11375. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  11376. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  11377. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  11378. const envMapCubeUVSize = generateCubeUVSize( parameters );
  11379. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  11380. const customDefines = generateDefines( defines );
  11381. const program = gl.createProgram();
  11382. let prefixVertex, prefixFragment;
  11383. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11384. if ( parameters.isRawShaderMaterial ) {
  11385. prefixVertex = [
  11386. customDefines
  11387. ].filter( filterEmptyLine ).join( '\n' );
  11388. if ( prefixVertex.length > 0 ) {
  11389. prefixVertex += '\n';
  11390. }
  11391. prefixFragment = [
  11392. customExtensions,
  11393. customDefines
  11394. ].filter( filterEmptyLine ).join( '\n' );
  11395. if ( prefixFragment.length > 0 ) {
  11396. prefixFragment += '\n';
  11397. }
  11398. } else {
  11399. prefixVertex = [
  11400. generatePrecision( parameters ),
  11401. '#define SHADER_NAME ' + parameters.shaderName,
  11402. customDefines,
  11403. parameters.instancing ? '#define USE_INSTANCING' : '',
  11404. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  11405. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  11406. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11407. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11408. parameters.map ? '#define USE_MAP' : '',
  11409. parameters.envMap ? '#define USE_ENVMAP' : '',
  11410. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11411. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11412. parameters.aoMap ? '#define USE_AOMAP' : '',
  11413. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11414. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11415. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11416. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11417. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11418. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11419. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11420. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11421. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11422. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11423. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  11424. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11425. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  11426. parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '',
  11427. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11428. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11429. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11430. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11431. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11432. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11433. parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '',
  11434. parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '',
  11435. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11436. parameters.vertexColors ? '#define USE_COLOR' : '',
  11437. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11438. parameters.vertexUvs ? '#define USE_UV' : '',
  11439. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11440. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11441. parameters.skinning ? '#define USE_SKINNING' : '',
  11442. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  11443. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  11444. ( parameters.morphColors && parameters.isWebGL2 ) ? '#define USE_MORPHCOLORS' : '',
  11445. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE' : '',
  11446. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  11447. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  11448. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11449. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11450. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11451. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11452. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  11453. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11454. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11455. 'uniform mat4 modelMatrix;',
  11456. 'uniform mat4 modelViewMatrix;',
  11457. 'uniform mat4 projectionMatrix;',
  11458. 'uniform mat4 viewMatrix;',
  11459. 'uniform mat3 normalMatrix;',
  11460. 'uniform vec3 cameraPosition;',
  11461. 'uniform bool isOrthographic;',
  11462. '#ifdef USE_INSTANCING',
  11463. ' attribute mat4 instanceMatrix;',
  11464. '#endif',
  11465. '#ifdef USE_INSTANCING_COLOR',
  11466. ' attribute vec3 instanceColor;',
  11467. '#endif',
  11468. 'attribute vec3 position;',
  11469. 'attribute vec3 normal;',
  11470. 'attribute vec2 uv;',
  11471. '#ifdef USE_TANGENT',
  11472. ' attribute vec4 tangent;',
  11473. '#endif',
  11474. '#if defined( USE_COLOR_ALPHA )',
  11475. ' attribute vec4 color;',
  11476. '#elif defined( USE_COLOR )',
  11477. ' attribute vec3 color;',
  11478. '#endif',
  11479. '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )',
  11480. ' attribute vec3 morphTarget0;',
  11481. ' attribute vec3 morphTarget1;',
  11482. ' attribute vec3 morphTarget2;',
  11483. ' attribute vec3 morphTarget3;',
  11484. ' #ifdef USE_MORPHNORMALS',
  11485. ' attribute vec3 morphNormal0;',
  11486. ' attribute vec3 morphNormal1;',
  11487. ' attribute vec3 morphNormal2;',
  11488. ' attribute vec3 morphNormal3;',
  11489. ' #else',
  11490. ' attribute vec3 morphTarget4;',
  11491. ' attribute vec3 morphTarget5;',
  11492. ' attribute vec3 morphTarget6;',
  11493. ' attribute vec3 morphTarget7;',
  11494. ' #endif',
  11495. '#endif',
  11496. '#ifdef USE_SKINNING',
  11497. ' attribute vec4 skinIndex;',
  11498. ' attribute vec4 skinWeight;',
  11499. '#endif',
  11500. '\n'
  11501. ].filter( filterEmptyLine ).join( '\n' );
  11502. prefixFragment = [
  11503. customExtensions,
  11504. generatePrecision( parameters ),
  11505. '#define SHADER_NAME ' + parameters.shaderName,
  11506. customDefines,
  11507. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11508. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11509. parameters.map ? '#define USE_MAP' : '',
  11510. parameters.matcap ? '#define USE_MATCAP' : '',
  11511. parameters.envMap ? '#define USE_ENVMAP' : '',
  11512. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  11513. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11514. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  11515. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  11516. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  11517. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  11518. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11519. parameters.aoMap ? '#define USE_AOMAP' : '',
  11520. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11521. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11522. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11523. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11524. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11525. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  11526. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11527. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11528. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11529. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  11530. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11531. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11532. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11533. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  11534. parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '',
  11535. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11536. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11537. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11538. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  11539. parameters.sheen ? '#define USE_SHEEN' : '',
  11540. parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '',
  11541. parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '',
  11542. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11543. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11544. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11545. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  11546. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11547. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  11548. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11549. parameters.vertexUvs ? '#define USE_UV' : '',
  11550. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11551. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  11552. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11553. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11554. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11555. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11556. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11557. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  11558. parameters.useLegacyLights ? '#define LEGACY_LIGHTS' : '',
  11559. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11560. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11561. 'uniform mat4 viewMatrix;',
  11562. 'uniform vec3 cameraPosition;',
  11563. 'uniform bool isOrthographic;',
  11564. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  11565. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  11566. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  11567. parameters.dithering ? '#define DITHERING' : '',
  11568. parameters.opaque ? '#define OPAQUE' : '',
  11569. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  11570. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
  11571. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  11572. '\n'
  11573. ].filter( filterEmptyLine ).join( '\n' );
  11574. }
  11575. vertexShader = resolveIncludes( vertexShader );
  11576. vertexShader = replaceLightNums( vertexShader, parameters );
  11577. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  11578. fragmentShader = resolveIncludes( fragmentShader );
  11579. fragmentShader = replaceLightNums( fragmentShader, parameters );
  11580. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  11581. vertexShader = unrollLoops( vertexShader );
  11582. fragmentShader = unrollLoops( fragmentShader );
  11583. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  11584. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11585. versionString = '#version 300 es\n';
  11586. prefixVertex = [
  11587. 'precision mediump sampler2DArray;',
  11588. '#define attribute in',
  11589. '#define varying out',
  11590. '#define texture2D texture'
  11591. ].join( '\n' ) + '\n' + prefixVertex;
  11592. prefixFragment = [
  11593. '#define varying in',
  11594. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  11595. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  11596. '#define gl_FragDepthEXT gl_FragDepth',
  11597. '#define texture2D texture',
  11598. '#define textureCube texture',
  11599. '#define texture2DProj textureProj',
  11600. '#define texture2DLodEXT textureLod',
  11601. '#define texture2DProjLodEXT textureProjLod',
  11602. '#define textureCubeLodEXT textureLod',
  11603. '#define texture2DGradEXT textureGrad',
  11604. '#define texture2DProjGradEXT textureProjGrad',
  11605. '#define textureCubeGradEXT textureGrad'
  11606. ].join( '\n' ) + '\n' + prefixFragment;
  11607. }
  11608. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11609. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  11610. // console.log( '*VERTEX*', vertexGlsl );
  11611. // console.log( '*FRAGMENT*', fragmentGlsl );
  11612. const glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
  11613. const glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
  11614. gl.attachShader( program, glVertexShader );
  11615. gl.attachShader( program, glFragmentShader );
  11616. // Force a particular attribute to index 0.
  11617. if ( parameters.index0AttributeName !== undefined ) {
  11618. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  11619. } else if ( parameters.morphTargets === true ) {
  11620. // programs with morphTargets displace position out of attribute 0
  11621. gl.bindAttribLocation( program, 0, 'position' );
  11622. }
  11623. gl.linkProgram( program );
  11624. // check for link errors
  11625. if ( renderer.debug.checkShaderErrors ) {
  11626. const programLog = gl.getProgramInfoLog( program ).trim();
  11627. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  11628. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  11629. let runnable = true;
  11630. let haveDiagnostics = true;
  11631. if ( gl.getProgramParameter( program, 35714 ) === false ) {
  11632. runnable = false;
  11633. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  11634. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  11635. console.error(
  11636. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  11637. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, 35715 ) + '\n\n' +
  11638. 'Program Info Log: ' + programLog + '\n' +
  11639. vertexErrors + '\n' +
  11640. fragmentErrors
  11641. );
  11642. } else if ( programLog !== '' ) {
  11643. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  11644. } else if ( vertexLog === '' || fragmentLog === '' ) {
  11645. haveDiagnostics = false;
  11646. }
  11647. if ( haveDiagnostics ) {
  11648. this.diagnostics = {
  11649. runnable: runnable,
  11650. programLog: programLog,
  11651. vertexShader: {
  11652. log: vertexLog,
  11653. prefix: prefixVertex
  11654. },
  11655. fragmentShader: {
  11656. log: fragmentLog,
  11657. prefix: prefixFragment
  11658. }
  11659. };
  11660. }
  11661. }
  11662. // Clean up
  11663. // Crashes in iOS9 and iOS10. #18402
  11664. // gl.detachShader( program, glVertexShader );
  11665. // gl.detachShader( program, glFragmentShader );
  11666. gl.deleteShader( glVertexShader );
  11667. gl.deleteShader( glFragmentShader );
  11668. // set up caching for uniform locations
  11669. let cachedUniforms;
  11670. this.getUniforms = function () {
  11671. if ( cachedUniforms === undefined ) {
  11672. cachedUniforms = new WebGLUniforms( gl, program );
  11673. }
  11674. return cachedUniforms;
  11675. };
  11676. // set up caching for attribute locations
  11677. let cachedAttributes;
  11678. this.getAttributes = function () {
  11679. if ( cachedAttributes === undefined ) {
  11680. cachedAttributes = fetchAttributeLocations( gl, program );
  11681. }
  11682. return cachedAttributes;
  11683. };
  11684. // free resource
  11685. this.destroy = function () {
  11686. bindingStates.releaseStatesOfProgram( this );
  11687. gl.deleteProgram( program );
  11688. this.program = undefined;
  11689. };
  11690. //
  11691. this.name = parameters.shaderName;
  11692. this.id = programIdCount ++;
  11693. this.cacheKey = cacheKey;
  11694. this.usedTimes = 1;
  11695. this.program = program;
  11696. this.vertexShader = glVertexShader;
  11697. this.fragmentShader = glFragmentShader;
  11698. return this;
  11699. }
  11700. let _id = 0;
  11701. class WebGLShaderCache {
  11702. constructor() {
  11703. this.shaderCache = new Map();
  11704. this.materialCache = new Map();
  11705. }
  11706. update( material ) {
  11707. const vertexShader = material.vertexShader;
  11708. const fragmentShader = material.fragmentShader;
  11709. const vertexShaderStage = this._getShaderStage( vertexShader );
  11710. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  11711. const materialShaders = this._getShaderCacheForMaterial( material );
  11712. if ( materialShaders.has( vertexShaderStage ) === false ) {
  11713. materialShaders.add( vertexShaderStage );
  11714. vertexShaderStage.usedTimes ++;
  11715. }
  11716. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  11717. materialShaders.add( fragmentShaderStage );
  11718. fragmentShaderStage.usedTimes ++;
  11719. }
  11720. return this;
  11721. }
  11722. remove( material ) {
  11723. const materialShaders = this.materialCache.get( material );
  11724. for ( const shaderStage of materialShaders ) {
  11725. shaderStage.usedTimes --;
  11726. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  11727. }
  11728. this.materialCache.delete( material );
  11729. return this;
  11730. }
  11731. getVertexShaderID( material ) {
  11732. return this._getShaderStage( material.vertexShader ).id;
  11733. }
  11734. getFragmentShaderID( material ) {
  11735. return this._getShaderStage( material.fragmentShader ).id;
  11736. }
  11737. dispose() {
  11738. this.shaderCache.clear();
  11739. this.materialCache.clear();
  11740. }
  11741. _getShaderCacheForMaterial( material ) {
  11742. const cache = this.materialCache;
  11743. let set = cache.get( material );
  11744. if ( set === undefined ) {
  11745. set = new Set();
  11746. cache.set( material, set );
  11747. }
  11748. return set;
  11749. }
  11750. _getShaderStage( code ) {
  11751. const cache = this.shaderCache;
  11752. let stage = cache.get( code );
  11753. if ( stage === undefined ) {
  11754. stage = new WebGLShaderStage( code );
  11755. cache.set( code, stage );
  11756. }
  11757. return stage;
  11758. }
  11759. }
  11760. class WebGLShaderStage {
  11761. constructor( code ) {
  11762. this.id = _id ++;
  11763. this.code = code;
  11764. this.usedTimes = 0;
  11765. }
  11766. }
  11767. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  11768. const _programLayers = new Layers();
  11769. const _customShaders = new WebGLShaderCache();
  11770. const programs = [];
  11771. const isWebGL2 = capabilities.isWebGL2;
  11772. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11773. const vertexTextures = capabilities.vertexTextures;
  11774. let precision = capabilities.precision;
  11775. const shaderIDs = {
  11776. MeshDepthMaterial: 'depth',
  11777. MeshDistanceMaterial: 'distanceRGBA',
  11778. MeshNormalMaterial: 'normal',
  11779. MeshBasicMaterial: 'basic',
  11780. MeshLambertMaterial: 'lambert',
  11781. MeshPhongMaterial: 'phong',
  11782. MeshToonMaterial: 'toon',
  11783. MeshStandardMaterial: 'physical',
  11784. MeshPhysicalMaterial: 'physical',
  11785. MeshMatcapMaterial: 'matcap',
  11786. LineBasicMaterial: 'basic',
  11787. LineDashedMaterial: 'dashed',
  11788. PointsMaterial: 'points',
  11789. ShadowMaterial: 'shadow',
  11790. SpriteMaterial: 'sprite'
  11791. };
  11792. function getParameters( material, lights, shadows, scene, object ) {
  11793. const fog = scene.fog;
  11794. const geometry = object.geometry;
  11795. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11796. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  11797. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  11798. const shaderID = shaderIDs[ material.type ];
  11799. // heuristics to create shader parameters according to lights in the scene
  11800. // (not to blow over maxLights budget)
  11801. if ( material.precision !== null ) {
  11802. precision = capabilities.getMaxPrecision( material.precision );
  11803. if ( precision !== material.precision ) {
  11804. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  11805. }
  11806. }
  11807. //
  11808. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11809. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11810. let morphTextureStride = 0;
  11811. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  11812. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  11813. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  11814. //
  11815. let vertexShader, fragmentShader;
  11816. let customVertexShaderID, customFragmentShaderID;
  11817. if ( shaderID ) {
  11818. const shader = ShaderLib[ shaderID ];
  11819. vertexShader = shader.vertexShader;
  11820. fragmentShader = shader.fragmentShader;
  11821. } else {
  11822. vertexShader = material.vertexShader;
  11823. fragmentShader = material.fragmentShader;
  11824. _customShaders.update( material );
  11825. customVertexShaderID = _customShaders.getVertexShaderID( material );
  11826. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  11827. }
  11828. const currentRenderTarget = renderer.getRenderTarget();
  11829. const useAlphaTest = material.alphaTest > 0;
  11830. const useClearcoat = material.clearcoat > 0;
  11831. const useIridescence = material.iridescence > 0;
  11832. const parameters = {
  11833. isWebGL2: isWebGL2,
  11834. shaderID: shaderID,
  11835. shaderName: material.type,
  11836. vertexShader: vertexShader,
  11837. fragmentShader: fragmentShader,
  11838. defines: material.defines,
  11839. customVertexShaderID: customVertexShaderID,
  11840. customFragmentShaderID: customFragmentShaderID,
  11841. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11842. glslVersion: material.glslVersion,
  11843. precision: precision,
  11844. instancing: object.isInstancedMesh === true,
  11845. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11846. supportsVertexTextures: vertexTextures,
  11847. outputEncoding: ( currentRenderTarget === null ) ? renderer.outputEncoding : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding ),
  11848. map: !! material.map,
  11849. matcap: !! material.matcap,
  11850. envMap: !! envMap,
  11851. envMapMode: envMap && envMap.mapping,
  11852. envMapCubeUVHeight: envMapCubeUVHeight,
  11853. lightMap: !! material.lightMap,
  11854. aoMap: !! material.aoMap,
  11855. emissiveMap: !! material.emissiveMap,
  11856. bumpMap: !! material.bumpMap,
  11857. normalMap: !! material.normalMap,
  11858. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11859. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11860. decodeVideoTexture: !! material.map && ( material.map.isVideoTexture === true ) && ( material.map.encoding === sRGBEncoding ),
  11861. clearcoat: useClearcoat,
  11862. clearcoatMap: useClearcoat && !! material.clearcoatMap,
  11863. clearcoatRoughnessMap: useClearcoat && !! material.clearcoatRoughnessMap,
  11864. clearcoatNormalMap: useClearcoat && !! material.clearcoatNormalMap,
  11865. iridescence: useIridescence,
  11866. iridescenceMap: useIridescence && !! material.iridescenceMap,
  11867. iridescenceThicknessMap: useIridescence && !! material.iridescenceThicknessMap,
  11868. displacementMap: !! material.displacementMap,
  11869. roughnessMap: !! material.roughnessMap,
  11870. metalnessMap: !! material.metalnessMap,
  11871. specularMap: !! material.specularMap,
  11872. specularIntensityMap: !! material.specularIntensityMap,
  11873. specularColorMap: !! material.specularColorMap,
  11874. opaque: material.transparent === false && material.blending === NormalBlending,
  11875. alphaMap: !! material.alphaMap,
  11876. alphaTest: useAlphaTest,
  11877. gradientMap: !! material.gradientMap,
  11878. sheen: material.sheen > 0,
  11879. sheenColorMap: !! material.sheenColorMap,
  11880. sheenRoughnessMap: !! material.sheenRoughnessMap,
  11881. transmission: material.transmission > 0,
  11882. transmissionMap: !! material.transmissionMap,
  11883. thicknessMap: !! material.thicknessMap,
  11884. combine: material.combine,
  11885. vertexTangents: ( !! material.normalMap && !! geometry.attributes.tangent ),
  11886. vertexColors: material.vertexColors,
  11887. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  11888. vertexUvs: !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatMap || !! material.clearcoatRoughnessMap || !! material.clearcoatNormalMap || !! material.iridescenceMap || !! material.iridescenceThicknessMap || !! material.displacementMap || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || !! material.sheenColorMap || !! material.sheenRoughnessMap,
  11889. uvsVertexOnly: ! ( !! material.map || !! material.bumpMap || !! material.normalMap || !! material.specularMap || !! material.alphaMap || !! material.emissiveMap || !! material.roughnessMap || !! material.metalnessMap || !! material.clearcoatNormalMap || !! material.iridescenceMap || !! material.iridescenceThicknessMap || material.transmission > 0 || !! material.transmissionMap || !! material.thicknessMap || !! material.specularIntensityMap || !! material.specularColorMap || material.sheen > 0 || !! material.sheenColorMap || !! material.sheenRoughnessMap ) && !! material.displacementMap,
  11890. fog: !! fog,
  11891. useFog: material.fog === true,
  11892. fogExp2: ( fog && fog.isFogExp2 ),
  11893. flatShading: !! material.flatShading,
  11894. sizeAttenuation: material.sizeAttenuation,
  11895. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11896. skinning: object.isSkinnedMesh === true,
  11897. morphTargets: geometry.morphAttributes.position !== undefined,
  11898. morphNormals: geometry.morphAttributes.normal !== undefined,
  11899. morphColors: geometry.morphAttributes.color !== undefined,
  11900. morphTargetsCount: morphTargetsCount,
  11901. morphTextureStride: morphTextureStride,
  11902. numDirLights: lights.directional.length,
  11903. numPointLights: lights.point.length,
  11904. numSpotLights: lights.spot.length,
  11905. numSpotLightMaps: lights.spotLightMap.length,
  11906. numRectAreaLights: lights.rectArea.length,
  11907. numHemiLights: lights.hemi.length,
  11908. numDirLightShadows: lights.directionalShadowMap.length,
  11909. numPointLightShadows: lights.pointShadowMap.length,
  11910. numSpotLightShadows: lights.spotShadowMap.length,
  11911. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  11912. numClippingPlanes: clipping.numPlanes,
  11913. numClipIntersection: clipping.numIntersection,
  11914. dithering: material.dithering,
  11915. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11916. shadowMapType: renderer.shadowMap.type,
  11917. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11918. useLegacyLights: renderer.useLegacyLights,
  11919. premultipliedAlpha: material.premultipliedAlpha,
  11920. doubleSided: material.side === DoubleSide,
  11921. flipSided: material.side === BackSide,
  11922. useDepthPacking: !! material.depthPacking,
  11923. depthPacking: material.depthPacking || 0,
  11924. index0AttributeName: material.index0AttributeName,
  11925. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11926. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11927. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11928. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11929. rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ),
  11930. rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  11931. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  11932. customProgramCacheKey: material.customProgramCacheKey()
  11933. };
  11934. return parameters;
  11935. }
  11936. function getProgramCacheKey( parameters ) {
  11937. const array = [];
  11938. if ( parameters.shaderID ) {
  11939. array.push( parameters.shaderID );
  11940. } else {
  11941. array.push( parameters.customVertexShaderID );
  11942. array.push( parameters.customFragmentShaderID );
  11943. }
  11944. if ( parameters.defines !== undefined ) {
  11945. for ( const name in parameters.defines ) {
  11946. array.push( name );
  11947. array.push( parameters.defines[ name ] );
  11948. }
  11949. }
  11950. if ( parameters.isRawShaderMaterial === false ) {
  11951. getProgramCacheKeyParameters( array, parameters );
  11952. getProgramCacheKeyBooleans( array, parameters );
  11953. array.push( renderer.outputEncoding );
  11954. }
  11955. array.push( parameters.customProgramCacheKey );
  11956. return array.join();
  11957. }
  11958. function getProgramCacheKeyParameters( array, parameters ) {
  11959. array.push( parameters.precision );
  11960. array.push( parameters.outputEncoding );
  11961. array.push( parameters.envMapMode );
  11962. array.push( parameters.envMapCubeUVHeight );
  11963. array.push( parameters.combine );
  11964. array.push( parameters.vertexUvs );
  11965. array.push( parameters.fogExp2 );
  11966. array.push( parameters.sizeAttenuation );
  11967. array.push( parameters.morphTargetsCount );
  11968. array.push( parameters.morphAttributeCount );
  11969. array.push( parameters.numDirLights );
  11970. array.push( parameters.numPointLights );
  11971. array.push( parameters.numSpotLights );
  11972. array.push( parameters.numSpotLightMaps );
  11973. array.push( parameters.numHemiLights );
  11974. array.push( parameters.numRectAreaLights );
  11975. array.push( parameters.numDirLightShadows );
  11976. array.push( parameters.numPointLightShadows );
  11977. array.push( parameters.numSpotLightShadows );
  11978. array.push( parameters.numSpotLightShadowsWithMaps );
  11979. array.push( parameters.shadowMapType );
  11980. array.push( parameters.toneMapping );
  11981. array.push( parameters.numClippingPlanes );
  11982. array.push( parameters.numClipIntersection );
  11983. array.push( parameters.depthPacking );
  11984. }
  11985. function getProgramCacheKeyBooleans( array, parameters ) {
  11986. _programLayers.disableAll();
  11987. if ( parameters.isWebGL2 )
  11988. _programLayers.enable( 0 );
  11989. if ( parameters.supportsVertexTextures )
  11990. _programLayers.enable( 1 );
  11991. if ( parameters.instancing )
  11992. _programLayers.enable( 2 );
  11993. if ( parameters.instancingColor )
  11994. _programLayers.enable( 3 );
  11995. if ( parameters.map )
  11996. _programLayers.enable( 4 );
  11997. if ( parameters.matcap )
  11998. _programLayers.enable( 5 );
  11999. if ( parameters.envMap )
  12000. _programLayers.enable( 6 );
  12001. if ( parameters.lightMap )
  12002. _programLayers.enable( 7 );
  12003. if ( parameters.aoMap )
  12004. _programLayers.enable( 8 );
  12005. if ( parameters.emissiveMap )
  12006. _programLayers.enable( 9 );
  12007. if ( parameters.bumpMap )
  12008. _programLayers.enable( 10 );
  12009. if ( parameters.normalMap )
  12010. _programLayers.enable( 11 );
  12011. if ( parameters.objectSpaceNormalMap )
  12012. _programLayers.enable( 12 );
  12013. if ( parameters.tangentSpaceNormalMap )
  12014. _programLayers.enable( 13 );
  12015. if ( parameters.clearcoat )
  12016. _programLayers.enable( 14 );
  12017. if ( parameters.clearcoatMap )
  12018. _programLayers.enable( 15 );
  12019. if ( parameters.clearcoatRoughnessMap )
  12020. _programLayers.enable( 16 );
  12021. if ( parameters.clearcoatNormalMap )
  12022. _programLayers.enable( 17 );
  12023. if ( parameters.iridescence )
  12024. _programLayers.enable( 18 );
  12025. if ( parameters.iridescenceMap )
  12026. _programLayers.enable( 19 );
  12027. if ( parameters.iridescenceThicknessMap )
  12028. _programLayers.enable( 20 );
  12029. if ( parameters.displacementMap )
  12030. _programLayers.enable( 21 );
  12031. if ( parameters.specularMap )
  12032. _programLayers.enable( 22 );
  12033. if ( parameters.roughnessMap )
  12034. _programLayers.enable( 23 );
  12035. if ( parameters.metalnessMap )
  12036. _programLayers.enable( 24 );
  12037. if ( parameters.gradientMap )
  12038. _programLayers.enable( 25 );
  12039. if ( parameters.alphaMap )
  12040. _programLayers.enable( 26 );
  12041. if ( parameters.alphaTest )
  12042. _programLayers.enable( 27 );
  12043. if ( parameters.vertexColors )
  12044. _programLayers.enable( 28 );
  12045. if ( parameters.vertexAlphas )
  12046. _programLayers.enable( 29 );
  12047. if ( parameters.vertexUvs )
  12048. _programLayers.enable( 30 );
  12049. if ( parameters.vertexTangents )
  12050. _programLayers.enable( 31 );
  12051. if ( parameters.uvsVertexOnly )
  12052. _programLayers.enable( 32 );
  12053. array.push( _programLayers.mask );
  12054. _programLayers.disableAll();
  12055. if ( parameters.fog )
  12056. _programLayers.enable( 0 );
  12057. if ( parameters.useFog )
  12058. _programLayers.enable( 1 );
  12059. if ( parameters.flatShading )
  12060. _programLayers.enable( 2 );
  12061. if ( parameters.logarithmicDepthBuffer )
  12062. _programLayers.enable( 3 );
  12063. if ( parameters.skinning )
  12064. _programLayers.enable( 4 );
  12065. if ( parameters.morphTargets )
  12066. _programLayers.enable( 5 );
  12067. if ( parameters.morphNormals )
  12068. _programLayers.enable( 6 );
  12069. if ( parameters.morphColors )
  12070. _programLayers.enable( 7 );
  12071. if ( parameters.premultipliedAlpha )
  12072. _programLayers.enable( 8 );
  12073. if ( parameters.shadowMapEnabled )
  12074. _programLayers.enable( 9 );
  12075. if ( parameters.useLegacyLights )
  12076. _programLayers.enable( 10 );
  12077. if ( parameters.doubleSided )
  12078. _programLayers.enable( 11 );
  12079. if ( parameters.flipSided )
  12080. _programLayers.enable( 12 );
  12081. if ( parameters.useDepthPacking )
  12082. _programLayers.enable( 13 );
  12083. if ( parameters.dithering )
  12084. _programLayers.enable( 14 );
  12085. if ( parameters.specularIntensityMap )
  12086. _programLayers.enable( 15 );
  12087. if ( parameters.specularColorMap )
  12088. _programLayers.enable( 16 );
  12089. if ( parameters.transmission )
  12090. _programLayers.enable( 17 );
  12091. if ( parameters.transmissionMap )
  12092. _programLayers.enable( 18 );
  12093. if ( parameters.thicknessMap )
  12094. _programLayers.enable( 19 );
  12095. if ( parameters.sheen )
  12096. _programLayers.enable( 20 );
  12097. if ( parameters.sheenColorMap )
  12098. _programLayers.enable( 21 );
  12099. if ( parameters.sheenRoughnessMap )
  12100. _programLayers.enable( 22 );
  12101. if ( parameters.decodeVideoTexture )
  12102. _programLayers.enable( 23 );
  12103. if ( parameters.opaque )
  12104. _programLayers.enable( 24 );
  12105. array.push( _programLayers.mask );
  12106. }
  12107. function getUniforms( material ) {
  12108. const shaderID = shaderIDs[ material.type ];
  12109. let uniforms;
  12110. if ( shaderID ) {
  12111. const shader = ShaderLib[ shaderID ];
  12112. uniforms = UniformsUtils.clone( shader.uniforms );
  12113. } else {
  12114. uniforms = material.uniforms;
  12115. }
  12116. return uniforms;
  12117. }
  12118. function acquireProgram( parameters, cacheKey ) {
  12119. let program;
  12120. // Check if code has been already compiled
  12121. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  12122. const preexistingProgram = programs[ p ];
  12123. if ( preexistingProgram.cacheKey === cacheKey ) {
  12124. program = preexistingProgram;
  12125. ++ program.usedTimes;
  12126. break;
  12127. }
  12128. }
  12129. if ( program === undefined ) {
  12130. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  12131. programs.push( program );
  12132. }
  12133. return program;
  12134. }
  12135. function releaseProgram( program ) {
  12136. if ( -- program.usedTimes === 0 ) {
  12137. // Remove from unordered set
  12138. const i = programs.indexOf( program );
  12139. programs[ i ] = programs[ programs.length - 1 ];
  12140. programs.pop();
  12141. // Free WebGL resources
  12142. program.destroy();
  12143. }
  12144. }
  12145. function releaseShaderCache( material ) {
  12146. _customShaders.remove( material );
  12147. }
  12148. function dispose() {
  12149. _customShaders.dispose();
  12150. }
  12151. return {
  12152. getParameters: getParameters,
  12153. getProgramCacheKey: getProgramCacheKey,
  12154. getUniforms: getUniforms,
  12155. acquireProgram: acquireProgram,
  12156. releaseProgram: releaseProgram,
  12157. releaseShaderCache: releaseShaderCache,
  12158. // Exposed for resource monitoring & error feedback via renderer.info:
  12159. programs: programs,
  12160. dispose: dispose
  12161. };
  12162. }
  12163. function WebGLProperties() {
  12164. let properties = new WeakMap();
  12165. function get( object ) {
  12166. let map = properties.get( object );
  12167. if ( map === undefined ) {
  12168. map = {};
  12169. properties.set( object, map );
  12170. }
  12171. return map;
  12172. }
  12173. function remove( object ) {
  12174. properties.delete( object );
  12175. }
  12176. function update( object, key, value ) {
  12177. properties.get( object )[ key ] = value;
  12178. }
  12179. function dispose() {
  12180. properties = new WeakMap();
  12181. }
  12182. return {
  12183. get: get,
  12184. remove: remove,
  12185. update: update,
  12186. dispose: dispose
  12187. };
  12188. }
  12189. function painterSortStable( a, b ) {
  12190. if ( a.groupOrder !== b.groupOrder ) {
  12191. return a.groupOrder - b.groupOrder;
  12192. } else if ( a.renderOrder !== b.renderOrder ) {
  12193. return a.renderOrder - b.renderOrder;
  12194. } else if ( a.material.id !== b.material.id ) {
  12195. return a.material.id - b.material.id;
  12196. } else if ( a.z !== b.z ) {
  12197. return a.z - b.z;
  12198. } else {
  12199. return a.id - b.id;
  12200. }
  12201. }
  12202. function reversePainterSortStable( a, b ) {
  12203. if ( a.groupOrder !== b.groupOrder ) {
  12204. return a.groupOrder - b.groupOrder;
  12205. } else if ( a.renderOrder !== b.renderOrder ) {
  12206. return a.renderOrder - b.renderOrder;
  12207. } else if ( a.z !== b.z ) {
  12208. return b.z - a.z;
  12209. } else {
  12210. return a.id - b.id;
  12211. }
  12212. }
  12213. function WebGLRenderList() {
  12214. const renderItems = [];
  12215. let renderItemsIndex = 0;
  12216. const opaque = [];
  12217. const transmissive = [];
  12218. const transparent = [];
  12219. function init() {
  12220. renderItemsIndex = 0;
  12221. opaque.length = 0;
  12222. transmissive.length = 0;
  12223. transparent.length = 0;
  12224. }
  12225. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  12226. let renderItem = renderItems[ renderItemsIndex ];
  12227. if ( renderItem === undefined ) {
  12228. renderItem = {
  12229. id: object.id,
  12230. object: object,
  12231. geometry: geometry,
  12232. material: material,
  12233. groupOrder: groupOrder,
  12234. renderOrder: object.renderOrder,
  12235. z: z,
  12236. group: group
  12237. };
  12238. renderItems[ renderItemsIndex ] = renderItem;
  12239. } else {
  12240. renderItem.id = object.id;
  12241. renderItem.object = object;
  12242. renderItem.geometry = geometry;
  12243. renderItem.material = material;
  12244. renderItem.groupOrder = groupOrder;
  12245. renderItem.renderOrder = object.renderOrder;
  12246. renderItem.z = z;
  12247. renderItem.group = group;
  12248. }
  12249. renderItemsIndex ++;
  12250. return renderItem;
  12251. }
  12252. function push( object, geometry, material, groupOrder, z, group ) {
  12253. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12254. if ( material.transmission > 0.0 ) {
  12255. transmissive.push( renderItem );
  12256. } else if ( material.transparent === true ) {
  12257. transparent.push( renderItem );
  12258. } else {
  12259. opaque.push( renderItem );
  12260. }
  12261. }
  12262. function unshift( object, geometry, material, groupOrder, z, group ) {
  12263. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  12264. if ( material.transmission > 0.0 ) {
  12265. transmissive.unshift( renderItem );
  12266. } else if ( material.transparent === true ) {
  12267. transparent.unshift( renderItem );
  12268. } else {
  12269. opaque.unshift( renderItem );
  12270. }
  12271. }
  12272. function sort( customOpaqueSort, customTransparentSort ) {
  12273. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  12274. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  12275. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  12276. }
  12277. function finish() {
  12278. // Clear references from inactive renderItems in the list
  12279. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  12280. const renderItem = renderItems[ i ];
  12281. if ( renderItem.id === null ) break;
  12282. renderItem.id = null;
  12283. renderItem.object = null;
  12284. renderItem.geometry = null;
  12285. renderItem.material = null;
  12286. renderItem.group = null;
  12287. }
  12288. }
  12289. return {
  12290. opaque: opaque,
  12291. transmissive: transmissive,
  12292. transparent: transparent,
  12293. init: init,
  12294. push: push,
  12295. unshift: unshift,
  12296. finish: finish,
  12297. sort: sort
  12298. };
  12299. }
  12300. function WebGLRenderLists() {
  12301. let lists = new WeakMap();
  12302. function get( scene, renderCallDepth ) {
  12303. const listArray = lists.get( scene );
  12304. let list;
  12305. if ( listArray === undefined ) {
  12306. list = new WebGLRenderList();
  12307. lists.set( scene, [ list ] );
  12308. } else {
  12309. if ( renderCallDepth >= listArray.length ) {
  12310. list = new WebGLRenderList();
  12311. listArray.push( list );
  12312. } else {
  12313. list = listArray[ renderCallDepth ];
  12314. }
  12315. }
  12316. return list;
  12317. }
  12318. function dispose() {
  12319. lists = new WeakMap();
  12320. }
  12321. return {
  12322. get: get,
  12323. dispose: dispose
  12324. };
  12325. }
  12326. function UniformsCache() {
  12327. const lights = {};
  12328. return {
  12329. get: function ( light ) {
  12330. if ( lights[ light.id ] !== undefined ) {
  12331. return lights[ light.id ];
  12332. }
  12333. let uniforms;
  12334. switch ( light.type ) {
  12335. case 'DirectionalLight':
  12336. uniforms = {
  12337. direction: new Vector3(),
  12338. color: new Color()
  12339. };
  12340. break;
  12341. case 'SpotLight':
  12342. uniforms = {
  12343. position: new Vector3(),
  12344. direction: new Vector3(),
  12345. color: new Color(),
  12346. distance: 0,
  12347. coneCos: 0,
  12348. penumbraCos: 0,
  12349. decay: 0
  12350. };
  12351. break;
  12352. case 'PointLight':
  12353. uniforms = {
  12354. position: new Vector3(),
  12355. color: new Color(),
  12356. distance: 0,
  12357. decay: 0
  12358. };
  12359. break;
  12360. case 'HemisphereLight':
  12361. uniforms = {
  12362. direction: new Vector3(),
  12363. skyColor: new Color(),
  12364. groundColor: new Color()
  12365. };
  12366. break;
  12367. case 'RectAreaLight':
  12368. uniforms = {
  12369. color: new Color(),
  12370. position: new Vector3(),
  12371. halfWidth: new Vector3(),
  12372. halfHeight: new Vector3()
  12373. };
  12374. break;
  12375. }
  12376. lights[ light.id ] = uniforms;
  12377. return uniforms;
  12378. }
  12379. };
  12380. }
  12381. function ShadowUniformsCache() {
  12382. const lights = {};
  12383. return {
  12384. get: function ( light ) {
  12385. if ( lights[ light.id ] !== undefined ) {
  12386. return lights[ light.id ];
  12387. }
  12388. let uniforms;
  12389. switch ( light.type ) {
  12390. case 'DirectionalLight':
  12391. uniforms = {
  12392. shadowBias: 0,
  12393. shadowNormalBias: 0,
  12394. shadowRadius: 1,
  12395. shadowMapSize: new Vector2()
  12396. };
  12397. break;
  12398. case 'SpotLight':
  12399. uniforms = {
  12400. shadowBias: 0,
  12401. shadowNormalBias: 0,
  12402. shadowRadius: 1,
  12403. shadowMapSize: new Vector2()
  12404. };
  12405. break;
  12406. case 'PointLight':
  12407. uniforms = {
  12408. shadowBias: 0,
  12409. shadowNormalBias: 0,
  12410. shadowRadius: 1,
  12411. shadowMapSize: new Vector2(),
  12412. shadowCameraNear: 1,
  12413. shadowCameraFar: 1000
  12414. };
  12415. break;
  12416. // TODO (abelnation): set RectAreaLight shadow uniforms
  12417. }
  12418. lights[ light.id ] = uniforms;
  12419. return uniforms;
  12420. }
  12421. };
  12422. }
  12423. let nextVersion = 0;
  12424. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  12425. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  12426. }
  12427. function WebGLLights( extensions, capabilities ) {
  12428. const cache = new UniformsCache();
  12429. const shadowCache = ShadowUniformsCache();
  12430. const state = {
  12431. version: 0,
  12432. hash: {
  12433. directionalLength: - 1,
  12434. pointLength: - 1,
  12435. spotLength: - 1,
  12436. rectAreaLength: - 1,
  12437. hemiLength: - 1,
  12438. numDirectionalShadows: - 1,
  12439. numPointShadows: - 1,
  12440. numSpotShadows: - 1,
  12441. numSpotMaps: - 1
  12442. },
  12443. ambient: [ 0, 0, 0 ],
  12444. probe: [],
  12445. directional: [],
  12446. directionalShadow: [],
  12447. directionalShadowMap: [],
  12448. directionalShadowMatrix: [],
  12449. spot: [],
  12450. spotLightMap: [],
  12451. spotShadow: [],
  12452. spotShadowMap: [],
  12453. spotLightMatrix: [],
  12454. rectArea: [],
  12455. rectAreaLTC1: null,
  12456. rectAreaLTC2: null,
  12457. point: [],
  12458. pointShadow: [],
  12459. pointShadowMap: [],
  12460. pointShadowMatrix: [],
  12461. hemi: [],
  12462. numSpotLightShadowsWithMaps: 0
  12463. };
  12464. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  12465. const vector3 = new Vector3();
  12466. const matrix4 = new Matrix4();
  12467. const matrix42 = new Matrix4();
  12468. function setup( lights, useLegacyLights ) {
  12469. let r = 0, g = 0, b = 0;
  12470. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  12471. let directionalLength = 0;
  12472. let pointLength = 0;
  12473. let spotLength = 0;
  12474. let rectAreaLength = 0;
  12475. let hemiLength = 0;
  12476. let numDirectionalShadows = 0;
  12477. let numPointShadows = 0;
  12478. let numSpotShadows = 0;
  12479. let numSpotMaps = 0;
  12480. let numSpotShadowsWithMaps = 0;
  12481. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  12482. lights.sort( shadowCastingAndTexturingLightsFirst );
  12483. // artist-friendly light intensity scaling factor
  12484. const scaleFactor = ( useLegacyLights === true ) ? Math.PI : 1;
  12485. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12486. const light = lights[ i ];
  12487. const color = light.color;
  12488. const intensity = light.intensity;
  12489. const distance = light.distance;
  12490. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12491. if ( light.isAmbientLight ) {
  12492. r += color.r * intensity * scaleFactor;
  12493. g += color.g * intensity * scaleFactor;
  12494. b += color.b * intensity * scaleFactor;
  12495. } else if ( light.isLightProbe ) {
  12496. for ( let j = 0; j < 9; j ++ ) {
  12497. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  12498. }
  12499. } else if ( light.isDirectionalLight ) {
  12500. const uniforms = cache.get( light );
  12501. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12502. if ( light.castShadow ) {
  12503. const shadow = light.shadow;
  12504. const shadowUniforms = shadowCache.get( light );
  12505. shadowUniforms.shadowBias = shadow.bias;
  12506. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12507. shadowUniforms.shadowRadius = shadow.radius;
  12508. shadowUniforms.shadowMapSize = shadow.mapSize;
  12509. state.directionalShadow[ directionalLength ] = shadowUniforms;
  12510. state.directionalShadowMap[ directionalLength ] = shadowMap;
  12511. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  12512. numDirectionalShadows ++;
  12513. }
  12514. state.directional[ directionalLength ] = uniforms;
  12515. directionalLength ++;
  12516. } else if ( light.isSpotLight ) {
  12517. const uniforms = cache.get( light );
  12518. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12519. uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor );
  12520. uniforms.distance = distance;
  12521. uniforms.coneCos = Math.cos( light.angle );
  12522. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  12523. uniforms.decay = light.decay;
  12524. state.spot[ spotLength ] = uniforms;
  12525. const shadow = light.shadow;
  12526. if ( light.map ) {
  12527. state.spotLightMap[ numSpotMaps ] = light.map;
  12528. numSpotMaps ++;
  12529. // make sure the lightMatrix is up to date
  12530. // TODO : do it if required only
  12531. shadow.updateMatrices( light );
  12532. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  12533. }
  12534. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  12535. if ( light.castShadow ) {
  12536. const shadowUniforms = shadowCache.get( light );
  12537. shadowUniforms.shadowBias = shadow.bias;
  12538. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12539. shadowUniforms.shadowRadius = shadow.radius;
  12540. shadowUniforms.shadowMapSize = shadow.mapSize;
  12541. state.spotShadow[ spotLength ] = shadowUniforms;
  12542. state.spotShadowMap[ spotLength ] = shadowMap;
  12543. numSpotShadows ++;
  12544. }
  12545. spotLength ++;
  12546. } else if ( light.isRectAreaLight ) {
  12547. const uniforms = cache.get( light );
  12548. uniforms.color.copy( color ).multiplyScalar( intensity );
  12549. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12550. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12551. state.rectArea[ rectAreaLength ] = uniforms;
  12552. rectAreaLength ++;
  12553. } else if ( light.isPointLight ) {
  12554. const uniforms = cache.get( light );
  12555. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12556. uniforms.distance = light.distance;
  12557. uniforms.decay = light.decay;
  12558. if ( light.castShadow ) {
  12559. const shadow = light.shadow;
  12560. const shadowUniforms = shadowCache.get( light );
  12561. shadowUniforms.shadowBias = shadow.bias;
  12562. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12563. shadowUniforms.shadowRadius = shadow.radius;
  12564. shadowUniforms.shadowMapSize = shadow.mapSize;
  12565. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12566. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12567. state.pointShadow[ pointLength ] = shadowUniforms;
  12568. state.pointShadowMap[ pointLength ] = shadowMap;
  12569. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  12570. numPointShadows ++;
  12571. }
  12572. state.point[ pointLength ] = uniforms;
  12573. pointLength ++;
  12574. } else if ( light.isHemisphereLight ) {
  12575. const uniforms = cache.get( light );
  12576. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor );
  12577. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor );
  12578. state.hemi[ hemiLength ] = uniforms;
  12579. hemiLength ++;
  12580. }
  12581. }
  12582. if ( rectAreaLength > 0 ) {
  12583. if ( capabilities.isWebGL2 ) {
  12584. // WebGL 2
  12585. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12586. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12587. } else {
  12588. // WebGL 1
  12589. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  12590. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12591. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12592. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  12593. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12594. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12595. } else {
  12596. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  12597. }
  12598. }
  12599. }
  12600. state.ambient[ 0 ] = r;
  12601. state.ambient[ 1 ] = g;
  12602. state.ambient[ 2 ] = b;
  12603. const hash = state.hash;
  12604. if ( hash.directionalLength !== directionalLength ||
  12605. hash.pointLength !== pointLength ||
  12606. hash.spotLength !== spotLength ||
  12607. hash.rectAreaLength !== rectAreaLength ||
  12608. hash.hemiLength !== hemiLength ||
  12609. hash.numDirectionalShadows !== numDirectionalShadows ||
  12610. hash.numPointShadows !== numPointShadows ||
  12611. hash.numSpotShadows !== numSpotShadows ||
  12612. hash.numSpotMaps !== numSpotMaps ) {
  12613. state.directional.length = directionalLength;
  12614. state.spot.length = spotLength;
  12615. state.rectArea.length = rectAreaLength;
  12616. state.point.length = pointLength;
  12617. state.hemi.length = hemiLength;
  12618. state.directionalShadow.length = numDirectionalShadows;
  12619. state.directionalShadowMap.length = numDirectionalShadows;
  12620. state.pointShadow.length = numPointShadows;
  12621. state.pointShadowMap.length = numPointShadows;
  12622. state.spotShadow.length = numSpotShadows;
  12623. state.spotShadowMap.length = numSpotShadows;
  12624. state.directionalShadowMatrix.length = numDirectionalShadows;
  12625. state.pointShadowMatrix.length = numPointShadows;
  12626. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  12627. state.spotLightMap.length = numSpotMaps;
  12628. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  12629. hash.directionalLength = directionalLength;
  12630. hash.pointLength = pointLength;
  12631. hash.spotLength = spotLength;
  12632. hash.rectAreaLength = rectAreaLength;
  12633. hash.hemiLength = hemiLength;
  12634. hash.numDirectionalShadows = numDirectionalShadows;
  12635. hash.numPointShadows = numPointShadows;
  12636. hash.numSpotShadows = numSpotShadows;
  12637. hash.numSpotMaps = numSpotMaps;
  12638. state.version = nextVersion ++;
  12639. }
  12640. }
  12641. function setupView( lights, camera ) {
  12642. let directionalLength = 0;
  12643. let pointLength = 0;
  12644. let spotLength = 0;
  12645. let rectAreaLength = 0;
  12646. let hemiLength = 0;
  12647. const viewMatrix = camera.matrixWorldInverse;
  12648. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12649. const light = lights[ i ];
  12650. if ( light.isDirectionalLight ) {
  12651. const uniforms = state.directional[ directionalLength ];
  12652. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12653. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12654. uniforms.direction.sub( vector3 );
  12655. uniforms.direction.transformDirection( viewMatrix );
  12656. directionalLength ++;
  12657. } else if ( light.isSpotLight ) {
  12658. const uniforms = state.spot[ spotLength ];
  12659. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12660. uniforms.position.applyMatrix4( viewMatrix );
  12661. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12662. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12663. uniforms.direction.sub( vector3 );
  12664. uniforms.direction.transformDirection( viewMatrix );
  12665. spotLength ++;
  12666. } else if ( light.isRectAreaLight ) {
  12667. const uniforms = state.rectArea[ rectAreaLength ];
  12668. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12669. uniforms.position.applyMatrix4( viewMatrix );
  12670. // extract local rotation of light to derive width/height half vectors
  12671. matrix42.identity();
  12672. matrix4.copy( light.matrixWorld );
  12673. matrix4.premultiply( viewMatrix );
  12674. matrix42.extractRotation( matrix4 );
  12675. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12676. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12677. uniforms.halfWidth.applyMatrix4( matrix42 );
  12678. uniforms.halfHeight.applyMatrix4( matrix42 );
  12679. rectAreaLength ++;
  12680. } else if ( light.isPointLight ) {
  12681. const uniforms = state.point[ pointLength ];
  12682. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12683. uniforms.position.applyMatrix4( viewMatrix );
  12684. pointLength ++;
  12685. } else if ( light.isHemisphereLight ) {
  12686. const uniforms = state.hemi[ hemiLength ];
  12687. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12688. uniforms.direction.transformDirection( viewMatrix );
  12689. hemiLength ++;
  12690. }
  12691. }
  12692. }
  12693. return {
  12694. setup: setup,
  12695. setupView: setupView,
  12696. state: state
  12697. };
  12698. }
  12699. function WebGLRenderState( extensions, capabilities ) {
  12700. const lights = new WebGLLights( extensions, capabilities );
  12701. const lightsArray = [];
  12702. const shadowsArray = [];
  12703. function init() {
  12704. lightsArray.length = 0;
  12705. shadowsArray.length = 0;
  12706. }
  12707. function pushLight( light ) {
  12708. lightsArray.push( light );
  12709. }
  12710. function pushShadow( shadowLight ) {
  12711. shadowsArray.push( shadowLight );
  12712. }
  12713. function setupLights( useLegacyLights ) {
  12714. lights.setup( lightsArray, useLegacyLights );
  12715. }
  12716. function setupLightsView( camera ) {
  12717. lights.setupView( lightsArray, camera );
  12718. }
  12719. const state = {
  12720. lightsArray: lightsArray,
  12721. shadowsArray: shadowsArray,
  12722. lights: lights
  12723. };
  12724. return {
  12725. init: init,
  12726. state: state,
  12727. setupLights: setupLights,
  12728. setupLightsView: setupLightsView,
  12729. pushLight: pushLight,
  12730. pushShadow: pushShadow
  12731. };
  12732. }
  12733. function WebGLRenderStates( extensions, capabilities ) {
  12734. let renderStates = new WeakMap();
  12735. function get( scene, renderCallDepth = 0 ) {
  12736. const renderStateArray = renderStates.get( scene );
  12737. let renderState;
  12738. if ( renderStateArray === undefined ) {
  12739. renderState = new WebGLRenderState( extensions, capabilities );
  12740. renderStates.set( scene, [ renderState ] );
  12741. } else {
  12742. if ( renderCallDepth >= renderStateArray.length ) {
  12743. renderState = new WebGLRenderState( extensions, capabilities );
  12744. renderStateArray.push( renderState );
  12745. } else {
  12746. renderState = renderStateArray[ renderCallDepth ];
  12747. }
  12748. }
  12749. return renderState;
  12750. }
  12751. function dispose() {
  12752. renderStates = new WeakMap();
  12753. }
  12754. return {
  12755. get: get,
  12756. dispose: dispose
  12757. };
  12758. }
  12759. class MeshDepthMaterial extends Material {
  12760. constructor( parameters ) {
  12761. super();
  12762. this.isMeshDepthMaterial = true;
  12763. this.type = 'MeshDepthMaterial';
  12764. this.depthPacking = BasicDepthPacking;
  12765. this.map = null;
  12766. this.alphaMap = null;
  12767. this.displacementMap = null;
  12768. this.displacementScale = 1;
  12769. this.displacementBias = 0;
  12770. this.wireframe = false;
  12771. this.wireframeLinewidth = 1;
  12772. this.setValues( parameters );
  12773. }
  12774. copy( source ) {
  12775. super.copy( source );
  12776. this.depthPacking = source.depthPacking;
  12777. this.map = source.map;
  12778. this.alphaMap = source.alphaMap;
  12779. this.displacementMap = source.displacementMap;
  12780. this.displacementScale = source.displacementScale;
  12781. this.displacementBias = source.displacementBias;
  12782. this.wireframe = source.wireframe;
  12783. this.wireframeLinewidth = source.wireframeLinewidth;
  12784. return this;
  12785. }
  12786. }
  12787. class MeshDistanceMaterial extends Material {
  12788. constructor( parameters ) {
  12789. super();
  12790. this.isMeshDistanceMaterial = true;
  12791. this.type = 'MeshDistanceMaterial';
  12792. this.referencePosition = new Vector3();
  12793. this.nearDistance = 1;
  12794. this.farDistance = 1000;
  12795. this.map = null;
  12796. this.alphaMap = null;
  12797. this.displacementMap = null;
  12798. this.displacementScale = 1;
  12799. this.displacementBias = 0;
  12800. this.setValues( parameters );
  12801. }
  12802. copy( source ) {
  12803. super.copy( source );
  12804. this.referencePosition.copy( source.referencePosition );
  12805. this.nearDistance = source.nearDistance;
  12806. this.farDistance = source.farDistance;
  12807. this.map = source.map;
  12808. this.alphaMap = source.alphaMap;
  12809. this.displacementMap = source.displacementMap;
  12810. this.displacementScale = source.displacementScale;
  12811. this.displacementBias = source.displacementBias;
  12812. return this;
  12813. }
  12814. }
  12815. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12816. 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}";
  12817. function WebGLShadowMap( _renderer, _objects, _capabilities ) {
  12818. let _frustum = new Frustum();
  12819. const _shadowMapSize = new Vector2(),
  12820. _viewportSize = new Vector2(),
  12821. _viewport = new Vector4(),
  12822. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  12823. _distanceMaterial = new MeshDistanceMaterial(),
  12824. _materialCache = {},
  12825. _maxTextureSize = _capabilities.maxTextureSize;
  12826. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  12827. const shadowMaterialVertical = new ShaderMaterial( {
  12828. defines: {
  12829. VSM_SAMPLES: 8
  12830. },
  12831. uniforms: {
  12832. shadow_pass: { value: null },
  12833. resolution: { value: new Vector2() },
  12834. radius: { value: 4.0 }
  12835. },
  12836. vertexShader: vertex,
  12837. fragmentShader: fragment
  12838. } );
  12839. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12840. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12841. const fullScreenTri = new BufferGeometry();
  12842. fullScreenTri.setAttribute(
  12843. 'position',
  12844. new BufferAttribute(
  12845. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  12846. 3
  12847. )
  12848. );
  12849. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  12850. const scope = this;
  12851. this.enabled = false;
  12852. this.autoUpdate = true;
  12853. this.needsUpdate = false;
  12854. this.type = PCFShadowMap;
  12855. this.render = function ( lights, scene, camera ) {
  12856. if ( scope.enabled === false ) return;
  12857. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  12858. if ( lights.length === 0 ) return;
  12859. const currentRenderTarget = _renderer.getRenderTarget();
  12860. const activeCubeFace = _renderer.getActiveCubeFace();
  12861. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12862. const _state = _renderer.state;
  12863. // Set GL state for depth map.
  12864. _state.setBlending( NoBlending );
  12865. _state.buffers.color.setClear( 1, 1, 1, 1 );
  12866. _state.buffers.depth.setTest( true );
  12867. _state.setScissorTest( false );
  12868. // render depth map
  12869. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  12870. const light = lights[ i ];
  12871. const shadow = light.shadow;
  12872. if ( shadow === undefined ) {
  12873. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  12874. continue;
  12875. }
  12876. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  12877. _shadowMapSize.copy( shadow.mapSize );
  12878. const shadowFrameExtents = shadow.getFrameExtents();
  12879. _shadowMapSize.multiply( shadowFrameExtents );
  12880. _viewportSize.copy( shadow.mapSize );
  12881. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  12882. if ( _shadowMapSize.x > _maxTextureSize ) {
  12883. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  12884. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12885. shadow.mapSize.x = _viewportSize.x;
  12886. }
  12887. if ( _shadowMapSize.y > _maxTextureSize ) {
  12888. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  12889. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12890. shadow.mapSize.y = _viewportSize.y;
  12891. }
  12892. }
  12893. if ( shadow.map === null ) {
  12894. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  12895. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12896. shadow.map.texture.name = light.name + '.shadowMap';
  12897. shadow.camera.updateProjectionMatrix();
  12898. }
  12899. _renderer.setRenderTarget( shadow.map );
  12900. _renderer.clear();
  12901. const viewportCount = shadow.getViewportCount();
  12902. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  12903. const viewport = shadow.getViewport( vp );
  12904. _viewport.set(
  12905. _viewportSize.x * viewport.x,
  12906. _viewportSize.y * viewport.y,
  12907. _viewportSize.x * viewport.z,
  12908. _viewportSize.y * viewport.w
  12909. );
  12910. _state.viewport( _viewport );
  12911. shadow.updateMatrices( light, vp );
  12912. _frustum = shadow.getFrustum();
  12913. renderObject( scene, camera, shadow.camera, light, this.type );
  12914. }
  12915. // do blur pass for VSM
  12916. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  12917. VSMPass( shadow, camera );
  12918. }
  12919. shadow.needsUpdate = false;
  12920. }
  12921. scope.needsUpdate = false;
  12922. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  12923. };
  12924. function VSMPass( shadow, camera ) {
  12925. const geometry = _objects.update( fullScreenMesh );
  12926. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  12927. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  12928. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  12929. shadowMaterialVertical.needsUpdate = true;
  12930. shadowMaterialHorizontal.needsUpdate = true;
  12931. }
  12932. if ( shadow.mapPass === null ) {
  12933. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  12934. }
  12935. // vertical pass
  12936. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12937. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12938. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12939. _renderer.setRenderTarget( shadow.mapPass );
  12940. _renderer.clear();
  12941. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  12942. // horizontal pass
  12943. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12944. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12945. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12946. _renderer.setRenderTarget( shadow.map );
  12947. _renderer.clear();
  12948. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  12949. }
  12950. function getDepthMaterial( object, material, light, shadowCameraNear, shadowCameraFar, type ) {
  12951. let result = null;
  12952. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  12953. if ( customMaterial !== undefined ) {
  12954. result = customMaterial;
  12955. } else {
  12956. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  12957. if ( ( _renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  12958. ( material.displacementMap && material.displacementScale !== 0 ) ||
  12959. ( material.alphaMap && material.alphaTest > 0 ) ||
  12960. ( material.map && material.alphaTest > 0 ) ) {
  12961. // in this case we need a unique material instance reflecting the
  12962. // appropriate state
  12963. const keyA = result.uuid, keyB = material.uuid;
  12964. let materialsForVariant = _materialCache[ keyA ];
  12965. if ( materialsForVariant === undefined ) {
  12966. materialsForVariant = {};
  12967. _materialCache[ keyA ] = materialsForVariant;
  12968. }
  12969. let cachedMaterial = materialsForVariant[ keyB ];
  12970. if ( cachedMaterial === undefined ) {
  12971. cachedMaterial = result.clone();
  12972. materialsForVariant[ keyB ] = cachedMaterial;
  12973. }
  12974. result = cachedMaterial;
  12975. }
  12976. }
  12977. result.visible = material.visible;
  12978. result.wireframe = material.wireframe;
  12979. if ( type === VSMShadowMap ) {
  12980. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  12981. } else {
  12982. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  12983. }
  12984. result.alphaMap = material.alphaMap;
  12985. result.alphaTest = material.alphaTest;
  12986. result.map = material.map;
  12987. result.clipShadows = material.clipShadows;
  12988. result.clippingPlanes = material.clippingPlanes;
  12989. result.clipIntersection = material.clipIntersection;
  12990. result.displacementMap = material.displacementMap;
  12991. result.displacementScale = material.displacementScale;
  12992. result.displacementBias = material.displacementBias;
  12993. result.wireframeLinewidth = material.wireframeLinewidth;
  12994. result.linewidth = material.linewidth;
  12995. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  12996. result.referencePosition.setFromMatrixPosition( light.matrixWorld );
  12997. result.nearDistance = shadowCameraNear;
  12998. result.farDistance = shadowCameraFar;
  12999. }
  13000. return result;
  13001. }
  13002. function renderObject( object, camera, shadowCamera, light, type ) {
  13003. if ( object.visible === false ) return;
  13004. const visible = object.layers.test( camera.layers );
  13005. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  13006. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  13007. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  13008. const geometry = _objects.update( object );
  13009. const material = object.material;
  13010. if ( Array.isArray( material ) ) {
  13011. const groups = geometry.groups;
  13012. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  13013. const group = groups[ k ];
  13014. const groupMaterial = material[ group.materialIndex ];
  13015. if ( groupMaterial && groupMaterial.visible ) {
  13016. const depthMaterial = getDepthMaterial( object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );
  13017. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  13018. }
  13019. }
  13020. } else if ( material.visible ) {
  13021. const depthMaterial = getDepthMaterial( object, material, light, shadowCamera.near, shadowCamera.far, type );
  13022. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  13023. }
  13024. }
  13025. }
  13026. const children = object.children;
  13027. for ( let i = 0, l = children.length; i < l; i ++ ) {
  13028. renderObject( children[ i ], camera, shadowCamera, light, type );
  13029. }
  13030. }
  13031. }
  13032. function WebGLState( gl, extensions, capabilities ) {
  13033. const isWebGL2 = capabilities.isWebGL2;
  13034. function ColorBuffer() {
  13035. let locked = false;
  13036. const color = new Vector4();
  13037. let currentColorMask = null;
  13038. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  13039. return {
  13040. setMask: function ( colorMask ) {
  13041. if ( currentColorMask !== colorMask && ! locked ) {
  13042. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  13043. currentColorMask = colorMask;
  13044. }
  13045. },
  13046. setLocked: function ( lock ) {
  13047. locked = lock;
  13048. },
  13049. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  13050. if ( premultipliedAlpha === true ) {
  13051. r *= a; g *= a; b *= a;
  13052. }
  13053. color.set( r, g, b, a );
  13054. if ( currentColorClear.equals( color ) === false ) {
  13055. gl.clearColor( r, g, b, a );
  13056. currentColorClear.copy( color );
  13057. }
  13058. },
  13059. reset: function () {
  13060. locked = false;
  13061. currentColorMask = null;
  13062. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  13063. }
  13064. };
  13065. }
  13066. function DepthBuffer() {
  13067. let locked = false;
  13068. let currentDepthMask = null;
  13069. let currentDepthFunc = null;
  13070. let currentDepthClear = null;
  13071. return {
  13072. setTest: function ( depthTest ) {
  13073. if ( depthTest ) {
  13074. enable( 2929 );
  13075. } else {
  13076. disable( 2929 );
  13077. }
  13078. },
  13079. setMask: function ( depthMask ) {
  13080. if ( currentDepthMask !== depthMask && ! locked ) {
  13081. gl.depthMask( depthMask );
  13082. currentDepthMask = depthMask;
  13083. }
  13084. },
  13085. setFunc: function ( depthFunc ) {
  13086. if ( currentDepthFunc !== depthFunc ) {
  13087. switch ( depthFunc ) {
  13088. case NeverDepth:
  13089. gl.depthFunc( 512 );
  13090. break;
  13091. case AlwaysDepth:
  13092. gl.depthFunc( 519 );
  13093. break;
  13094. case LessDepth:
  13095. gl.depthFunc( 513 );
  13096. break;
  13097. case LessEqualDepth:
  13098. gl.depthFunc( 515 );
  13099. break;
  13100. case EqualDepth:
  13101. gl.depthFunc( 514 );
  13102. break;
  13103. case GreaterEqualDepth:
  13104. gl.depthFunc( 518 );
  13105. break;
  13106. case GreaterDepth:
  13107. gl.depthFunc( 516 );
  13108. break;
  13109. case NotEqualDepth:
  13110. gl.depthFunc( 517 );
  13111. break;
  13112. default:
  13113. gl.depthFunc( 515 );
  13114. }
  13115. currentDepthFunc = depthFunc;
  13116. }
  13117. },
  13118. setLocked: function ( lock ) {
  13119. locked = lock;
  13120. },
  13121. setClear: function ( depth ) {
  13122. if ( currentDepthClear !== depth ) {
  13123. gl.clearDepth( depth );
  13124. currentDepthClear = depth;
  13125. }
  13126. },
  13127. reset: function () {
  13128. locked = false;
  13129. currentDepthMask = null;
  13130. currentDepthFunc = null;
  13131. currentDepthClear = null;
  13132. }
  13133. };
  13134. }
  13135. function StencilBuffer() {
  13136. let locked = false;
  13137. let currentStencilMask = null;
  13138. let currentStencilFunc = null;
  13139. let currentStencilRef = null;
  13140. let currentStencilFuncMask = null;
  13141. let currentStencilFail = null;
  13142. let currentStencilZFail = null;
  13143. let currentStencilZPass = null;
  13144. let currentStencilClear = null;
  13145. return {
  13146. setTest: function ( stencilTest ) {
  13147. if ( ! locked ) {
  13148. if ( stencilTest ) {
  13149. enable( 2960 );
  13150. } else {
  13151. disable( 2960 );
  13152. }
  13153. }
  13154. },
  13155. setMask: function ( stencilMask ) {
  13156. if ( currentStencilMask !== stencilMask && ! locked ) {
  13157. gl.stencilMask( stencilMask );
  13158. currentStencilMask = stencilMask;
  13159. }
  13160. },
  13161. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  13162. if ( currentStencilFunc !== stencilFunc ||
  13163. currentStencilRef !== stencilRef ||
  13164. currentStencilFuncMask !== stencilMask ) {
  13165. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  13166. currentStencilFunc = stencilFunc;
  13167. currentStencilRef = stencilRef;
  13168. currentStencilFuncMask = stencilMask;
  13169. }
  13170. },
  13171. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  13172. if ( currentStencilFail !== stencilFail ||
  13173. currentStencilZFail !== stencilZFail ||
  13174. currentStencilZPass !== stencilZPass ) {
  13175. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  13176. currentStencilFail = stencilFail;
  13177. currentStencilZFail = stencilZFail;
  13178. currentStencilZPass = stencilZPass;
  13179. }
  13180. },
  13181. setLocked: function ( lock ) {
  13182. locked = lock;
  13183. },
  13184. setClear: function ( stencil ) {
  13185. if ( currentStencilClear !== stencil ) {
  13186. gl.clearStencil( stencil );
  13187. currentStencilClear = stencil;
  13188. }
  13189. },
  13190. reset: function () {
  13191. locked = false;
  13192. currentStencilMask = null;
  13193. currentStencilFunc = null;
  13194. currentStencilRef = null;
  13195. currentStencilFuncMask = null;
  13196. currentStencilFail = null;
  13197. currentStencilZFail = null;
  13198. currentStencilZPass = null;
  13199. currentStencilClear = null;
  13200. }
  13201. };
  13202. }
  13203. //
  13204. const colorBuffer = new ColorBuffer();
  13205. const depthBuffer = new DepthBuffer();
  13206. const stencilBuffer = new StencilBuffer();
  13207. const uboBindings = new WeakMap();
  13208. const uboProgramMap = new WeakMap();
  13209. let enabledCapabilities = {};
  13210. let currentBoundFramebuffers = {};
  13211. let currentDrawbuffers = new WeakMap();
  13212. let defaultDrawbuffers = [];
  13213. let currentProgram = null;
  13214. let currentBlendingEnabled = false;
  13215. let currentBlending = null;
  13216. let currentBlendEquation = null;
  13217. let currentBlendSrc = null;
  13218. let currentBlendDst = null;
  13219. let currentBlendEquationAlpha = null;
  13220. let currentBlendSrcAlpha = null;
  13221. let currentBlendDstAlpha = null;
  13222. let currentPremultipledAlpha = false;
  13223. let currentFlipSided = null;
  13224. let currentCullFace = null;
  13225. let currentLineWidth = null;
  13226. let currentPolygonOffsetFactor = null;
  13227. let currentPolygonOffsetUnits = null;
  13228. const maxTextures = gl.getParameter( 35661 );
  13229. let lineWidthAvailable = false;
  13230. let version = 0;
  13231. const glVersion = gl.getParameter( 7938 );
  13232. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  13233. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  13234. lineWidthAvailable = ( version >= 1.0 );
  13235. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  13236. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  13237. lineWidthAvailable = ( version >= 2.0 );
  13238. }
  13239. let currentTextureSlot = null;
  13240. let currentBoundTextures = {};
  13241. const scissorParam = gl.getParameter( 3088 );
  13242. const viewportParam = gl.getParameter( 2978 );
  13243. const currentScissor = new Vector4().fromArray( scissorParam );
  13244. const currentViewport = new Vector4().fromArray( viewportParam );
  13245. function createTexture( type, target, count ) {
  13246. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  13247. const texture = gl.createTexture();
  13248. gl.bindTexture( type, texture );
  13249. gl.texParameteri( type, 10241, 9728 );
  13250. gl.texParameteri( type, 10240, 9728 );
  13251. for ( let i = 0; i < count; i ++ ) {
  13252. gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
  13253. }
  13254. return texture;
  13255. }
  13256. const emptyTextures = {};
  13257. emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
  13258. emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
  13259. // init
  13260. colorBuffer.setClear( 0, 0, 0, 1 );
  13261. depthBuffer.setClear( 1 );
  13262. stencilBuffer.setClear( 0 );
  13263. enable( 2929 );
  13264. depthBuffer.setFunc( LessEqualDepth );
  13265. setFlipSided( false );
  13266. setCullFace( CullFaceBack );
  13267. enable( 2884 );
  13268. setBlending( NoBlending );
  13269. //
  13270. function enable( id ) {
  13271. if ( enabledCapabilities[ id ] !== true ) {
  13272. gl.enable( id );
  13273. enabledCapabilities[ id ] = true;
  13274. }
  13275. }
  13276. function disable( id ) {
  13277. if ( enabledCapabilities[ id ] !== false ) {
  13278. gl.disable( id );
  13279. enabledCapabilities[ id ] = false;
  13280. }
  13281. }
  13282. function bindFramebuffer( target, framebuffer ) {
  13283. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  13284. gl.bindFramebuffer( target, framebuffer );
  13285. currentBoundFramebuffers[ target ] = framebuffer;
  13286. if ( isWebGL2 ) {
  13287. // 36009 is equivalent to 36160
  13288. if ( target === 36009 ) {
  13289. currentBoundFramebuffers[ 36160 ] = framebuffer;
  13290. }
  13291. if ( target === 36160 ) {
  13292. currentBoundFramebuffers[ 36009 ] = framebuffer;
  13293. }
  13294. }
  13295. return true;
  13296. }
  13297. return false;
  13298. }
  13299. function drawBuffers( renderTarget, framebuffer ) {
  13300. let drawBuffers = defaultDrawbuffers;
  13301. let needsUpdate = false;
  13302. if ( renderTarget ) {
  13303. drawBuffers = currentDrawbuffers.get( framebuffer );
  13304. if ( drawBuffers === undefined ) {
  13305. drawBuffers = [];
  13306. currentDrawbuffers.set( framebuffer, drawBuffers );
  13307. }
  13308. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13309. const textures = renderTarget.texture;
  13310. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== 36064 ) {
  13311. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  13312. drawBuffers[ i ] = 36064 + i;
  13313. }
  13314. drawBuffers.length = textures.length;
  13315. needsUpdate = true;
  13316. }
  13317. } else {
  13318. if ( drawBuffers[ 0 ] !== 36064 ) {
  13319. drawBuffers[ 0 ] = 36064;
  13320. needsUpdate = true;
  13321. }
  13322. }
  13323. } else {
  13324. if ( drawBuffers[ 0 ] !== 1029 ) {
  13325. drawBuffers[ 0 ] = 1029;
  13326. needsUpdate = true;
  13327. }
  13328. }
  13329. if ( needsUpdate ) {
  13330. if ( capabilities.isWebGL2 ) {
  13331. gl.drawBuffers( drawBuffers );
  13332. } else {
  13333. extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers );
  13334. }
  13335. }
  13336. }
  13337. function useProgram( program ) {
  13338. if ( currentProgram !== program ) {
  13339. gl.useProgram( program );
  13340. currentProgram = program;
  13341. return true;
  13342. }
  13343. return false;
  13344. }
  13345. const equationToGL = {
  13346. [ AddEquation ]: 32774,
  13347. [ SubtractEquation ]: 32778,
  13348. [ ReverseSubtractEquation ]: 32779
  13349. };
  13350. if ( isWebGL2 ) {
  13351. equationToGL[ MinEquation ] = 32775;
  13352. equationToGL[ MaxEquation ] = 32776;
  13353. } else {
  13354. const extension = extensions.get( 'EXT_blend_minmax' );
  13355. if ( extension !== null ) {
  13356. equationToGL[ MinEquation ] = extension.MIN_EXT;
  13357. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  13358. }
  13359. }
  13360. const factorToGL = {
  13361. [ ZeroFactor ]: 0,
  13362. [ OneFactor ]: 1,
  13363. [ SrcColorFactor ]: 768,
  13364. [ SrcAlphaFactor ]: 770,
  13365. [ SrcAlphaSaturateFactor ]: 776,
  13366. [ DstColorFactor ]: 774,
  13367. [ DstAlphaFactor ]: 772,
  13368. [ OneMinusSrcColorFactor ]: 769,
  13369. [ OneMinusSrcAlphaFactor ]: 771,
  13370. [ OneMinusDstColorFactor ]: 775,
  13371. [ OneMinusDstAlphaFactor ]: 773
  13372. };
  13373. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  13374. if ( blending === NoBlending ) {
  13375. if ( currentBlendingEnabled === true ) {
  13376. disable( 3042 );
  13377. currentBlendingEnabled = false;
  13378. }
  13379. return;
  13380. }
  13381. if ( currentBlendingEnabled === false ) {
  13382. enable( 3042 );
  13383. currentBlendingEnabled = true;
  13384. }
  13385. if ( blending !== CustomBlending ) {
  13386. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  13387. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  13388. gl.blendEquation( 32774 );
  13389. currentBlendEquation = AddEquation;
  13390. currentBlendEquationAlpha = AddEquation;
  13391. }
  13392. if ( premultipliedAlpha ) {
  13393. switch ( blending ) {
  13394. case NormalBlending:
  13395. gl.blendFuncSeparate( 1, 771, 1, 771 );
  13396. break;
  13397. case AdditiveBlending:
  13398. gl.blendFunc( 1, 1 );
  13399. break;
  13400. case SubtractiveBlending:
  13401. gl.blendFuncSeparate( 0, 769, 0, 1 );
  13402. break;
  13403. case MultiplyBlending:
  13404. gl.blendFuncSeparate( 0, 768, 0, 770 );
  13405. break;
  13406. default:
  13407. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13408. break;
  13409. }
  13410. } else {
  13411. switch ( blending ) {
  13412. case NormalBlending:
  13413. gl.blendFuncSeparate( 770, 771, 1, 771 );
  13414. break;
  13415. case AdditiveBlending:
  13416. gl.blendFunc( 770, 1 );
  13417. break;
  13418. case SubtractiveBlending:
  13419. gl.blendFuncSeparate( 0, 769, 0, 1 );
  13420. break;
  13421. case MultiplyBlending:
  13422. gl.blendFunc( 0, 768 );
  13423. break;
  13424. default:
  13425. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13426. break;
  13427. }
  13428. }
  13429. currentBlendSrc = null;
  13430. currentBlendDst = null;
  13431. currentBlendSrcAlpha = null;
  13432. currentBlendDstAlpha = null;
  13433. currentBlending = blending;
  13434. currentPremultipledAlpha = premultipliedAlpha;
  13435. }
  13436. return;
  13437. }
  13438. // custom blending
  13439. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13440. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13441. blendDstAlpha = blendDstAlpha || blendDst;
  13442. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  13443. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  13444. currentBlendEquation = blendEquation;
  13445. currentBlendEquationAlpha = blendEquationAlpha;
  13446. }
  13447. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  13448. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  13449. currentBlendSrc = blendSrc;
  13450. currentBlendDst = blendDst;
  13451. currentBlendSrcAlpha = blendSrcAlpha;
  13452. currentBlendDstAlpha = blendDstAlpha;
  13453. }
  13454. currentBlending = blending;
  13455. currentPremultipledAlpha = false;
  13456. }
  13457. function setMaterial( material, frontFaceCW ) {
  13458. material.side === DoubleSide
  13459. ? disable( 2884 )
  13460. : enable( 2884 );
  13461. let flipSided = ( material.side === BackSide );
  13462. if ( frontFaceCW ) flipSided = ! flipSided;
  13463. setFlipSided( flipSided );
  13464. ( material.blending === NormalBlending && material.transparent === false )
  13465. ? setBlending( NoBlending )
  13466. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  13467. depthBuffer.setFunc( material.depthFunc );
  13468. depthBuffer.setTest( material.depthTest );
  13469. depthBuffer.setMask( material.depthWrite );
  13470. colorBuffer.setMask( material.colorWrite );
  13471. const stencilWrite = material.stencilWrite;
  13472. stencilBuffer.setTest( stencilWrite );
  13473. if ( stencilWrite ) {
  13474. stencilBuffer.setMask( material.stencilWriteMask );
  13475. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  13476. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  13477. }
  13478. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13479. material.alphaToCoverage === true
  13480. ? enable( 32926 )
  13481. : disable( 32926 );
  13482. }
  13483. //
  13484. function setFlipSided( flipSided ) {
  13485. if ( currentFlipSided !== flipSided ) {
  13486. if ( flipSided ) {
  13487. gl.frontFace( 2304 );
  13488. } else {
  13489. gl.frontFace( 2305 );
  13490. }
  13491. currentFlipSided = flipSided;
  13492. }
  13493. }
  13494. function setCullFace( cullFace ) {
  13495. if ( cullFace !== CullFaceNone ) {
  13496. enable( 2884 );
  13497. if ( cullFace !== currentCullFace ) {
  13498. if ( cullFace === CullFaceBack ) {
  13499. gl.cullFace( 1029 );
  13500. } else if ( cullFace === CullFaceFront ) {
  13501. gl.cullFace( 1028 );
  13502. } else {
  13503. gl.cullFace( 1032 );
  13504. }
  13505. }
  13506. } else {
  13507. disable( 2884 );
  13508. }
  13509. currentCullFace = cullFace;
  13510. }
  13511. function setLineWidth( width ) {
  13512. if ( width !== currentLineWidth ) {
  13513. if ( lineWidthAvailable ) gl.lineWidth( width );
  13514. currentLineWidth = width;
  13515. }
  13516. }
  13517. function setPolygonOffset( polygonOffset, factor, units ) {
  13518. if ( polygonOffset ) {
  13519. enable( 32823 );
  13520. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  13521. gl.polygonOffset( factor, units );
  13522. currentPolygonOffsetFactor = factor;
  13523. currentPolygonOffsetUnits = units;
  13524. }
  13525. } else {
  13526. disable( 32823 );
  13527. }
  13528. }
  13529. function setScissorTest( scissorTest ) {
  13530. if ( scissorTest ) {
  13531. enable( 3089 );
  13532. } else {
  13533. disable( 3089 );
  13534. }
  13535. }
  13536. // texture
  13537. function activeTexture( webglSlot ) {
  13538. if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1;
  13539. if ( currentTextureSlot !== webglSlot ) {
  13540. gl.activeTexture( webglSlot );
  13541. currentTextureSlot = webglSlot;
  13542. }
  13543. }
  13544. function bindTexture( webglType, webglTexture, webglSlot ) {
  13545. if ( webglSlot === undefined ) {
  13546. if ( currentTextureSlot === null ) {
  13547. webglSlot = 33984 + maxTextures - 1;
  13548. } else {
  13549. webglSlot = currentTextureSlot;
  13550. }
  13551. }
  13552. let boundTexture = currentBoundTextures[ webglSlot ];
  13553. if ( boundTexture === undefined ) {
  13554. boundTexture = { type: undefined, texture: undefined };
  13555. currentBoundTextures[ webglSlot ] = boundTexture;
  13556. }
  13557. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  13558. if ( currentTextureSlot !== webglSlot ) {
  13559. gl.activeTexture( webglSlot );
  13560. currentTextureSlot = webglSlot;
  13561. }
  13562. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  13563. boundTexture.type = webglType;
  13564. boundTexture.texture = webglTexture;
  13565. }
  13566. }
  13567. function unbindTexture() {
  13568. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  13569. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  13570. gl.bindTexture( boundTexture.type, null );
  13571. boundTexture.type = undefined;
  13572. boundTexture.texture = undefined;
  13573. }
  13574. }
  13575. function compressedTexImage2D() {
  13576. try {
  13577. gl.compressedTexImage2D.apply( gl, arguments );
  13578. } catch ( error ) {
  13579. console.error( 'THREE.WebGLState:', error );
  13580. }
  13581. }
  13582. function compressedTexImage3D() {
  13583. try {
  13584. gl.compressedTexImage3D.apply( gl, arguments );
  13585. } catch ( error ) {
  13586. console.error( 'THREE.WebGLState:', error );
  13587. }
  13588. }
  13589. function texSubImage2D() {
  13590. try {
  13591. gl.texSubImage2D.apply( gl, arguments );
  13592. } catch ( error ) {
  13593. console.error( 'THREE.WebGLState:', error );
  13594. }
  13595. }
  13596. function texSubImage3D() {
  13597. try {
  13598. gl.texSubImage3D.apply( gl, arguments );
  13599. } catch ( error ) {
  13600. console.error( 'THREE.WebGLState:', error );
  13601. }
  13602. }
  13603. function compressedTexSubImage2D() {
  13604. try {
  13605. gl.compressedTexSubImage2D.apply( gl, arguments );
  13606. } catch ( error ) {
  13607. console.error( 'THREE.WebGLState:', error );
  13608. }
  13609. }
  13610. function compressedTexSubImage3D() {
  13611. try {
  13612. gl.compressedTexSubImage3D.apply( gl, arguments );
  13613. } catch ( error ) {
  13614. console.error( 'THREE.WebGLState:', error );
  13615. }
  13616. }
  13617. function texStorage2D() {
  13618. try {
  13619. gl.texStorage2D.apply( gl, arguments );
  13620. } catch ( error ) {
  13621. console.error( 'THREE.WebGLState:', error );
  13622. }
  13623. }
  13624. function texStorage3D() {
  13625. try {
  13626. gl.texStorage3D.apply( gl, arguments );
  13627. } catch ( error ) {
  13628. console.error( 'THREE.WebGLState:', error );
  13629. }
  13630. }
  13631. function texImage2D() {
  13632. try {
  13633. gl.texImage2D.apply( gl, arguments );
  13634. } catch ( error ) {
  13635. console.error( 'THREE.WebGLState:', error );
  13636. }
  13637. }
  13638. function texImage3D() {
  13639. try {
  13640. gl.texImage3D.apply( gl, arguments );
  13641. } catch ( error ) {
  13642. console.error( 'THREE.WebGLState:', error );
  13643. }
  13644. }
  13645. //
  13646. function scissor( scissor ) {
  13647. if ( currentScissor.equals( scissor ) === false ) {
  13648. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  13649. currentScissor.copy( scissor );
  13650. }
  13651. }
  13652. function viewport( viewport ) {
  13653. if ( currentViewport.equals( viewport ) === false ) {
  13654. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  13655. currentViewport.copy( viewport );
  13656. }
  13657. }
  13658. function updateUBOMapping( uniformsGroup, program ) {
  13659. let mapping = uboProgramMap.get( program );
  13660. if ( mapping === undefined ) {
  13661. mapping = new WeakMap();
  13662. uboProgramMap.set( program, mapping );
  13663. }
  13664. let blockIndex = mapping.get( uniformsGroup );
  13665. if ( blockIndex === undefined ) {
  13666. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  13667. mapping.set( uniformsGroup, blockIndex );
  13668. }
  13669. }
  13670. function uniformBlockBinding( uniformsGroup, program ) {
  13671. const mapping = uboProgramMap.get( program );
  13672. const blockIndex = mapping.get( uniformsGroup );
  13673. if ( uboBindings.get( program ) !== blockIndex ) {
  13674. // bind shader specific block index to global block point
  13675. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  13676. uboBindings.set( program, blockIndex );
  13677. }
  13678. }
  13679. //
  13680. function reset() {
  13681. // reset state
  13682. gl.disable( 3042 );
  13683. gl.disable( 2884 );
  13684. gl.disable( 2929 );
  13685. gl.disable( 32823 );
  13686. gl.disable( 3089 );
  13687. gl.disable( 2960 );
  13688. gl.disable( 32926 );
  13689. gl.blendEquation( 32774 );
  13690. gl.blendFunc( 1, 0 );
  13691. gl.blendFuncSeparate( 1, 0, 1, 0 );
  13692. gl.colorMask( true, true, true, true );
  13693. gl.clearColor( 0, 0, 0, 0 );
  13694. gl.depthMask( true );
  13695. gl.depthFunc( 513 );
  13696. gl.clearDepth( 1 );
  13697. gl.stencilMask( 0xffffffff );
  13698. gl.stencilFunc( 519, 0, 0xffffffff );
  13699. gl.stencilOp( 7680, 7680, 7680 );
  13700. gl.clearStencil( 0 );
  13701. gl.cullFace( 1029 );
  13702. gl.frontFace( 2305 );
  13703. gl.polygonOffset( 0, 0 );
  13704. gl.activeTexture( 33984 );
  13705. gl.bindFramebuffer( 36160, null );
  13706. if ( isWebGL2 === true ) {
  13707. gl.bindFramebuffer( 36009, null );
  13708. gl.bindFramebuffer( 36008, null );
  13709. }
  13710. gl.useProgram( null );
  13711. gl.lineWidth( 1 );
  13712. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  13713. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  13714. // reset internals
  13715. enabledCapabilities = {};
  13716. currentTextureSlot = null;
  13717. currentBoundTextures = {};
  13718. currentBoundFramebuffers = {};
  13719. currentDrawbuffers = new WeakMap();
  13720. defaultDrawbuffers = [];
  13721. currentProgram = null;
  13722. currentBlendingEnabled = false;
  13723. currentBlending = null;
  13724. currentBlendEquation = null;
  13725. currentBlendSrc = null;
  13726. currentBlendDst = null;
  13727. currentBlendEquationAlpha = null;
  13728. currentBlendSrcAlpha = null;
  13729. currentBlendDstAlpha = null;
  13730. currentPremultipledAlpha = false;
  13731. currentFlipSided = null;
  13732. currentCullFace = null;
  13733. currentLineWidth = null;
  13734. currentPolygonOffsetFactor = null;
  13735. currentPolygonOffsetUnits = null;
  13736. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13737. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13738. colorBuffer.reset();
  13739. depthBuffer.reset();
  13740. stencilBuffer.reset();
  13741. }
  13742. return {
  13743. buffers: {
  13744. color: colorBuffer,
  13745. depth: depthBuffer,
  13746. stencil: stencilBuffer
  13747. },
  13748. enable: enable,
  13749. disable: disable,
  13750. bindFramebuffer: bindFramebuffer,
  13751. drawBuffers: drawBuffers,
  13752. useProgram: useProgram,
  13753. setBlending: setBlending,
  13754. setMaterial: setMaterial,
  13755. setFlipSided: setFlipSided,
  13756. setCullFace: setCullFace,
  13757. setLineWidth: setLineWidth,
  13758. setPolygonOffset: setPolygonOffset,
  13759. setScissorTest: setScissorTest,
  13760. activeTexture: activeTexture,
  13761. bindTexture: bindTexture,
  13762. unbindTexture: unbindTexture,
  13763. compressedTexImage2D: compressedTexImage2D,
  13764. compressedTexImage3D: compressedTexImage3D,
  13765. texImage2D: texImage2D,
  13766. texImage3D: texImage3D,
  13767. updateUBOMapping: updateUBOMapping,
  13768. uniformBlockBinding: uniformBlockBinding,
  13769. texStorage2D: texStorage2D,
  13770. texStorage3D: texStorage3D,
  13771. texSubImage2D: texSubImage2D,
  13772. texSubImage3D: texSubImage3D,
  13773. compressedTexSubImage2D: compressedTexSubImage2D,
  13774. compressedTexSubImage3D: compressedTexSubImage3D,
  13775. scissor: scissor,
  13776. viewport: viewport,
  13777. reset: reset
  13778. };
  13779. }
  13780. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  13781. const isWebGL2 = capabilities.isWebGL2;
  13782. const maxTextures = capabilities.maxTextures;
  13783. const maxCubemapSize = capabilities.maxCubemapSize;
  13784. const maxTextureSize = capabilities.maxTextureSize;
  13785. const maxSamples = capabilities.maxSamples;
  13786. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  13787. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  13788. const _videoTextures = new WeakMap();
  13789. let _canvas;
  13790. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  13791. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13792. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13793. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13794. let useOffscreenCanvas = false;
  13795. try {
  13796. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  13797. // eslint-disable-next-line compat/compat
  13798. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  13799. } catch ( err ) {
  13800. // Ignore any errors
  13801. }
  13802. function createCanvas( width, height ) {
  13803. // Use OffscreenCanvas when available. Specially needed in web workers
  13804. return useOffscreenCanvas ?
  13805. // eslint-disable-next-line compat/compat
  13806. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  13807. }
  13808. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  13809. let scale = 1;
  13810. // handle case if texture exceeds max size
  13811. if ( image.width > maxSize || image.height > maxSize ) {
  13812. scale = maxSize / Math.max( image.width, image.height );
  13813. }
  13814. // only perform resize if necessary
  13815. if ( scale < 1 || needsPowerOfTwo === true ) {
  13816. // only perform resize for certain image types
  13817. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  13818. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  13819. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  13820. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13821. const width = floor( scale * image.width );
  13822. const height = floor( scale * image.height );
  13823. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  13824. // cube textures can't reuse the same canvas
  13825. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  13826. canvas.width = width;
  13827. canvas.height = height;
  13828. const context = canvas.getContext( '2d' );
  13829. context.drawImage( image, 0, 0, width, height );
  13830. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  13831. return canvas;
  13832. } else {
  13833. if ( 'data' in image ) {
  13834. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  13835. }
  13836. return image;
  13837. }
  13838. }
  13839. return image;
  13840. }
  13841. function isPowerOfTwo$1( image ) {
  13842. return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height );
  13843. }
  13844. function textureNeedsPowerOfTwo( texture ) {
  13845. if ( isWebGL2 ) return false;
  13846. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  13847. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  13848. }
  13849. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  13850. return texture.generateMipmaps && supportsMips &&
  13851. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13852. }
  13853. function generateMipmap( target ) {
  13854. _gl.generateMipmap( target );
  13855. }
  13856. function getInternalFormat( internalFormatName, glFormat, glType, encoding, forceLinearEncoding = false ) {
  13857. if ( isWebGL2 === false ) return glFormat;
  13858. if ( internalFormatName !== null ) {
  13859. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  13860. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  13861. }
  13862. let internalFormat = glFormat;
  13863. if ( glFormat === 6403 ) {
  13864. if ( glType === 5126 ) internalFormat = 33326;
  13865. if ( glType === 5131 ) internalFormat = 33325;
  13866. if ( glType === 5121 ) internalFormat = 33321;
  13867. }
  13868. if ( glFormat === 33319 ) {
  13869. if ( glType === 5126 ) internalFormat = 33328;
  13870. if ( glType === 5131 ) internalFormat = 33327;
  13871. if ( glType === 5121 ) internalFormat = 33323;
  13872. }
  13873. if ( glFormat === 6408 ) {
  13874. if ( glType === 5126 ) internalFormat = 34836;
  13875. if ( glType === 5131 ) internalFormat = 34842;
  13876. if ( glType === 5121 ) internalFormat = ( encoding === sRGBEncoding && forceLinearEncoding === false ) ? 35907 : 32856;
  13877. if ( glType === 32819 ) internalFormat = 32854;
  13878. if ( glType === 32820 ) internalFormat = 32855;
  13879. }
  13880. if ( internalFormat === 33325 || internalFormat === 33326 ||
  13881. internalFormat === 33327 || internalFormat === 33328 ||
  13882. internalFormat === 34842 || internalFormat === 34836 ) {
  13883. extensions.get( 'EXT_color_buffer_float' );
  13884. }
  13885. return internalFormat;
  13886. }
  13887. function getMipLevels( texture, image, supportsMips ) {
  13888. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  13889. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  13890. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  13891. // user-defined mipmaps
  13892. return texture.mipmaps.length;
  13893. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  13894. return image.mipmaps.length;
  13895. } else {
  13896. // texture without mipmaps (only base level)
  13897. return 1;
  13898. }
  13899. }
  13900. // Fallback filters for non-power-of-2 textures
  13901. function filterFallback( f ) {
  13902. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  13903. return 9728;
  13904. }
  13905. return 9729;
  13906. }
  13907. //
  13908. function onTextureDispose( event ) {
  13909. const texture = event.target;
  13910. texture.removeEventListener( 'dispose', onTextureDispose );
  13911. deallocateTexture( texture );
  13912. if ( texture.isVideoTexture ) {
  13913. _videoTextures.delete( texture );
  13914. }
  13915. }
  13916. function onRenderTargetDispose( event ) {
  13917. const renderTarget = event.target;
  13918. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  13919. deallocateRenderTarget( renderTarget );
  13920. }
  13921. //
  13922. function deallocateTexture( texture ) {
  13923. const textureProperties = properties.get( texture );
  13924. if ( textureProperties.__webglInit === undefined ) return;
  13925. // check if it's necessary to remove the WebGLTexture object
  13926. const source = texture.source;
  13927. const webglTextures = _sources.get( source );
  13928. if ( webglTextures ) {
  13929. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  13930. webglTexture.usedTimes --;
  13931. // the WebGLTexture object is not used anymore, remove it
  13932. if ( webglTexture.usedTimes === 0 ) {
  13933. deleteTexture( texture );
  13934. }
  13935. // remove the weak map entry if no WebGLTexture uses the source anymore
  13936. if ( Object.keys( webglTextures ).length === 0 ) {
  13937. _sources.delete( source );
  13938. }
  13939. }
  13940. properties.remove( texture );
  13941. }
  13942. function deleteTexture( texture ) {
  13943. const textureProperties = properties.get( texture );
  13944. _gl.deleteTexture( textureProperties.__webglTexture );
  13945. const source = texture.source;
  13946. const webglTextures = _sources.get( source );
  13947. delete webglTextures[ textureProperties.__cacheKey ];
  13948. info.memory.textures --;
  13949. }
  13950. function deallocateRenderTarget( renderTarget ) {
  13951. const texture = renderTarget.texture;
  13952. const renderTargetProperties = properties.get( renderTarget );
  13953. const textureProperties = properties.get( texture );
  13954. if ( textureProperties.__webglTexture !== undefined ) {
  13955. _gl.deleteTexture( textureProperties.__webglTexture );
  13956. info.memory.textures --;
  13957. }
  13958. if ( renderTarget.depthTexture ) {
  13959. renderTarget.depthTexture.dispose();
  13960. }
  13961. if ( renderTarget.isWebGLCubeRenderTarget ) {
  13962. for ( let i = 0; i < 6; i ++ ) {
  13963. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  13964. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  13965. }
  13966. } else {
  13967. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  13968. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  13969. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  13970. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  13971. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  13972. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  13973. }
  13974. }
  13975. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  13976. }
  13977. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13978. for ( let i = 0, il = texture.length; i < il; i ++ ) {
  13979. const attachmentProperties = properties.get( texture[ i ] );
  13980. if ( attachmentProperties.__webglTexture ) {
  13981. _gl.deleteTexture( attachmentProperties.__webglTexture );
  13982. info.memory.textures --;
  13983. }
  13984. properties.remove( texture[ i ] );
  13985. }
  13986. }
  13987. properties.remove( texture );
  13988. properties.remove( renderTarget );
  13989. }
  13990. //
  13991. let textureUnits = 0;
  13992. function resetTextureUnits() {
  13993. textureUnits = 0;
  13994. }
  13995. function allocateTextureUnit() {
  13996. const textureUnit = textureUnits;
  13997. if ( textureUnit >= maxTextures ) {
  13998. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  13999. }
  14000. textureUnits += 1;
  14001. return textureUnit;
  14002. }
  14003. function getTextureCacheKey( texture ) {
  14004. const array = [];
  14005. array.push( texture.wrapS );
  14006. array.push( texture.wrapT );
  14007. array.push( texture.wrapR || 0 );
  14008. array.push( texture.magFilter );
  14009. array.push( texture.minFilter );
  14010. array.push( texture.anisotropy );
  14011. array.push( texture.internalFormat );
  14012. array.push( texture.format );
  14013. array.push( texture.type );
  14014. array.push( texture.generateMipmaps );
  14015. array.push( texture.premultiplyAlpha );
  14016. array.push( texture.flipY );
  14017. array.push( texture.unpackAlignment );
  14018. array.push( texture.encoding );
  14019. return array.join();
  14020. }
  14021. //
  14022. function setTexture2D( texture, slot ) {
  14023. const textureProperties = properties.get( texture );
  14024. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  14025. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  14026. const image = texture.image;
  14027. if ( image === null ) {
  14028. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  14029. } else if ( image.complete === false ) {
  14030. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  14031. } else {
  14032. uploadTexture( textureProperties, texture, slot );
  14033. return;
  14034. }
  14035. }
  14036. state.bindTexture( 3553, textureProperties.__webglTexture, 33984 + slot );
  14037. }
  14038. function setTexture2DArray( texture, slot ) {
  14039. const textureProperties = properties.get( texture );
  14040. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14041. uploadTexture( textureProperties, texture, slot );
  14042. return;
  14043. }
  14044. state.bindTexture( 35866, textureProperties.__webglTexture, 33984 + slot );
  14045. }
  14046. function setTexture3D( texture, slot ) {
  14047. const textureProperties = properties.get( texture );
  14048. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14049. uploadTexture( textureProperties, texture, slot );
  14050. return;
  14051. }
  14052. state.bindTexture( 32879, textureProperties.__webglTexture, 33984 + slot );
  14053. }
  14054. function setTextureCube( texture, slot ) {
  14055. const textureProperties = properties.get( texture );
  14056. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14057. uploadCubeTexture( textureProperties, texture, slot );
  14058. return;
  14059. }
  14060. state.bindTexture( 34067, textureProperties.__webglTexture, 33984 + slot );
  14061. }
  14062. const wrappingToGL = {
  14063. [ RepeatWrapping ]: 10497,
  14064. [ ClampToEdgeWrapping ]: 33071,
  14065. [ MirroredRepeatWrapping ]: 33648
  14066. };
  14067. const filterToGL = {
  14068. [ NearestFilter ]: 9728,
  14069. [ NearestMipmapNearestFilter ]: 9984,
  14070. [ NearestMipmapLinearFilter ]: 9986,
  14071. [ LinearFilter ]: 9729,
  14072. [ LinearMipmapNearestFilter ]: 9985,
  14073. [ LinearMipmapLinearFilter ]: 9987
  14074. };
  14075. function setTextureParameters( textureType, texture, supportsMips ) {
  14076. if ( supportsMips ) {
  14077. _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] );
  14078. _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] );
  14079. if ( textureType === 32879 || textureType === 35866 ) {
  14080. _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] );
  14081. }
  14082. _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] );
  14083. _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] );
  14084. } else {
  14085. _gl.texParameteri( textureType, 10242, 33071 );
  14086. _gl.texParameteri( textureType, 10243, 33071 );
  14087. if ( textureType === 32879 || textureType === 35866 ) {
  14088. _gl.texParameteri( textureType, 32882, 33071 );
  14089. }
  14090. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  14091. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  14092. }
  14093. _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
  14094. _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
  14095. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  14096. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  14097. }
  14098. }
  14099. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  14100. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  14101. if ( texture.magFilter === NearestFilter ) return;
  14102. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  14103. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  14104. if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only
  14105. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  14106. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  14107. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  14108. }
  14109. }
  14110. }
  14111. function initTexture( textureProperties, texture ) {
  14112. let forceUpload = false;
  14113. if ( textureProperties.__webglInit === undefined ) {
  14114. textureProperties.__webglInit = true;
  14115. texture.addEventListener( 'dispose', onTextureDispose );
  14116. }
  14117. // create Source <-> WebGLTextures mapping if necessary
  14118. const source = texture.source;
  14119. let webglTextures = _sources.get( source );
  14120. if ( webglTextures === undefined ) {
  14121. webglTextures = {};
  14122. _sources.set( source, webglTextures );
  14123. }
  14124. // check if there is already a WebGLTexture object for the given texture parameters
  14125. const textureCacheKey = getTextureCacheKey( texture );
  14126. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  14127. // if not, create a new instance of WebGLTexture
  14128. if ( webglTextures[ textureCacheKey ] === undefined ) {
  14129. // create new entry
  14130. webglTextures[ textureCacheKey ] = {
  14131. texture: _gl.createTexture(),
  14132. usedTimes: 0
  14133. };
  14134. info.memory.textures ++;
  14135. // when a new instance of WebGLTexture was created, a texture upload is required
  14136. // even if the image contents are identical
  14137. forceUpload = true;
  14138. }
  14139. webglTextures[ textureCacheKey ].usedTimes ++;
  14140. // every time the texture cache key changes, it's necessary to check if an instance of
  14141. // WebGLTexture can be deleted in order to avoid a memory leak.
  14142. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  14143. if ( webglTexture !== undefined ) {
  14144. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  14145. if ( webglTexture.usedTimes === 0 ) {
  14146. deleteTexture( texture );
  14147. }
  14148. }
  14149. // store references to cache key and WebGLTexture object
  14150. textureProperties.__cacheKey = textureCacheKey;
  14151. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  14152. }
  14153. return forceUpload;
  14154. }
  14155. function uploadTexture( textureProperties, texture, slot ) {
  14156. let textureType = 3553;
  14157. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = 35866;
  14158. if ( texture.isData3DTexture ) textureType = 32879;
  14159. const forceUpload = initTexture( textureProperties, texture );
  14160. const source = texture.source;
  14161. state.bindTexture( textureType, textureProperties.__webglTexture, 33984 + slot );
  14162. const sourceProperties = properties.get( source );
  14163. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14164. state.activeTexture( 33984 + slot );
  14165. _gl.pixelStorei( 37440, texture.flipY );
  14166. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  14167. _gl.pixelStorei( 3317, texture.unpackAlignment );
  14168. _gl.pixelStorei( 37443, 0 );
  14169. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false;
  14170. let image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  14171. image = verifyColorSpace( texture, image );
  14172. const supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14173. glFormat = utils.convert( texture.format, texture.encoding );
  14174. let glType = utils.convert( texture.type ),
  14175. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture );
  14176. setTextureParameters( textureType, texture, supportsMips );
  14177. let mipmap;
  14178. const mipmaps = texture.mipmaps;
  14179. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  14180. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14181. const levels = getMipLevels( texture, image, supportsMips );
  14182. if ( texture.isDepthTexture ) {
  14183. // populate depth texture with dummy data
  14184. glInternalFormat = 6402;
  14185. if ( isWebGL2 ) {
  14186. if ( texture.type === FloatType ) {
  14187. glInternalFormat = 36012;
  14188. } else if ( texture.type === UnsignedIntType ) {
  14189. glInternalFormat = 33190;
  14190. } else if ( texture.type === UnsignedInt248Type ) {
  14191. glInternalFormat = 35056;
  14192. } else {
  14193. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  14194. }
  14195. } else {
  14196. if ( texture.type === FloatType ) {
  14197. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  14198. }
  14199. }
  14200. // validation checks for WebGL 1
  14201. if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
  14202. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14203. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  14204. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14205. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  14206. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  14207. texture.type = UnsignedIntType;
  14208. glType = utils.convert( texture.type );
  14209. }
  14210. }
  14211. if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) {
  14212. // Depth stencil textures need the DEPTH_STENCIL internal format
  14213. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14214. glInternalFormat = 34041;
  14215. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14216. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  14217. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14218. if ( texture.type !== UnsignedInt248Type ) {
  14219. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  14220. texture.type = UnsignedInt248Type;
  14221. glType = utils.convert( texture.type );
  14222. }
  14223. }
  14224. //
  14225. if ( allocateMemory ) {
  14226. if ( useTexStorage ) {
  14227. state.texStorage2D( 3553, 1, glInternalFormat, image.width, image.height );
  14228. } else {
  14229. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  14230. }
  14231. }
  14232. } else if ( texture.isDataTexture ) {
  14233. // use manually created mipmaps if available
  14234. // if there are no manual mipmaps
  14235. // set 0 level mipmap and then use GL to generate other mipmap levels
  14236. if ( mipmaps.length > 0 && supportsMips ) {
  14237. if ( useTexStorage && allocateMemory ) {
  14238. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14239. }
  14240. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14241. mipmap = mipmaps[ i ];
  14242. if ( useTexStorage ) {
  14243. state.texSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14244. } else {
  14245. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14246. }
  14247. }
  14248. texture.generateMipmaps = false;
  14249. } else {
  14250. if ( useTexStorage ) {
  14251. if ( allocateMemory ) {
  14252. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  14253. }
  14254. state.texSubImage2D( 3553, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  14255. } else {
  14256. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14257. }
  14258. }
  14259. } else if ( texture.isCompressedTexture ) {
  14260. if ( texture.isCompressedArrayTexture ) {
  14261. if ( useTexStorage && allocateMemory ) {
  14262. state.texStorage3D( 35866, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  14263. }
  14264. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14265. mipmap = mipmaps[ i ];
  14266. if ( texture.format !== RGBAFormat ) {
  14267. if ( glFormat !== null ) {
  14268. if ( useTexStorage ) {
  14269. state.compressedTexSubImage3D( 35866, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data, 0, 0 );
  14270. } else {
  14271. state.compressedTexImage3D( 35866, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  14272. }
  14273. } else {
  14274. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14275. }
  14276. } else {
  14277. if ( useTexStorage ) {
  14278. state.texSubImage3D( 35866, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  14279. } else {
  14280. state.texImage3D( 35866, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  14281. }
  14282. }
  14283. }
  14284. } else {
  14285. if ( useTexStorage && allocateMemory ) {
  14286. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14287. }
  14288. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14289. mipmap = mipmaps[ i ];
  14290. if ( texture.format !== RGBAFormat ) {
  14291. if ( glFormat !== null ) {
  14292. if ( useTexStorage ) {
  14293. state.compressedTexSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14294. } else {
  14295. state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14296. }
  14297. } else {
  14298. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  14299. }
  14300. } else {
  14301. if ( useTexStorage ) {
  14302. state.texSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14303. } else {
  14304. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14305. }
  14306. }
  14307. }
  14308. }
  14309. } else if ( texture.isDataArrayTexture ) {
  14310. if ( useTexStorage ) {
  14311. if ( allocateMemory ) {
  14312. state.texStorage3D( 35866, levels, glInternalFormat, image.width, image.height, image.depth );
  14313. }
  14314. state.texSubImage3D( 35866, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14315. } else {
  14316. state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14317. }
  14318. } else if ( texture.isData3DTexture ) {
  14319. if ( useTexStorage ) {
  14320. if ( allocateMemory ) {
  14321. state.texStorage3D( 32879, levels, glInternalFormat, image.width, image.height, image.depth );
  14322. }
  14323. state.texSubImage3D( 32879, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  14324. } else {
  14325. state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  14326. }
  14327. } else if ( texture.isFramebufferTexture ) {
  14328. if ( allocateMemory ) {
  14329. if ( useTexStorage ) {
  14330. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  14331. } else {
  14332. let width = image.width, height = image.height;
  14333. for ( let i = 0; i < levels; i ++ ) {
  14334. state.texImage2D( 3553, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  14335. width >>= 1;
  14336. height >>= 1;
  14337. }
  14338. }
  14339. }
  14340. } else {
  14341. // regular Texture (image, video, canvas)
  14342. // use manually created mipmaps if available
  14343. // if there are no manual mipmaps
  14344. // set 0 level mipmap and then use GL to generate other mipmap levels
  14345. if ( mipmaps.length > 0 && supportsMips ) {
  14346. if ( useTexStorage && allocateMemory ) {
  14347. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  14348. }
  14349. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  14350. mipmap = mipmaps[ i ];
  14351. if ( useTexStorage ) {
  14352. state.texSubImage2D( 3553, i, 0, 0, glFormat, glType, mipmap );
  14353. } else {
  14354. state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );
  14355. }
  14356. }
  14357. texture.generateMipmaps = false;
  14358. } else {
  14359. if ( useTexStorage ) {
  14360. if ( allocateMemory ) {
  14361. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  14362. }
  14363. state.texSubImage2D( 3553, 0, 0, 0, glFormat, glType, image );
  14364. } else {
  14365. state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
  14366. }
  14367. }
  14368. }
  14369. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14370. generateMipmap( textureType );
  14371. }
  14372. sourceProperties.__version = source.version;
  14373. if ( texture.onUpdate ) texture.onUpdate( texture );
  14374. }
  14375. textureProperties.__version = texture.version;
  14376. }
  14377. function uploadCubeTexture( textureProperties, texture, slot ) {
  14378. if ( texture.image.length !== 6 ) return;
  14379. const forceUpload = initTexture( textureProperties, texture );
  14380. const source = texture.source;
  14381. state.bindTexture( 34067, textureProperties.__webglTexture, 33984 + slot );
  14382. const sourceProperties = properties.get( source );
  14383. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  14384. state.activeTexture( 33984 + slot );
  14385. _gl.pixelStorei( 37440, texture.flipY );
  14386. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  14387. _gl.pixelStorei( 3317, texture.unpackAlignment );
  14388. _gl.pixelStorei( 37443, 0 );
  14389. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  14390. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  14391. const cubeImage = [];
  14392. for ( let i = 0; i < 6; i ++ ) {
  14393. if ( ! isCompressed && ! isDataTexture ) {
  14394. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  14395. } else {
  14396. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  14397. }
  14398. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  14399. }
  14400. const image = cubeImage[ 0 ],
  14401. supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  14402. glFormat = utils.convert( texture.format, texture.encoding ),
  14403. glType = utils.convert( texture.type ),
  14404. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14405. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  14406. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  14407. let levels = getMipLevels( texture, image, supportsMips );
  14408. setTextureParameters( 34067, texture, supportsMips );
  14409. let mipmaps;
  14410. if ( isCompressed ) {
  14411. if ( useTexStorage && allocateMemory ) {
  14412. state.texStorage2D( 34067, levels, glInternalFormat, image.width, image.height );
  14413. }
  14414. for ( let i = 0; i < 6; i ++ ) {
  14415. mipmaps = cubeImage[ i ].mipmaps;
  14416. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14417. const mipmap = mipmaps[ j ];
  14418. if ( texture.format !== RGBAFormat ) {
  14419. if ( glFormat !== null ) {
  14420. if ( useTexStorage ) {
  14421. state.compressedTexSubImage2D( 34069 + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14422. } else {
  14423. state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14424. }
  14425. } else {
  14426. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  14427. }
  14428. } else {
  14429. if ( useTexStorage ) {
  14430. state.texSubImage2D( 34069 + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14431. } else {
  14432. state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14433. }
  14434. }
  14435. }
  14436. }
  14437. } else {
  14438. mipmaps = texture.mipmaps;
  14439. if ( useTexStorage && allocateMemory ) {
  14440. // TODO: Uniformly handle mipmap definitions
  14441. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  14442. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  14443. if ( mipmaps.length > 0 ) levels ++;
  14444. state.texStorage2D( 34067, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height );
  14445. }
  14446. for ( let i = 0; i < 6; i ++ ) {
  14447. if ( isDataTexture ) {
  14448. if ( useTexStorage ) {
  14449. state.texSubImage2D( 34069 + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  14450. } else {
  14451. state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  14452. }
  14453. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14454. const mipmap = mipmaps[ j ];
  14455. const mipmapImage = mipmap.image[ i ].image;
  14456. if ( useTexStorage ) {
  14457. state.texSubImage2D( 34069 + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  14458. } else {
  14459. state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  14460. }
  14461. }
  14462. } else {
  14463. if ( useTexStorage ) {
  14464. state.texSubImage2D( 34069 + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  14465. } else {
  14466. state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  14467. }
  14468. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14469. const mipmap = mipmaps[ j ];
  14470. if ( useTexStorage ) {
  14471. state.texSubImage2D( 34069 + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  14472. } else {
  14473. state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  14474. }
  14475. }
  14476. }
  14477. }
  14478. }
  14479. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14480. // We assume images for cube map have the same size.
  14481. generateMipmap( 34067 );
  14482. }
  14483. sourceProperties.__version = source.version;
  14484. if ( texture.onUpdate ) texture.onUpdate( texture );
  14485. }
  14486. textureProperties.__version = texture.version;
  14487. }
  14488. // Render targets
  14489. // Setup storage for target texture and bind it to correct framebuffer
  14490. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) {
  14491. const glFormat = utils.convert( texture.format, texture.encoding );
  14492. const glType = utils.convert( texture.type );
  14493. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14494. const renderTargetProperties = properties.get( renderTarget );
  14495. if ( ! renderTargetProperties.__hasExternalTextures ) {
  14496. if ( textureTarget === 32879 || textureTarget === 35866 ) {
  14497. state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null );
  14498. } else {
  14499. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14500. }
  14501. }
  14502. state.bindFramebuffer( 36160, framebuffer );
  14503. if ( useMultisampledRTT( renderTarget ) ) {
  14504. multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  14505. } else if ( textureTarget === 3553 || ( textureTarget >= 34069 && textureTarget <= 34074 ) ) { // see #24753
  14506. _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 );
  14507. }
  14508. state.bindFramebuffer( 36160, null );
  14509. }
  14510. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14511. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  14512. _gl.bindRenderbuffer( 36161, renderbuffer );
  14513. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14514. let glInternalFormat = 33189;
  14515. if ( isMultisample || useMultisampledRTT( renderTarget ) ) {
  14516. const depthTexture = renderTarget.depthTexture;
  14517. if ( depthTexture && depthTexture.isDepthTexture ) {
  14518. if ( depthTexture.type === FloatType ) {
  14519. glInternalFormat = 36012;
  14520. } else if ( depthTexture.type === UnsignedIntType ) {
  14521. glInternalFormat = 33190;
  14522. }
  14523. }
  14524. const samples = getRenderTargetSamples( renderTarget );
  14525. if ( useMultisampledRTT( renderTarget ) ) {
  14526. multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14527. } else {
  14528. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14529. }
  14530. } else {
  14531. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  14532. }
  14533. _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
  14534. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14535. const samples = getRenderTargetSamples( renderTarget );
  14536. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14537. _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  14538. } else if ( useMultisampledRTT( renderTarget ) ) {
  14539. multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  14540. } else {
  14541. _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
  14542. }
  14543. _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
  14544. } else {
  14545. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14546. for ( let i = 0; i < textures.length; i ++ ) {
  14547. const texture = textures[ i ];
  14548. const glFormat = utils.convert( texture.format, texture.encoding );
  14549. const glType = utils.convert( texture.type );
  14550. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14551. const samples = getRenderTargetSamples( renderTarget );
  14552. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14553. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14554. } else if ( useMultisampledRTT( renderTarget ) ) {
  14555. multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14556. } else {
  14557. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  14558. }
  14559. }
  14560. }
  14561. _gl.bindRenderbuffer( 36161, null );
  14562. }
  14563. // Setup resources for a Depth Texture for a FBO (needs an extension)
  14564. function setupDepthTexture( framebuffer, renderTarget ) {
  14565. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  14566. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  14567. state.bindFramebuffer( 36160, framebuffer );
  14568. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  14569. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  14570. }
  14571. // upload an empty depth texture with framebuffer size
  14572. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  14573. renderTarget.depthTexture.image.width !== renderTarget.width ||
  14574. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  14575. renderTarget.depthTexture.image.width = renderTarget.width;
  14576. renderTarget.depthTexture.image.height = renderTarget.height;
  14577. renderTarget.depthTexture.needsUpdate = true;
  14578. }
  14579. setTexture2D( renderTarget.depthTexture, 0 );
  14580. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  14581. const samples = getRenderTargetSamples( renderTarget );
  14582. if ( renderTarget.depthTexture.format === DepthFormat ) {
  14583. if ( useMultisampledRTT( renderTarget ) ) {
  14584. multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, 36096, 3553, webglDepthTexture, 0, samples );
  14585. } else {
  14586. _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
  14587. }
  14588. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  14589. if ( useMultisampledRTT( renderTarget ) ) {
  14590. multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, 33306, 3553, webglDepthTexture, 0, samples );
  14591. } else {
  14592. _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
  14593. }
  14594. } else {
  14595. throw new Error( 'Unknown depthTexture format' );
  14596. }
  14597. }
  14598. // Setup GL resources for a non-texture depth buffer
  14599. function setupDepthRenderbuffer( renderTarget ) {
  14600. const renderTargetProperties = properties.get( renderTarget );
  14601. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14602. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  14603. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  14604. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  14605. } else {
  14606. if ( isCube ) {
  14607. renderTargetProperties.__webglDepthbuffer = [];
  14608. for ( let i = 0; i < 6; i ++ ) {
  14609. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
  14610. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  14611. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  14612. }
  14613. } else {
  14614. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  14615. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14616. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  14617. }
  14618. }
  14619. state.bindFramebuffer( 36160, null );
  14620. }
  14621. // rebind framebuffer with external textures
  14622. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  14623. const renderTargetProperties = properties.get( renderTarget );
  14624. if ( colorTexture !== undefined ) {
  14625. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, 36064, 3553 );
  14626. }
  14627. if ( depthTexture !== undefined ) {
  14628. setupDepthRenderbuffer( renderTarget );
  14629. }
  14630. }
  14631. // Set up GL resources for the render target
  14632. function setupRenderTarget( renderTarget ) {
  14633. const texture = renderTarget.texture;
  14634. const renderTargetProperties = properties.get( renderTarget );
  14635. const textureProperties = properties.get( texture );
  14636. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14637. if ( renderTarget.isWebGLMultipleRenderTargets !== true ) {
  14638. if ( textureProperties.__webglTexture === undefined ) {
  14639. textureProperties.__webglTexture = _gl.createTexture();
  14640. }
  14641. textureProperties.__version = texture.version;
  14642. info.memory.textures ++;
  14643. }
  14644. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14645. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14646. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14647. // Setup framebuffer
  14648. if ( isCube ) {
  14649. renderTargetProperties.__webglFramebuffer = [];
  14650. for ( let i = 0; i < 6; i ++ ) {
  14651. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14652. }
  14653. } else {
  14654. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14655. if ( isMultipleRenderTargets ) {
  14656. if ( capabilities.drawBuffers ) {
  14657. const textures = renderTarget.texture;
  14658. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14659. const attachmentProperties = properties.get( textures[ i ] );
  14660. if ( attachmentProperties.__webglTexture === undefined ) {
  14661. attachmentProperties.__webglTexture = _gl.createTexture();
  14662. info.memory.textures ++;
  14663. }
  14664. }
  14665. } else {
  14666. console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' );
  14667. }
  14668. }
  14669. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  14670. const textures = isMultipleRenderTargets ? texture : [ texture ];
  14671. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14672. renderTargetProperties.__webglColorRenderbuffer = [];
  14673. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  14674. for ( let i = 0; i < textures.length; i ++ ) {
  14675. const texture = textures[ i ];
  14676. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  14677. _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14678. const glFormat = utils.convert( texture.format, texture.encoding );
  14679. const glType = utils.convert( texture.type );
  14680. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, renderTarget.isXRRenderTarget === true );
  14681. const samples = getRenderTargetSamples( renderTarget );
  14682. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14683. _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14684. }
  14685. _gl.bindRenderbuffer( 36161, null );
  14686. if ( renderTarget.depthBuffer ) {
  14687. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14688. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  14689. }
  14690. state.bindFramebuffer( 36160, null );
  14691. }
  14692. }
  14693. // Setup color buffer
  14694. if ( isCube ) {
  14695. state.bindTexture( 34067, textureProperties.__webglTexture );
  14696. setTextureParameters( 34067, texture, supportsMips );
  14697. for ( let i = 0; i < 6; i ++ ) {
  14698. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, 36064, 34069 + i );
  14699. }
  14700. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14701. generateMipmap( 34067 );
  14702. }
  14703. state.unbindTexture();
  14704. } else if ( isMultipleRenderTargets ) {
  14705. const textures = renderTarget.texture;
  14706. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14707. const attachment = textures[ i ];
  14708. const attachmentProperties = properties.get( attachment );
  14709. state.bindTexture( 3553, attachmentProperties.__webglTexture );
  14710. setTextureParameters( 3553, attachment, supportsMips );
  14711. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, 36064 + i, 3553 );
  14712. if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) {
  14713. generateMipmap( 3553 );
  14714. }
  14715. }
  14716. state.unbindTexture();
  14717. } else {
  14718. let glTextureType = 3553;
  14719. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  14720. if ( isWebGL2 ) {
  14721. glTextureType = renderTarget.isWebGL3DRenderTarget ? 32879 : 35866;
  14722. } else {
  14723. console.error( 'THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.' );
  14724. }
  14725. }
  14726. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  14727. setTextureParameters( glTextureType, texture, supportsMips );
  14728. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, 36064, glTextureType );
  14729. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14730. generateMipmap( glTextureType );
  14731. }
  14732. state.unbindTexture();
  14733. }
  14734. // Setup depth and stencil buffers
  14735. if ( renderTarget.depthBuffer ) {
  14736. setupDepthRenderbuffer( renderTarget );
  14737. }
  14738. }
  14739. function updateRenderTargetMipmap( renderTarget ) {
  14740. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14741. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14742. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14743. const texture = textures[ i ];
  14744. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14745. const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  14746. const webglTexture = properties.get( texture ).__webglTexture;
  14747. state.bindTexture( target, webglTexture );
  14748. generateMipmap( target );
  14749. state.unbindTexture();
  14750. }
  14751. }
  14752. }
  14753. function updateMultisampleRenderTarget( renderTarget ) {
  14754. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  14755. const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [ renderTarget.texture ];
  14756. const width = renderTarget.width;
  14757. const height = renderTarget.height;
  14758. let mask = 16384;
  14759. const invalidationArray = [];
  14760. const depthStyle = renderTarget.stencilBuffer ? 33306 : 36096;
  14761. const renderTargetProperties = properties.get( renderTarget );
  14762. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14763. // If MRT we need to remove FBO attachments
  14764. if ( isMultipleRenderTargets ) {
  14765. for ( let i = 0; i < textures.length; i ++ ) {
  14766. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  14767. _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, null );
  14768. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  14769. _gl.framebufferTexture2D( 36009, 36064 + i, 3553, null, 0 );
  14770. }
  14771. }
  14772. state.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
  14773. state.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );
  14774. for ( let i = 0; i < textures.length; i ++ ) {
  14775. invalidationArray.push( 36064 + i );
  14776. if ( renderTarget.depthBuffer ) {
  14777. invalidationArray.push( depthStyle );
  14778. }
  14779. const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false;
  14780. if ( ignoreDepthValues === false ) {
  14781. if ( renderTarget.depthBuffer ) mask |= 256;
  14782. if ( renderTarget.stencilBuffer ) mask |= 1024;
  14783. }
  14784. if ( isMultipleRenderTargets ) {
  14785. _gl.framebufferRenderbuffer( 36008, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14786. }
  14787. if ( ignoreDepthValues === true ) {
  14788. _gl.invalidateFramebuffer( 36008, [ depthStyle ] );
  14789. _gl.invalidateFramebuffer( 36009, [ depthStyle ] );
  14790. }
  14791. if ( isMultipleRenderTargets ) {
  14792. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  14793. _gl.framebufferTexture2D( 36009, 36064, 3553, webglTexture, 0 );
  14794. }
  14795. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );
  14796. if ( supportsInvalidateFramebuffer ) {
  14797. _gl.invalidateFramebuffer( 36008, invalidationArray );
  14798. }
  14799. }
  14800. state.bindFramebuffer( 36008, null );
  14801. state.bindFramebuffer( 36009, null );
  14802. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  14803. if ( isMultipleRenderTargets ) {
  14804. for ( let i = 0; i < textures.length; i ++ ) {
  14805. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  14806. _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14807. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  14808. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  14809. _gl.framebufferTexture2D( 36009, 36064 + i, 3553, webglTexture, 0 );
  14810. }
  14811. }
  14812. state.bindFramebuffer( 36009, renderTargetProperties.__webglMultisampledFramebuffer );
  14813. }
  14814. }
  14815. function getRenderTargetSamples( renderTarget ) {
  14816. return Math.min( maxSamples, renderTarget.samples );
  14817. }
  14818. function useMultisampledRTT( renderTarget ) {
  14819. const renderTargetProperties = properties.get( renderTarget );
  14820. return isWebGL2 && renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  14821. }
  14822. function updateVideoTexture( texture ) {
  14823. const frame = info.render.frame;
  14824. // Check the last frame we updated the VideoTexture
  14825. if ( _videoTextures.get( texture ) !== frame ) {
  14826. _videoTextures.set( texture, frame );
  14827. texture.update();
  14828. }
  14829. }
  14830. function verifyColorSpace( texture, image ) {
  14831. const encoding = texture.encoding;
  14832. const format = texture.format;
  14833. const type = texture.type;
  14834. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat ) return image;
  14835. if ( encoding !== LinearEncoding ) {
  14836. // sRGB
  14837. if ( encoding === sRGBEncoding ) {
  14838. if ( isWebGL2 === false ) {
  14839. // in WebGL 1, try to use EXT_sRGB extension and unsized formats
  14840. if ( extensions.has( 'EXT_sRGB' ) === true && format === RGBAFormat ) {
  14841. texture.format = _SRGBAFormat;
  14842. // it's not possible to generate mips in WebGL 1 with this extension
  14843. texture.minFilter = LinearFilter;
  14844. texture.generateMipmaps = false;
  14845. } else {
  14846. // slow fallback (CPU decode)
  14847. image = ImageUtils.sRGBToLinear( image );
  14848. }
  14849. } else {
  14850. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  14851. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  14852. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  14853. }
  14854. }
  14855. } else {
  14856. console.error( 'THREE.WebGLTextures: Unsupported texture encoding:', encoding );
  14857. }
  14858. }
  14859. return image;
  14860. }
  14861. //
  14862. this.allocateTextureUnit = allocateTextureUnit;
  14863. this.resetTextureUnits = resetTextureUnits;
  14864. this.setTexture2D = setTexture2D;
  14865. this.setTexture2DArray = setTexture2DArray;
  14866. this.setTexture3D = setTexture3D;
  14867. this.setTextureCube = setTextureCube;
  14868. this.rebindTextures = rebindTextures;
  14869. this.setupRenderTarget = setupRenderTarget;
  14870. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14871. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14872. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  14873. this.setupFrameBufferTexture = setupFrameBufferTexture;
  14874. this.useMultisampledRTT = useMultisampledRTT;
  14875. }
  14876. function WebGLUtils( gl, extensions, capabilities ) {
  14877. const isWebGL2 = capabilities.isWebGL2;
  14878. function convert( p, encoding = null ) {
  14879. let extension;
  14880. if ( p === UnsignedByteType ) return 5121;
  14881. if ( p === UnsignedShort4444Type ) return 32819;
  14882. if ( p === UnsignedShort5551Type ) return 32820;
  14883. if ( p === ByteType ) return 5120;
  14884. if ( p === ShortType ) return 5122;
  14885. if ( p === UnsignedShortType ) return 5123;
  14886. if ( p === IntType ) return 5124;
  14887. if ( p === UnsignedIntType ) return 5125;
  14888. if ( p === FloatType ) return 5126;
  14889. if ( p === HalfFloatType ) {
  14890. if ( isWebGL2 ) return 5131;
  14891. extension = extensions.get( 'OES_texture_half_float' );
  14892. if ( extension !== null ) {
  14893. return extension.HALF_FLOAT_OES;
  14894. } else {
  14895. return null;
  14896. }
  14897. }
  14898. if ( p === AlphaFormat ) return 6406;
  14899. if ( p === RGBAFormat ) return 6408;
  14900. if ( p === LuminanceFormat ) return 6409;
  14901. if ( p === LuminanceAlphaFormat ) return 6410;
  14902. if ( p === DepthFormat ) return 6402;
  14903. if ( p === DepthStencilFormat ) return 34041;
  14904. // WebGL 1 sRGB fallback
  14905. if ( p === _SRGBAFormat ) {
  14906. extension = extensions.get( 'EXT_sRGB' );
  14907. if ( extension !== null ) {
  14908. return extension.SRGB_ALPHA_EXT;
  14909. } else {
  14910. return null;
  14911. }
  14912. }
  14913. // WebGL2 formats.
  14914. if ( p === RedFormat ) return 6403;
  14915. if ( p === RedIntegerFormat ) return 36244;
  14916. if ( p === RGFormat ) return 33319;
  14917. if ( p === RGIntegerFormat ) return 33320;
  14918. if ( p === RGBAIntegerFormat ) return 36249;
  14919. // S3TC
  14920. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  14921. if ( encoding === sRGBEncoding ) {
  14922. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  14923. if ( extension !== null ) {
  14924. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  14925. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  14926. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  14927. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  14928. } else {
  14929. return null;
  14930. }
  14931. } else {
  14932. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  14933. if ( extension !== null ) {
  14934. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14935. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14936. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14937. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14938. } else {
  14939. return null;
  14940. }
  14941. }
  14942. }
  14943. // PVRTC
  14944. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  14945. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  14946. if ( extension !== null ) {
  14947. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14948. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14949. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14950. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14951. } else {
  14952. return null;
  14953. }
  14954. }
  14955. // ETC1
  14956. if ( p === RGB_ETC1_Format ) {
  14957. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  14958. if ( extension !== null ) {
  14959. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14960. } else {
  14961. return null;
  14962. }
  14963. }
  14964. // ETC2
  14965. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  14966. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  14967. if ( extension !== null ) {
  14968. if ( p === RGB_ETC2_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  14969. if ( p === RGBA_ETC2_EAC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  14970. } else {
  14971. return null;
  14972. }
  14973. }
  14974. // ASTC
  14975. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  14976. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  14977. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  14978. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  14979. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  14980. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  14981. if ( extension !== null ) {
  14982. if ( p === RGBA_ASTC_4x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  14983. if ( p === RGBA_ASTC_5x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  14984. if ( p === RGBA_ASTC_5x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  14985. if ( p === RGBA_ASTC_6x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  14986. if ( p === RGBA_ASTC_6x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  14987. if ( p === RGBA_ASTC_8x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  14988. if ( p === RGBA_ASTC_8x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  14989. if ( p === RGBA_ASTC_8x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  14990. if ( p === RGBA_ASTC_10x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  14991. if ( p === RGBA_ASTC_10x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  14992. if ( p === RGBA_ASTC_10x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  14993. if ( p === RGBA_ASTC_10x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  14994. if ( p === RGBA_ASTC_12x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  14995. if ( p === RGBA_ASTC_12x12_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  14996. } else {
  14997. return null;
  14998. }
  14999. }
  15000. // BPTC
  15001. if ( p === RGBA_BPTC_Format ) {
  15002. extension = extensions.get( 'EXT_texture_compression_bptc' );
  15003. if ( extension !== null ) {
  15004. if ( p === RGBA_BPTC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  15005. } else {
  15006. return null;
  15007. }
  15008. }
  15009. // RGTC
  15010. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  15011. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  15012. if ( extension !== null ) {
  15013. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  15014. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  15015. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  15016. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  15017. } else {
  15018. return null;
  15019. }
  15020. }
  15021. //
  15022. if ( p === UnsignedInt248Type ) {
  15023. if ( isWebGL2 ) return 34042;
  15024. extension = extensions.get( 'WEBGL_depth_texture' );
  15025. if ( extension !== null ) {
  15026. return extension.UNSIGNED_INT_24_8_WEBGL;
  15027. } else {
  15028. return null;
  15029. }
  15030. }
  15031. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  15032. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  15033. }
  15034. return { convert: convert };
  15035. }
  15036. class ArrayCamera extends PerspectiveCamera {
  15037. constructor( array = [] ) {
  15038. super();
  15039. this.isArrayCamera = true;
  15040. this.cameras = array;
  15041. }
  15042. }
  15043. class Group extends Object3D {
  15044. constructor() {
  15045. super();
  15046. this.isGroup = true;
  15047. this.type = 'Group';
  15048. }
  15049. }
  15050. const _moveEvent = { type: 'move' };
  15051. class WebXRController {
  15052. constructor() {
  15053. this._targetRay = null;
  15054. this._grip = null;
  15055. this._hand = null;
  15056. }
  15057. getHandSpace() {
  15058. if ( this._hand === null ) {
  15059. this._hand = new Group();
  15060. this._hand.matrixAutoUpdate = false;
  15061. this._hand.visible = false;
  15062. this._hand.joints = {};
  15063. this._hand.inputState = { pinching: false };
  15064. }
  15065. return this._hand;
  15066. }
  15067. getTargetRaySpace() {
  15068. if ( this._targetRay === null ) {
  15069. this._targetRay = new Group();
  15070. this._targetRay.matrixAutoUpdate = false;
  15071. this._targetRay.visible = false;
  15072. this._targetRay.hasLinearVelocity = false;
  15073. this._targetRay.linearVelocity = new Vector3();
  15074. this._targetRay.hasAngularVelocity = false;
  15075. this._targetRay.angularVelocity = new Vector3();
  15076. }
  15077. return this._targetRay;
  15078. }
  15079. getGripSpace() {
  15080. if ( this._grip === null ) {
  15081. this._grip = new Group();
  15082. this._grip.matrixAutoUpdate = false;
  15083. this._grip.visible = false;
  15084. this._grip.hasLinearVelocity = false;
  15085. this._grip.linearVelocity = new Vector3();
  15086. this._grip.hasAngularVelocity = false;
  15087. this._grip.angularVelocity = new Vector3();
  15088. }
  15089. return this._grip;
  15090. }
  15091. dispatchEvent( event ) {
  15092. if ( this._targetRay !== null ) {
  15093. this._targetRay.dispatchEvent( event );
  15094. }
  15095. if ( this._grip !== null ) {
  15096. this._grip.dispatchEvent( event );
  15097. }
  15098. if ( this._hand !== null ) {
  15099. this._hand.dispatchEvent( event );
  15100. }
  15101. return this;
  15102. }
  15103. connect( inputSource ) {
  15104. if ( inputSource && inputSource.hand ) {
  15105. const hand = this._hand;
  15106. if ( hand ) {
  15107. for ( const inputjoint of inputSource.hand.values() ) {
  15108. // Initialize hand with joints when connected
  15109. this._getHandJoint( hand, inputjoint );
  15110. }
  15111. }
  15112. }
  15113. this.dispatchEvent( { type: 'connected', data: inputSource } );
  15114. return this;
  15115. }
  15116. disconnect( inputSource ) {
  15117. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  15118. if ( this._targetRay !== null ) {
  15119. this._targetRay.visible = false;
  15120. }
  15121. if ( this._grip !== null ) {
  15122. this._grip.visible = false;
  15123. }
  15124. if ( this._hand !== null ) {
  15125. this._hand.visible = false;
  15126. }
  15127. return this;
  15128. }
  15129. update( inputSource, frame, referenceSpace ) {
  15130. let inputPose = null;
  15131. let gripPose = null;
  15132. let handPose = null;
  15133. const targetRay = this._targetRay;
  15134. const grip = this._grip;
  15135. const hand = this._hand;
  15136. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  15137. if ( hand && inputSource.hand ) {
  15138. handPose = true;
  15139. for ( const inputjoint of inputSource.hand.values() ) {
  15140. // Update the joints groups with the XRJoint poses
  15141. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  15142. // The transform of this joint will be updated with the joint pose on each frame
  15143. const joint = this._getHandJoint( hand, inputjoint );
  15144. if ( jointPose !== null ) {
  15145. joint.matrix.fromArray( jointPose.transform.matrix );
  15146. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  15147. joint.jointRadius = jointPose.radius;
  15148. }
  15149. joint.visible = jointPose !== null;
  15150. }
  15151. // Custom events
  15152. // Check pinchz
  15153. const indexTip = hand.joints[ 'index-finger-tip' ];
  15154. const thumbTip = hand.joints[ 'thumb-tip' ];
  15155. const distance = indexTip.position.distanceTo( thumbTip.position );
  15156. const distanceToPinch = 0.02;
  15157. const threshold = 0.005;
  15158. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  15159. hand.inputState.pinching = false;
  15160. this.dispatchEvent( {
  15161. type: 'pinchend',
  15162. handedness: inputSource.handedness,
  15163. target: this
  15164. } );
  15165. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  15166. hand.inputState.pinching = true;
  15167. this.dispatchEvent( {
  15168. type: 'pinchstart',
  15169. handedness: inputSource.handedness,
  15170. target: this
  15171. } );
  15172. }
  15173. } else {
  15174. if ( grip !== null && inputSource.gripSpace ) {
  15175. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  15176. if ( gripPose !== null ) {
  15177. grip.matrix.fromArray( gripPose.transform.matrix );
  15178. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  15179. if ( gripPose.linearVelocity ) {
  15180. grip.hasLinearVelocity = true;
  15181. grip.linearVelocity.copy( gripPose.linearVelocity );
  15182. } else {
  15183. grip.hasLinearVelocity = false;
  15184. }
  15185. if ( gripPose.angularVelocity ) {
  15186. grip.hasAngularVelocity = true;
  15187. grip.angularVelocity.copy( gripPose.angularVelocity );
  15188. } else {
  15189. grip.hasAngularVelocity = false;
  15190. }
  15191. }
  15192. }
  15193. }
  15194. if ( targetRay !== null ) {
  15195. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  15196. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  15197. if ( inputPose === null && gripPose !== null ) {
  15198. inputPose = gripPose;
  15199. }
  15200. if ( inputPose !== null ) {
  15201. targetRay.matrix.fromArray( inputPose.transform.matrix );
  15202. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  15203. if ( inputPose.linearVelocity ) {
  15204. targetRay.hasLinearVelocity = true;
  15205. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  15206. } else {
  15207. targetRay.hasLinearVelocity = false;
  15208. }
  15209. if ( inputPose.angularVelocity ) {
  15210. targetRay.hasAngularVelocity = true;
  15211. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  15212. } else {
  15213. targetRay.hasAngularVelocity = false;
  15214. }
  15215. this.dispatchEvent( _moveEvent );
  15216. }
  15217. }
  15218. }
  15219. if ( targetRay !== null ) {
  15220. targetRay.visible = ( inputPose !== null );
  15221. }
  15222. if ( grip !== null ) {
  15223. grip.visible = ( gripPose !== null );
  15224. }
  15225. if ( hand !== null ) {
  15226. hand.visible = ( handPose !== null );
  15227. }
  15228. return this;
  15229. }
  15230. // private method
  15231. _getHandJoint( hand, inputjoint ) {
  15232. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  15233. const joint = new Group();
  15234. joint.matrixAutoUpdate = false;
  15235. joint.visible = false;
  15236. hand.joints[ inputjoint.jointName ] = joint;
  15237. hand.add( joint );
  15238. }
  15239. return hand.joints[ inputjoint.jointName ];
  15240. }
  15241. }
  15242. class DepthTexture extends Texture {
  15243. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  15244. format = format !== undefined ? format : DepthFormat;
  15245. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  15246. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  15247. }
  15248. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  15249. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  15250. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  15251. this.isDepthTexture = true;
  15252. this.image = { width: width, height: height };
  15253. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  15254. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  15255. this.flipY = false;
  15256. this.generateMipmaps = false;
  15257. }
  15258. }
  15259. class WebXRManager extends EventDispatcher {
  15260. constructor( renderer, gl ) {
  15261. super();
  15262. const scope = this;
  15263. let session = null;
  15264. let framebufferScaleFactor = 1.0;
  15265. let referenceSpace = null;
  15266. let referenceSpaceType = 'local-floor';
  15267. // Set default foveation to maximum.
  15268. let foveation = 1.0;
  15269. let customReferenceSpace = null;
  15270. let pose = null;
  15271. let glBinding = null;
  15272. let glProjLayer = null;
  15273. let glBaseLayer = null;
  15274. let xrFrame = null;
  15275. const attributes = gl.getContextAttributes();
  15276. let initialRenderTarget = null;
  15277. let newRenderTarget = null;
  15278. const controllers = [];
  15279. const controllerInputSources = [];
  15280. const planes = new Set();
  15281. const planesLastChangedTimes = new Map();
  15282. //
  15283. const cameraL = new PerspectiveCamera();
  15284. cameraL.layers.enable( 1 );
  15285. cameraL.viewport = new Vector4();
  15286. const cameraR = new PerspectiveCamera();
  15287. cameraR.layers.enable( 2 );
  15288. cameraR.viewport = new Vector4();
  15289. const cameras = [ cameraL, cameraR ];
  15290. const cameraVR = new ArrayCamera();
  15291. cameraVR.layers.enable( 1 );
  15292. cameraVR.layers.enable( 2 );
  15293. let _currentDepthNear = null;
  15294. let _currentDepthFar = null;
  15295. //
  15296. this.cameraAutoUpdate = true;
  15297. this.enabled = false;
  15298. this.isPresenting = false;
  15299. this.getController = function ( index ) {
  15300. let controller = controllers[ index ];
  15301. if ( controller === undefined ) {
  15302. controller = new WebXRController();
  15303. controllers[ index ] = controller;
  15304. }
  15305. return controller.getTargetRaySpace();
  15306. };
  15307. this.getControllerGrip = function ( index ) {
  15308. let controller = controllers[ index ];
  15309. if ( controller === undefined ) {
  15310. controller = new WebXRController();
  15311. controllers[ index ] = controller;
  15312. }
  15313. return controller.getGripSpace();
  15314. };
  15315. this.getHand = function ( index ) {
  15316. let controller = controllers[ index ];
  15317. if ( controller === undefined ) {
  15318. controller = new WebXRController();
  15319. controllers[ index ] = controller;
  15320. }
  15321. return controller.getHandSpace();
  15322. };
  15323. //
  15324. function onSessionEvent( event ) {
  15325. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  15326. if ( controllerIndex === - 1 ) {
  15327. return;
  15328. }
  15329. const controller = controllers[ controllerIndex ];
  15330. if ( controller !== undefined ) {
  15331. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  15332. }
  15333. }
  15334. function onSessionEnd() {
  15335. session.removeEventListener( 'select', onSessionEvent );
  15336. session.removeEventListener( 'selectstart', onSessionEvent );
  15337. session.removeEventListener( 'selectend', onSessionEvent );
  15338. session.removeEventListener( 'squeeze', onSessionEvent );
  15339. session.removeEventListener( 'squeezestart', onSessionEvent );
  15340. session.removeEventListener( 'squeezeend', onSessionEvent );
  15341. session.removeEventListener( 'end', onSessionEnd );
  15342. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  15343. for ( let i = 0; i < controllers.length; i ++ ) {
  15344. const inputSource = controllerInputSources[ i ];
  15345. if ( inputSource === null ) continue;
  15346. controllerInputSources[ i ] = null;
  15347. controllers[ i ].disconnect( inputSource );
  15348. }
  15349. _currentDepthNear = null;
  15350. _currentDepthFar = null;
  15351. // restore framebuffer/rendering state
  15352. renderer.setRenderTarget( initialRenderTarget );
  15353. glBaseLayer = null;
  15354. glProjLayer = null;
  15355. glBinding = null;
  15356. session = null;
  15357. newRenderTarget = null;
  15358. //
  15359. animation.stop();
  15360. scope.isPresenting = false;
  15361. scope.dispatchEvent( { type: 'sessionend' } );
  15362. }
  15363. this.setFramebufferScaleFactor = function ( value ) {
  15364. framebufferScaleFactor = value;
  15365. if ( scope.isPresenting === true ) {
  15366. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  15367. }
  15368. };
  15369. this.setReferenceSpaceType = function ( value ) {
  15370. referenceSpaceType = value;
  15371. if ( scope.isPresenting === true ) {
  15372. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  15373. }
  15374. };
  15375. this.getReferenceSpace = function () {
  15376. return customReferenceSpace || referenceSpace;
  15377. };
  15378. this.setReferenceSpace = function ( space ) {
  15379. customReferenceSpace = space;
  15380. };
  15381. this.getBaseLayer = function () {
  15382. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  15383. };
  15384. this.getBinding = function () {
  15385. return glBinding;
  15386. };
  15387. this.getFrame = function () {
  15388. return xrFrame;
  15389. };
  15390. this.getSession = function () {
  15391. return session;
  15392. };
  15393. this.setSession = async function ( value ) {
  15394. session = value;
  15395. if ( session !== null ) {
  15396. initialRenderTarget = renderer.getRenderTarget();
  15397. session.addEventListener( 'select', onSessionEvent );
  15398. session.addEventListener( 'selectstart', onSessionEvent );
  15399. session.addEventListener( 'selectend', onSessionEvent );
  15400. session.addEventListener( 'squeeze', onSessionEvent );
  15401. session.addEventListener( 'squeezestart', onSessionEvent );
  15402. session.addEventListener( 'squeezeend', onSessionEvent );
  15403. session.addEventListener( 'end', onSessionEnd );
  15404. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  15405. if ( attributes.xrCompatible !== true ) {
  15406. await gl.makeXRCompatible();
  15407. }
  15408. if ( ( session.renderState.layers === undefined ) || ( renderer.capabilities.isWebGL2 === false ) ) {
  15409. const layerInit = {
  15410. antialias: ( session.renderState.layers === undefined ) ? attributes.antialias : true,
  15411. alpha: attributes.alpha,
  15412. depth: attributes.depth,
  15413. stencil: attributes.stencil,
  15414. framebufferScaleFactor: framebufferScaleFactor
  15415. };
  15416. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  15417. session.updateRenderState( { baseLayer: glBaseLayer } );
  15418. newRenderTarget = new WebGLRenderTarget(
  15419. glBaseLayer.framebufferWidth,
  15420. glBaseLayer.framebufferHeight,
  15421. {
  15422. format: RGBAFormat,
  15423. type: UnsignedByteType,
  15424. encoding: renderer.outputEncoding,
  15425. stencilBuffer: attributes.stencil
  15426. }
  15427. );
  15428. } else {
  15429. let depthFormat = null;
  15430. let depthType = null;
  15431. let glDepthFormat = null;
  15432. if ( attributes.depth ) {
  15433. glDepthFormat = attributes.stencil ? 35056 : 33190;
  15434. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  15435. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  15436. }
  15437. const projectionlayerInit = {
  15438. colorFormat: 32856,
  15439. depthFormat: glDepthFormat,
  15440. scaleFactor: framebufferScaleFactor
  15441. };
  15442. glBinding = new XRWebGLBinding( session, gl );
  15443. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  15444. session.updateRenderState( { layers: [ glProjLayer ] } );
  15445. newRenderTarget = new WebGLRenderTarget(
  15446. glProjLayer.textureWidth,
  15447. glProjLayer.textureHeight,
  15448. {
  15449. format: RGBAFormat,
  15450. type: UnsignedByteType,
  15451. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  15452. stencilBuffer: attributes.stencil,
  15453. encoding: renderer.outputEncoding,
  15454. samples: attributes.antialias ? 4 : 0
  15455. } );
  15456. const renderTargetProperties = renderer.properties.get( newRenderTarget );
  15457. renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues;
  15458. }
  15459. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  15460. this.setFoveation( foveation );
  15461. customReferenceSpace = null;
  15462. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  15463. animation.setContext( session );
  15464. animation.start();
  15465. scope.isPresenting = true;
  15466. scope.dispatchEvent( { type: 'sessionstart' } );
  15467. }
  15468. };
  15469. function onInputSourcesChange( event ) {
  15470. // Notify disconnected
  15471. for ( let i = 0; i < event.removed.length; i ++ ) {
  15472. const inputSource = event.removed[ i ];
  15473. const index = controllerInputSources.indexOf( inputSource );
  15474. if ( index >= 0 ) {
  15475. controllerInputSources[ index ] = null;
  15476. controllers[ index ].disconnect( inputSource );
  15477. }
  15478. }
  15479. // Notify connected
  15480. for ( let i = 0; i < event.added.length; i ++ ) {
  15481. const inputSource = event.added[ i ];
  15482. let controllerIndex = controllerInputSources.indexOf( inputSource );
  15483. if ( controllerIndex === - 1 ) {
  15484. // Assign input source a controller that currently has no input source
  15485. for ( let i = 0; i < controllers.length; i ++ ) {
  15486. if ( i >= controllerInputSources.length ) {
  15487. controllerInputSources.push( inputSource );
  15488. controllerIndex = i;
  15489. break;
  15490. } else if ( controllerInputSources[ i ] === null ) {
  15491. controllerInputSources[ i ] = inputSource;
  15492. controllerIndex = i;
  15493. break;
  15494. }
  15495. }
  15496. // If all controllers do currently receive input we ignore new ones
  15497. if ( controllerIndex === - 1 ) break;
  15498. }
  15499. const controller = controllers[ controllerIndex ];
  15500. if ( controller ) {
  15501. controller.connect( inputSource );
  15502. }
  15503. }
  15504. }
  15505. //
  15506. const cameraLPos = new Vector3();
  15507. const cameraRPos = new Vector3();
  15508. /**
  15509. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15510. * the cameras' projection and world matrices have already been set.
  15511. * And that near and far planes are identical for both cameras.
  15512. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15513. */
  15514. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  15515. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  15516. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  15517. const ipd = cameraLPos.distanceTo( cameraRPos );
  15518. const projL = cameraL.projectionMatrix.elements;
  15519. const projR = cameraR.projectionMatrix.elements;
  15520. // VR systems will have identical far and near planes, and
  15521. // most likely identical top and bottom frustum extents.
  15522. // Use the left camera for these values.
  15523. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  15524. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  15525. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  15526. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  15527. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  15528. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  15529. const left = near * leftFov;
  15530. const right = near * rightFov;
  15531. // Calculate the new camera's position offset from the
  15532. // left camera. xOffset should be roughly half `ipd`.
  15533. const zOffset = ipd / ( - leftFov + rightFov );
  15534. const xOffset = zOffset * - leftFov;
  15535. // TODO: Better way to apply this offset?
  15536. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  15537. camera.translateX( xOffset );
  15538. camera.translateZ( zOffset );
  15539. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  15540. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15541. // Find the union of the frustum values of the cameras and scale
  15542. // the values so that the near plane's position does not change in world space,
  15543. // although must now be relative to the new union camera.
  15544. const near2 = near + zOffset;
  15545. const far2 = far + zOffset;
  15546. const left2 = left - xOffset;
  15547. const right2 = right + ( ipd - xOffset );
  15548. const top2 = topFov * far / far2 * near2;
  15549. const bottom2 = bottomFov * far / far2 * near2;
  15550. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  15551. }
  15552. function updateCamera( camera, parent ) {
  15553. if ( parent === null ) {
  15554. camera.matrixWorld.copy( camera.matrix );
  15555. } else {
  15556. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  15557. }
  15558. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15559. }
  15560. this.updateCamera = function ( camera ) {
  15561. if ( session === null ) return;
  15562. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  15563. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  15564. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  15565. // Note that the new renderState won't apply until the next frame. See #18320
  15566. session.updateRenderState( {
  15567. depthNear: cameraVR.near,
  15568. depthFar: cameraVR.far
  15569. } );
  15570. _currentDepthNear = cameraVR.near;
  15571. _currentDepthFar = cameraVR.far;
  15572. }
  15573. const parent = camera.parent;
  15574. const cameras = cameraVR.cameras;
  15575. updateCamera( cameraVR, parent );
  15576. for ( let i = 0; i < cameras.length; i ++ ) {
  15577. updateCamera( cameras[ i ], parent );
  15578. }
  15579. cameraVR.matrixWorld.decompose( cameraVR.position, cameraVR.quaternion, cameraVR.scale );
  15580. // update user camera and its children
  15581. camera.matrix.copy( cameraVR.matrix );
  15582. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  15583. const children = camera.children;
  15584. for ( let i = 0, l = children.length; i < l; i ++ ) {
  15585. children[ i ].updateMatrixWorld( true );
  15586. }
  15587. // update projection matrix for proper view frustum culling
  15588. if ( cameras.length === 2 ) {
  15589. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  15590. } else {
  15591. // assume single camera setup (AR)
  15592. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  15593. }
  15594. };
  15595. this.getCamera = function () {
  15596. return cameraVR;
  15597. };
  15598. this.getFoveation = function () {
  15599. if ( glProjLayer === null && glBaseLayer === null ) {
  15600. return undefined;
  15601. }
  15602. return foveation;
  15603. };
  15604. this.setFoveation = function ( value ) {
  15605. // 0 = no foveation = full resolution
  15606. // 1 = maximum foveation = the edges render at lower resolution
  15607. foveation = value;
  15608. if ( glProjLayer !== null ) {
  15609. glProjLayer.fixedFoveation = value;
  15610. }
  15611. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  15612. glBaseLayer.fixedFoveation = value;
  15613. }
  15614. };
  15615. this.getPlanes = function () {
  15616. return planes;
  15617. };
  15618. // Animation Loop
  15619. let onAnimationFrameCallback = null;
  15620. function onAnimationFrame( time, frame ) {
  15621. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  15622. xrFrame = frame;
  15623. if ( pose !== null ) {
  15624. const views = pose.views;
  15625. if ( glBaseLayer !== null ) {
  15626. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  15627. renderer.setRenderTarget( newRenderTarget );
  15628. }
  15629. let cameraVRNeedsUpdate = false;
  15630. // check if it's necessary to rebuild cameraVR's camera list
  15631. if ( views.length !== cameraVR.cameras.length ) {
  15632. cameraVR.cameras.length = 0;
  15633. cameraVRNeedsUpdate = true;
  15634. }
  15635. for ( let i = 0; i < views.length; i ++ ) {
  15636. const view = views[ i ];
  15637. let viewport = null;
  15638. if ( glBaseLayer !== null ) {
  15639. viewport = glBaseLayer.getViewport( view );
  15640. } else {
  15641. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  15642. viewport = glSubImage.viewport;
  15643. // For side-by-side projection, we only produce a single texture for both eyes.
  15644. if ( i === 0 ) {
  15645. renderer.setRenderTargetTextures(
  15646. newRenderTarget,
  15647. glSubImage.colorTexture,
  15648. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  15649. renderer.setRenderTarget( newRenderTarget );
  15650. }
  15651. }
  15652. let camera = cameras[ i ];
  15653. if ( camera === undefined ) {
  15654. camera = new PerspectiveCamera();
  15655. camera.layers.enable( i );
  15656. camera.viewport = new Vector4();
  15657. cameras[ i ] = camera;
  15658. }
  15659. camera.matrix.fromArray( view.transform.matrix );
  15660. camera.projectionMatrix.fromArray( view.projectionMatrix );
  15661. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  15662. if ( i === 0 ) {
  15663. cameraVR.matrix.copy( camera.matrix );
  15664. }
  15665. if ( cameraVRNeedsUpdate === true ) {
  15666. cameraVR.cameras.push( camera );
  15667. }
  15668. }
  15669. }
  15670. //
  15671. for ( let i = 0; i < controllers.length; i ++ ) {
  15672. const inputSource = controllerInputSources[ i ];
  15673. const controller = controllers[ i ];
  15674. if ( inputSource !== null && controller !== undefined ) {
  15675. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  15676. }
  15677. }
  15678. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  15679. if ( frame.detectedPlanes ) {
  15680. scope.dispatchEvent( { type: 'planesdetected', data: frame.detectedPlanes } );
  15681. let planesToRemove = null;
  15682. for ( const plane of planes ) {
  15683. if ( ! frame.detectedPlanes.has( plane ) ) {
  15684. if ( planesToRemove === null ) {
  15685. planesToRemove = [];
  15686. }
  15687. planesToRemove.push( plane );
  15688. }
  15689. }
  15690. if ( planesToRemove !== null ) {
  15691. for ( const plane of planesToRemove ) {
  15692. planes.delete( plane );
  15693. planesLastChangedTimes.delete( plane );
  15694. scope.dispatchEvent( { type: 'planeremoved', data: plane } );
  15695. }
  15696. }
  15697. for ( const plane of frame.detectedPlanes ) {
  15698. if ( ! planes.has( plane ) ) {
  15699. planes.add( plane );
  15700. planesLastChangedTimes.set( plane, frame.lastChangedTime );
  15701. scope.dispatchEvent( { type: 'planeadded', data: plane } );
  15702. } else {
  15703. const lastKnownTime = planesLastChangedTimes.get( plane );
  15704. if ( plane.lastChangedTime > lastKnownTime ) {
  15705. planesLastChangedTimes.set( plane, plane.lastChangedTime );
  15706. scope.dispatchEvent( { type: 'planechanged', data: plane } );
  15707. }
  15708. }
  15709. }
  15710. }
  15711. xrFrame = null;
  15712. }
  15713. const animation = new WebGLAnimation();
  15714. animation.setAnimationLoop( onAnimationFrame );
  15715. this.setAnimationLoop = function ( callback ) {
  15716. onAnimationFrameCallback = callback;
  15717. };
  15718. this.dispose = function () {};
  15719. }
  15720. }
  15721. function WebGLMaterials( renderer, properties ) {
  15722. function refreshFogUniforms( uniforms, fog ) {
  15723. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  15724. if ( fog.isFog ) {
  15725. uniforms.fogNear.value = fog.near;
  15726. uniforms.fogFar.value = fog.far;
  15727. } else if ( fog.isFogExp2 ) {
  15728. uniforms.fogDensity.value = fog.density;
  15729. }
  15730. }
  15731. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  15732. if ( material.isMeshBasicMaterial ) {
  15733. refreshUniformsCommon( uniforms, material );
  15734. } else if ( material.isMeshLambertMaterial ) {
  15735. refreshUniformsCommon( uniforms, material );
  15736. } else if ( material.isMeshToonMaterial ) {
  15737. refreshUniformsCommon( uniforms, material );
  15738. refreshUniformsToon( uniforms, material );
  15739. } else if ( material.isMeshPhongMaterial ) {
  15740. refreshUniformsCommon( uniforms, material );
  15741. refreshUniformsPhong( uniforms, material );
  15742. } else if ( material.isMeshStandardMaterial ) {
  15743. refreshUniformsCommon( uniforms, material );
  15744. refreshUniformsStandard( uniforms, material );
  15745. if ( material.isMeshPhysicalMaterial ) {
  15746. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  15747. }
  15748. } else if ( material.isMeshMatcapMaterial ) {
  15749. refreshUniformsCommon( uniforms, material );
  15750. refreshUniformsMatcap( uniforms, material );
  15751. } else if ( material.isMeshDepthMaterial ) {
  15752. refreshUniformsCommon( uniforms, material );
  15753. } else if ( material.isMeshDistanceMaterial ) {
  15754. refreshUniformsCommon( uniforms, material );
  15755. refreshUniformsDistance( uniforms, material );
  15756. } else if ( material.isMeshNormalMaterial ) {
  15757. refreshUniformsCommon( uniforms, material );
  15758. } else if ( material.isLineBasicMaterial ) {
  15759. refreshUniformsLine( uniforms, material );
  15760. if ( material.isLineDashedMaterial ) {
  15761. refreshUniformsDash( uniforms, material );
  15762. }
  15763. } else if ( material.isPointsMaterial ) {
  15764. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  15765. } else if ( material.isSpriteMaterial ) {
  15766. refreshUniformsSprites( uniforms, material );
  15767. } else if ( material.isShadowMaterial ) {
  15768. uniforms.color.value.copy( material.color );
  15769. uniforms.opacity.value = material.opacity;
  15770. } else if ( material.isShaderMaterial ) {
  15771. material.uniformsNeedUpdate = false; // #15581
  15772. }
  15773. }
  15774. function refreshUniformsCommon( uniforms, material ) {
  15775. uniforms.opacity.value = material.opacity;
  15776. if ( material.color ) {
  15777. uniforms.diffuse.value.copy( material.color );
  15778. }
  15779. if ( material.emissive ) {
  15780. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  15781. }
  15782. if ( material.map ) {
  15783. uniforms.map.value = material.map;
  15784. }
  15785. if ( material.alphaMap ) {
  15786. uniforms.alphaMap.value = material.alphaMap;
  15787. }
  15788. if ( material.bumpMap ) {
  15789. uniforms.bumpMap.value = material.bumpMap;
  15790. uniforms.bumpScale.value = material.bumpScale;
  15791. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  15792. }
  15793. if ( material.displacementMap ) {
  15794. uniforms.displacementMap.value = material.displacementMap;
  15795. uniforms.displacementScale.value = material.displacementScale;
  15796. uniforms.displacementBias.value = material.displacementBias;
  15797. }
  15798. if ( material.emissiveMap ) {
  15799. uniforms.emissiveMap.value = material.emissiveMap;
  15800. }
  15801. if ( material.normalMap ) {
  15802. uniforms.normalMap.value = material.normalMap;
  15803. uniforms.normalScale.value.copy( material.normalScale );
  15804. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  15805. }
  15806. if ( material.specularMap ) {
  15807. uniforms.specularMap.value = material.specularMap;
  15808. }
  15809. if ( material.alphaTest > 0 ) {
  15810. uniforms.alphaTest.value = material.alphaTest;
  15811. }
  15812. const envMap = properties.get( material ).envMap;
  15813. if ( envMap ) {
  15814. uniforms.envMap.value = envMap;
  15815. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  15816. uniforms.reflectivity.value = material.reflectivity;
  15817. uniforms.ior.value = material.ior;
  15818. uniforms.refractionRatio.value = material.refractionRatio;
  15819. }
  15820. if ( material.lightMap ) {
  15821. uniforms.lightMap.value = material.lightMap;
  15822. // artist-friendly light intensity scaling factor
  15823. const scaleFactor = ( renderer.useLegacyLights === true ) ? Math.PI : 1;
  15824. uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor;
  15825. }
  15826. if ( material.aoMap ) {
  15827. uniforms.aoMap.value = material.aoMap;
  15828. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15829. }
  15830. // uv repeat and offset setting priorities
  15831. // 1. color map
  15832. // 2. specular map
  15833. // 3. displacementMap map
  15834. // 4. normal map
  15835. // 5. bump map
  15836. // 6. roughnessMap map
  15837. // 7. metalnessMap map
  15838. // 8. alphaMap map
  15839. // 9. emissiveMap map
  15840. // 10. clearcoat map
  15841. // 11. clearcoat normal map
  15842. // 12. clearcoat roughnessMap map
  15843. // 13. iridescence map
  15844. // 14. iridescence thickness map
  15845. // 15. specular intensity map
  15846. // 16. specular tint map
  15847. // 17. transmission map
  15848. // 18. thickness map
  15849. let uvScaleMap;
  15850. if ( material.map ) {
  15851. uvScaleMap = material.map;
  15852. } else if ( material.specularMap ) {
  15853. uvScaleMap = material.specularMap;
  15854. } else if ( material.displacementMap ) {
  15855. uvScaleMap = material.displacementMap;
  15856. } else if ( material.normalMap ) {
  15857. uvScaleMap = material.normalMap;
  15858. } else if ( material.bumpMap ) {
  15859. uvScaleMap = material.bumpMap;
  15860. } else if ( material.roughnessMap ) {
  15861. uvScaleMap = material.roughnessMap;
  15862. } else if ( material.metalnessMap ) {
  15863. uvScaleMap = material.metalnessMap;
  15864. } else if ( material.alphaMap ) {
  15865. uvScaleMap = material.alphaMap;
  15866. } else if ( material.emissiveMap ) {
  15867. uvScaleMap = material.emissiveMap;
  15868. } else if ( material.clearcoatMap ) {
  15869. uvScaleMap = material.clearcoatMap;
  15870. } else if ( material.clearcoatNormalMap ) {
  15871. uvScaleMap = material.clearcoatNormalMap;
  15872. } else if ( material.clearcoatRoughnessMap ) {
  15873. uvScaleMap = material.clearcoatRoughnessMap;
  15874. } else if ( material.iridescenceMap ) {
  15875. uvScaleMap = material.iridescenceMap;
  15876. } else if ( material.iridescenceThicknessMap ) {
  15877. uvScaleMap = material.iridescenceThicknessMap;
  15878. } else if ( material.specularIntensityMap ) {
  15879. uvScaleMap = material.specularIntensityMap;
  15880. } else if ( material.specularColorMap ) {
  15881. uvScaleMap = material.specularColorMap;
  15882. } else if ( material.transmissionMap ) {
  15883. uvScaleMap = material.transmissionMap;
  15884. } else if ( material.thicknessMap ) {
  15885. uvScaleMap = material.thicknessMap;
  15886. } else if ( material.sheenColorMap ) {
  15887. uvScaleMap = material.sheenColorMap;
  15888. } else if ( material.sheenRoughnessMap ) {
  15889. uvScaleMap = material.sheenRoughnessMap;
  15890. }
  15891. if ( uvScaleMap !== undefined ) {
  15892. // backwards compatibility
  15893. if ( uvScaleMap.isWebGLRenderTarget ) {
  15894. uvScaleMap = uvScaleMap.texture;
  15895. }
  15896. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15897. uvScaleMap.updateMatrix();
  15898. }
  15899. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15900. }
  15901. // uv repeat and offset setting priorities for uv2
  15902. // 1. ao map
  15903. // 2. light map
  15904. let uv2ScaleMap;
  15905. if ( material.aoMap ) {
  15906. uv2ScaleMap = material.aoMap;
  15907. } else if ( material.lightMap ) {
  15908. uv2ScaleMap = material.lightMap;
  15909. }
  15910. if ( uv2ScaleMap !== undefined ) {
  15911. // backwards compatibility
  15912. if ( uv2ScaleMap.isWebGLRenderTarget ) {
  15913. uv2ScaleMap = uv2ScaleMap.texture;
  15914. }
  15915. if ( uv2ScaleMap.matrixAutoUpdate === true ) {
  15916. uv2ScaleMap.updateMatrix();
  15917. }
  15918. uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );
  15919. }
  15920. }
  15921. function refreshUniformsLine( uniforms, material ) {
  15922. uniforms.diffuse.value.copy( material.color );
  15923. uniforms.opacity.value = material.opacity;
  15924. }
  15925. function refreshUniformsDash( uniforms, material ) {
  15926. uniforms.dashSize.value = material.dashSize;
  15927. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15928. uniforms.scale.value = material.scale;
  15929. }
  15930. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  15931. uniforms.diffuse.value.copy( material.color );
  15932. uniforms.opacity.value = material.opacity;
  15933. uniforms.size.value = material.size * pixelRatio;
  15934. uniforms.scale.value = height * 0.5;
  15935. if ( material.map ) {
  15936. uniforms.map.value = material.map;
  15937. }
  15938. if ( material.alphaMap ) {
  15939. uniforms.alphaMap.value = material.alphaMap;
  15940. }
  15941. if ( material.alphaTest > 0 ) {
  15942. uniforms.alphaTest.value = material.alphaTest;
  15943. }
  15944. // uv repeat and offset setting priorities
  15945. // 1. color map
  15946. // 2. alpha map
  15947. let uvScaleMap;
  15948. if ( material.map ) {
  15949. uvScaleMap = material.map;
  15950. } else if ( material.alphaMap ) {
  15951. uvScaleMap = material.alphaMap;
  15952. }
  15953. if ( uvScaleMap !== undefined ) {
  15954. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15955. uvScaleMap.updateMatrix();
  15956. }
  15957. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15958. }
  15959. }
  15960. function refreshUniformsSprites( uniforms, material ) {
  15961. uniforms.diffuse.value.copy( material.color );
  15962. uniforms.opacity.value = material.opacity;
  15963. uniforms.rotation.value = material.rotation;
  15964. if ( material.map ) {
  15965. uniforms.map.value = material.map;
  15966. }
  15967. if ( material.alphaMap ) {
  15968. uniforms.alphaMap.value = material.alphaMap;
  15969. }
  15970. if ( material.alphaTest > 0 ) {
  15971. uniforms.alphaTest.value = material.alphaTest;
  15972. }
  15973. // uv repeat and offset setting priorities
  15974. // 1. color map
  15975. // 2. alpha map
  15976. let uvScaleMap;
  15977. if ( material.map ) {
  15978. uvScaleMap = material.map;
  15979. } else if ( material.alphaMap ) {
  15980. uvScaleMap = material.alphaMap;
  15981. }
  15982. if ( uvScaleMap !== undefined ) {
  15983. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15984. uvScaleMap.updateMatrix();
  15985. }
  15986. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15987. }
  15988. }
  15989. function refreshUniformsPhong( uniforms, material ) {
  15990. uniforms.specular.value.copy( material.specular );
  15991. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15992. }
  15993. function refreshUniformsToon( uniforms, material ) {
  15994. if ( material.gradientMap ) {
  15995. uniforms.gradientMap.value = material.gradientMap;
  15996. }
  15997. }
  15998. function refreshUniformsStandard( uniforms, material ) {
  15999. uniforms.roughness.value = material.roughness;
  16000. uniforms.metalness.value = material.metalness;
  16001. if ( material.roughnessMap ) {
  16002. uniforms.roughnessMap.value = material.roughnessMap;
  16003. }
  16004. if ( material.metalnessMap ) {
  16005. uniforms.metalnessMap.value = material.metalnessMap;
  16006. }
  16007. const envMap = properties.get( material ).envMap;
  16008. if ( envMap ) {
  16009. //uniforms.envMap.value = material.envMap; // part of uniforms common
  16010. uniforms.envMapIntensity.value = material.envMapIntensity;
  16011. }
  16012. }
  16013. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  16014. uniforms.ior.value = material.ior; // also part of uniforms common
  16015. if ( material.sheen > 0 ) {
  16016. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  16017. uniforms.sheenRoughness.value = material.sheenRoughness;
  16018. if ( material.sheenColorMap ) {
  16019. uniforms.sheenColorMap.value = material.sheenColorMap;
  16020. }
  16021. if ( material.sheenRoughnessMap ) {
  16022. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  16023. }
  16024. }
  16025. if ( material.clearcoat > 0 ) {
  16026. uniforms.clearcoat.value = material.clearcoat;
  16027. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  16028. if ( material.clearcoatMap ) {
  16029. uniforms.clearcoatMap.value = material.clearcoatMap;
  16030. }
  16031. if ( material.clearcoatRoughnessMap ) {
  16032. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  16033. }
  16034. if ( material.clearcoatNormalMap ) {
  16035. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  16036. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  16037. if ( material.side === BackSide ) {
  16038. uniforms.clearcoatNormalScale.value.negate();
  16039. }
  16040. }
  16041. }
  16042. if ( material.iridescence > 0 ) {
  16043. uniforms.iridescence.value = material.iridescence;
  16044. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  16045. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  16046. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  16047. if ( material.iridescenceMap ) {
  16048. uniforms.iridescenceMap.value = material.iridescenceMap;
  16049. }
  16050. if ( material.iridescenceThicknessMap ) {
  16051. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  16052. }
  16053. }
  16054. if ( material.transmission > 0 ) {
  16055. uniforms.transmission.value = material.transmission;
  16056. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  16057. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  16058. if ( material.transmissionMap ) {
  16059. uniforms.transmissionMap.value = material.transmissionMap;
  16060. }
  16061. uniforms.thickness.value = material.thickness;
  16062. if ( material.thicknessMap ) {
  16063. uniforms.thicknessMap.value = material.thicknessMap;
  16064. }
  16065. uniforms.attenuationDistance.value = material.attenuationDistance;
  16066. uniforms.attenuationColor.value.copy( material.attenuationColor );
  16067. }
  16068. uniforms.specularIntensity.value = material.specularIntensity;
  16069. uniforms.specularColor.value.copy( material.specularColor );
  16070. if ( material.specularIntensityMap ) {
  16071. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  16072. }
  16073. if ( material.specularColorMap ) {
  16074. uniforms.specularColorMap.value = material.specularColorMap;
  16075. }
  16076. }
  16077. function refreshUniformsMatcap( uniforms, material ) {
  16078. if ( material.matcap ) {
  16079. uniforms.matcap.value = material.matcap;
  16080. }
  16081. }
  16082. function refreshUniformsDistance( uniforms, material ) {
  16083. uniforms.referencePosition.value.copy( material.referencePosition );
  16084. uniforms.nearDistance.value = material.nearDistance;
  16085. uniforms.farDistance.value = material.farDistance;
  16086. }
  16087. return {
  16088. refreshFogUniforms: refreshFogUniforms,
  16089. refreshMaterialUniforms: refreshMaterialUniforms
  16090. };
  16091. }
  16092. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  16093. let buffers = {};
  16094. let updateList = {};
  16095. let allocatedBindingPoints = [];
  16096. const maxBindingPoints = ( capabilities.isWebGL2 ) ? gl.getParameter( 35375 ) : 0; // binding points are global whereas block indices are per shader program
  16097. function bind( uniformsGroup, program ) {
  16098. const webglProgram = program.program;
  16099. state.uniformBlockBinding( uniformsGroup, webglProgram );
  16100. }
  16101. function update( uniformsGroup, program ) {
  16102. let buffer = buffers[ uniformsGroup.id ];
  16103. if ( buffer === undefined ) {
  16104. prepareUniformsGroup( uniformsGroup );
  16105. buffer = createBuffer( uniformsGroup );
  16106. buffers[ uniformsGroup.id ] = buffer;
  16107. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  16108. }
  16109. // ensure to update the binding points/block indices mapping for this program
  16110. const webglProgram = program.program;
  16111. state.updateUBOMapping( uniformsGroup, webglProgram );
  16112. // update UBO once per frame
  16113. const frame = info.render.frame;
  16114. if ( updateList[ uniformsGroup.id ] !== frame ) {
  16115. updateBufferData( uniformsGroup );
  16116. updateList[ uniformsGroup.id ] = frame;
  16117. }
  16118. }
  16119. function createBuffer( uniformsGroup ) {
  16120. // the setup of an UBO is independent of a particular shader program but global
  16121. const bindingPointIndex = allocateBindingPointIndex();
  16122. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  16123. const buffer = gl.createBuffer();
  16124. const size = uniformsGroup.__size;
  16125. const usage = uniformsGroup.usage;
  16126. gl.bindBuffer( 35345, buffer );
  16127. gl.bufferData( 35345, size, usage );
  16128. gl.bindBuffer( 35345, null );
  16129. gl.bindBufferBase( 35345, bindingPointIndex, buffer );
  16130. return buffer;
  16131. }
  16132. function allocateBindingPointIndex() {
  16133. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  16134. if ( allocatedBindingPoints.indexOf( i ) === - 1 ) {
  16135. allocatedBindingPoints.push( i );
  16136. return i;
  16137. }
  16138. }
  16139. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  16140. return 0;
  16141. }
  16142. function updateBufferData( uniformsGroup ) {
  16143. const buffer = buffers[ uniformsGroup.id ];
  16144. const uniforms = uniformsGroup.uniforms;
  16145. const cache = uniformsGroup.__cache;
  16146. gl.bindBuffer( 35345, buffer );
  16147. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  16148. const uniform = uniforms[ i ];
  16149. // partly update the buffer if necessary
  16150. if ( hasUniformChanged( uniform, i, cache ) === true ) {
  16151. const offset = uniform.__offset;
  16152. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16153. let arrayOffset = 0;
  16154. for ( let i = 0; i < values.length; i ++ ) {
  16155. const value = values[ i ];
  16156. const info = getUniformSize( value );
  16157. if ( typeof value === 'number' ) {
  16158. uniform.__data[ 0 ] = value;
  16159. gl.bufferSubData( 35345, offset + arrayOffset, uniform.__data );
  16160. } else if ( value.isMatrix3 ) {
  16161. // manually converting 3x3 to 3x4
  16162. uniform.__data[ 0 ] = value.elements[ 0 ];
  16163. uniform.__data[ 1 ] = value.elements[ 1 ];
  16164. uniform.__data[ 2 ] = value.elements[ 2 ];
  16165. uniform.__data[ 3 ] = value.elements[ 0 ];
  16166. uniform.__data[ 4 ] = value.elements[ 3 ];
  16167. uniform.__data[ 5 ] = value.elements[ 4 ];
  16168. uniform.__data[ 6 ] = value.elements[ 5 ];
  16169. uniform.__data[ 7 ] = value.elements[ 0 ];
  16170. uniform.__data[ 8 ] = value.elements[ 6 ];
  16171. uniform.__data[ 9 ] = value.elements[ 7 ];
  16172. uniform.__data[ 10 ] = value.elements[ 8 ];
  16173. uniform.__data[ 11 ] = value.elements[ 0 ];
  16174. } else {
  16175. value.toArray( uniform.__data, arrayOffset );
  16176. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  16177. }
  16178. }
  16179. gl.bufferSubData( 35345, offset, uniform.__data );
  16180. }
  16181. }
  16182. gl.bindBuffer( 35345, null );
  16183. }
  16184. function hasUniformChanged( uniform, index, cache ) {
  16185. const value = uniform.value;
  16186. if ( cache[ index ] === undefined ) {
  16187. // cache entry does not exist so far
  16188. if ( typeof value === 'number' ) {
  16189. cache[ index ] = value;
  16190. } else {
  16191. const values = Array.isArray( value ) ? value : [ value ];
  16192. const tempValues = [];
  16193. for ( let i = 0; i < values.length; i ++ ) {
  16194. tempValues.push( values[ i ].clone() );
  16195. }
  16196. cache[ index ] = tempValues;
  16197. }
  16198. return true;
  16199. } else {
  16200. // compare current value with cached entry
  16201. if ( typeof value === 'number' ) {
  16202. if ( cache[ index ] !== value ) {
  16203. cache[ index ] = value;
  16204. return true;
  16205. }
  16206. } else {
  16207. const cachedObjects = Array.isArray( cache[ index ] ) ? cache[ index ] : [ cache[ index ] ];
  16208. const values = Array.isArray( value ) ? value : [ value ];
  16209. for ( let i = 0; i < cachedObjects.length; i ++ ) {
  16210. const cachedObject = cachedObjects[ i ];
  16211. if ( cachedObject.equals( values[ i ] ) === false ) {
  16212. cachedObject.copy( values[ i ] );
  16213. return true;
  16214. }
  16215. }
  16216. }
  16217. }
  16218. return false;
  16219. }
  16220. function prepareUniformsGroup( uniformsGroup ) {
  16221. // determine total buffer size according to the STD140 layout
  16222. // Hint: STD140 is the only supported layout in WebGL 2
  16223. const uniforms = uniformsGroup.uniforms;
  16224. let offset = 0; // global buffer offset in bytes
  16225. const chunkSize = 16; // size of a chunk in bytes
  16226. let chunkOffset = 0; // offset within a single chunk in bytes
  16227. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  16228. const uniform = uniforms[ i ];
  16229. const infos = {
  16230. boundary: 0, // bytes
  16231. storage: 0 // bytes
  16232. };
  16233. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  16234. for ( let j = 0, jl = values.length; j < jl; j ++ ) {
  16235. const value = values[ j ];
  16236. const info = getUniformSize( value );
  16237. infos.boundary += info.boundary;
  16238. infos.storage += info.storage;
  16239. }
  16240. // the following two properties will be used for partial buffer updates
  16241. uniform.__data = new Float32Array( infos.storage / Float32Array.BYTES_PER_ELEMENT );
  16242. uniform.__offset = offset;
  16243. //
  16244. if ( i > 0 ) {
  16245. chunkOffset = offset % chunkSize;
  16246. const remainingSizeInChunk = chunkSize - chunkOffset;
  16247. // check for chunk overflow
  16248. if ( chunkOffset !== 0 && ( remainingSizeInChunk - infos.boundary ) < 0 ) {
  16249. // add padding and adjust offset
  16250. offset += ( chunkSize - chunkOffset );
  16251. uniform.__offset = offset;
  16252. }
  16253. }
  16254. offset += infos.storage;
  16255. }
  16256. // ensure correct final padding
  16257. chunkOffset = offset % chunkSize;
  16258. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  16259. //
  16260. uniformsGroup.__size = offset;
  16261. uniformsGroup.__cache = {};
  16262. return this;
  16263. }
  16264. function getUniformSize( value ) {
  16265. const info = {
  16266. boundary: 0, // bytes
  16267. storage: 0 // bytes
  16268. };
  16269. // determine sizes according to STD140
  16270. if ( typeof value === 'number' ) {
  16271. // float/int
  16272. info.boundary = 4;
  16273. info.storage = 4;
  16274. } else if ( value.isVector2 ) {
  16275. // vec2
  16276. info.boundary = 8;
  16277. info.storage = 8;
  16278. } else if ( value.isVector3 || value.isColor ) {
  16279. // vec3
  16280. info.boundary = 16;
  16281. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  16282. } else if ( value.isVector4 ) {
  16283. // vec4
  16284. info.boundary = 16;
  16285. info.storage = 16;
  16286. } else if ( value.isMatrix3 ) {
  16287. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  16288. info.boundary = 48;
  16289. info.storage = 48;
  16290. } else if ( value.isMatrix4 ) {
  16291. // mat4
  16292. info.boundary = 64;
  16293. info.storage = 64;
  16294. } else if ( value.isTexture ) {
  16295. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  16296. } else {
  16297. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  16298. }
  16299. return info;
  16300. }
  16301. function onUniformsGroupsDispose( event ) {
  16302. const uniformsGroup = event.target;
  16303. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  16304. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  16305. allocatedBindingPoints.splice( index, 1 );
  16306. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  16307. delete buffers[ uniformsGroup.id ];
  16308. delete updateList[ uniformsGroup.id ];
  16309. }
  16310. function dispose() {
  16311. for ( const id in buffers ) {
  16312. gl.deleteBuffer( buffers[ id ] );
  16313. }
  16314. allocatedBindingPoints = [];
  16315. buffers = {};
  16316. updateList = {};
  16317. }
  16318. return {
  16319. bind: bind,
  16320. update: update,
  16321. dispose: dispose
  16322. };
  16323. }
  16324. function createCanvasElement() {
  16325. const canvas = createElementNS( 'canvas' );
  16326. canvas.style.display = 'block';
  16327. return canvas;
  16328. }
  16329. function WebGLRenderer( parameters = {} ) {
  16330. this.isWebGLRenderer = true;
  16331. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  16332. _context = parameters.context !== undefined ? parameters.context : null,
  16333. _depth = parameters.depth !== undefined ? parameters.depth : true,
  16334. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  16335. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  16336. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  16337. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  16338. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  16339. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  16340. let _alpha;
  16341. if ( _context !== null ) {
  16342. _alpha = _context.getContextAttributes().alpha;
  16343. } else {
  16344. _alpha = parameters.alpha !== undefined ? parameters.alpha : false;
  16345. }
  16346. let currentRenderList = null;
  16347. let currentRenderState = null;
  16348. // render() can be called from within a callback triggered by another render.
  16349. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  16350. const renderListStack = [];
  16351. const renderStateStack = [];
  16352. // public properties
  16353. this.domElement = _canvas;
  16354. // Debug configuration container
  16355. this.debug = {
  16356. /**
  16357. * Enables error checking and reporting when shader programs are being compiled
  16358. * @type {boolean}
  16359. */
  16360. checkShaderErrors: true
  16361. };
  16362. // clearing
  16363. this.autoClear = true;
  16364. this.autoClearColor = true;
  16365. this.autoClearDepth = true;
  16366. this.autoClearStencil = true;
  16367. // scene graph
  16368. this.sortObjects = true;
  16369. // user-defined clipping
  16370. this.clippingPlanes = [];
  16371. this.localClippingEnabled = false;
  16372. // physically based shading
  16373. this.outputEncoding = LinearEncoding;
  16374. // physical lights
  16375. this.useLegacyLights = true;
  16376. // tone mapping
  16377. this.toneMapping = NoToneMapping;
  16378. this.toneMappingExposure = 1.0;
  16379. // internal properties
  16380. const _this = this;
  16381. let _isContextLost = false;
  16382. // internal state cache
  16383. let _currentActiveCubeFace = 0;
  16384. let _currentActiveMipmapLevel = 0;
  16385. let _currentRenderTarget = null;
  16386. let _currentMaterialId = - 1;
  16387. let _currentCamera = null;
  16388. const _currentViewport = new Vector4();
  16389. const _currentScissor = new Vector4();
  16390. let _currentScissorTest = null;
  16391. //
  16392. let _width = _canvas.width;
  16393. let _height = _canvas.height;
  16394. let _pixelRatio = 1;
  16395. let _opaqueSort = null;
  16396. let _transparentSort = null;
  16397. const _viewport = new Vector4( 0, 0, _width, _height );
  16398. const _scissor = new Vector4( 0, 0, _width, _height );
  16399. let _scissorTest = false;
  16400. // frustum
  16401. const _frustum = new Frustum();
  16402. // clipping
  16403. let _clippingEnabled = false;
  16404. let _localClippingEnabled = false;
  16405. // transmission
  16406. let _transmissionRenderTarget = null;
  16407. // camera matrices cache
  16408. const _projScreenMatrix = new Matrix4();
  16409. const _vector3 = new Vector3();
  16410. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  16411. function getTargetPixelRatio() {
  16412. return _currentRenderTarget === null ? _pixelRatio : 1;
  16413. }
  16414. // initialize
  16415. let _gl = _context;
  16416. function getContext( contextNames, contextAttributes ) {
  16417. for ( let i = 0; i < contextNames.length; i ++ ) {
  16418. const contextName = contextNames[ i ];
  16419. const context = _canvas.getContext( contextName, contextAttributes );
  16420. if ( context !== null ) return context;
  16421. }
  16422. return null;
  16423. }
  16424. try {
  16425. const contextAttributes = {
  16426. alpha: true,
  16427. depth: _depth,
  16428. stencil: _stencil,
  16429. antialias: _antialias,
  16430. premultipliedAlpha: _premultipliedAlpha,
  16431. preserveDrawingBuffer: _preserveDrawingBuffer,
  16432. powerPreference: _powerPreference,
  16433. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  16434. };
  16435. // OffscreenCanvas does not have setAttribute, see #22811
  16436. if ( 'setAttribute' in _canvas ) _canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  16437. // event listeners must be registered before WebGL context is created, see #12753
  16438. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  16439. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  16440. _canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16441. if ( _gl === null ) {
  16442. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  16443. if ( _this.isWebGL1Renderer === true ) {
  16444. contextNames.shift();
  16445. }
  16446. _gl = getContext( contextNames, contextAttributes );
  16447. if ( _gl === null ) {
  16448. if ( getContext( contextNames ) ) {
  16449. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  16450. } else {
  16451. throw new Error( 'Error creating WebGL context.' );
  16452. }
  16453. }
  16454. }
  16455. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  16456. if ( _gl.getShaderPrecisionFormat === undefined ) {
  16457. _gl.getShaderPrecisionFormat = function () {
  16458. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  16459. };
  16460. }
  16461. } catch ( error ) {
  16462. console.error( 'THREE.WebGLRenderer: ' + error.message );
  16463. throw error;
  16464. }
  16465. let extensions, capabilities, state, info;
  16466. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  16467. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  16468. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  16469. let utils, bindingStates, uniformsGroups;
  16470. function initGLContext() {
  16471. extensions = new WebGLExtensions( _gl );
  16472. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  16473. extensions.init( capabilities );
  16474. utils = new WebGLUtils( _gl, extensions, capabilities );
  16475. state = new WebGLState( _gl, extensions, capabilities );
  16476. info = new WebGLInfo();
  16477. properties = new WebGLProperties();
  16478. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  16479. cubemaps = new WebGLCubeMaps( _this );
  16480. cubeuvmaps = new WebGLCubeUVMaps( _this );
  16481. attributes = new WebGLAttributes( _gl, capabilities );
  16482. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  16483. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  16484. objects = new WebGLObjects( _gl, geometries, attributes, info );
  16485. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  16486. clipping = new WebGLClipping( properties );
  16487. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  16488. materials = new WebGLMaterials( _this, properties );
  16489. renderLists = new WebGLRenderLists();
  16490. renderStates = new WebGLRenderStates( extensions, capabilities );
  16491. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, _premultipliedAlpha );
  16492. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  16493. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  16494. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  16495. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  16496. info.programs = programCache.programs;
  16497. _this.capabilities = capabilities;
  16498. _this.extensions = extensions;
  16499. _this.properties = properties;
  16500. _this.renderLists = renderLists;
  16501. _this.shadowMap = shadowMap;
  16502. _this.state = state;
  16503. _this.info = info;
  16504. }
  16505. initGLContext();
  16506. // xr
  16507. const xr = new WebXRManager( _this, _gl );
  16508. this.xr = xr;
  16509. // API
  16510. this.getContext = function () {
  16511. return _gl;
  16512. };
  16513. this.getContextAttributes = function () {
  16514. return _gl.getContextAttributes();
  16515. };
  16516. this.forceContextLoss = function () {
  16517. const extension = extensions.get( 'WEBGL_lose_context' );
  16518. if ( extension ) extension.loseContext();
  16519. };
  16520. this.forceContextRestore = function () {
  16521. const extension = extensions.get( 'WEBGL_lose_context' );
  16522. if ( extension ) extension.restoreContext();
  16523. };
  16524. this.getPixelRatio = function () {
  16525. return _pixelRatio;
  16526. };
  16527. this.setPixelRatio = function ( value ) {
  16528. if ( value === undefined ) return;
  16529. _pixelRatio = value;
  16530. this.setSize( _width, _height, false );
  16531. };
  16532. this.getSize = function ( target ) {
  16533. return target.set( _width, _height );
  16534. };
  16535. this.setSize = function ( width, height, updateStyle = true ) {
  16536. if ( xr.isPresenting ) {
  16537. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  16538. return;
  16539. }
  16540. _width = width;
  16541. _height = height;
  16542. _canvas.width = Math.floor( width * _pixelRatio );
  16543. _canvas.height = Math.floor( height * _pixelRatio );
  16544. if ( updateStyle === true ) {
  16545. _canvas.style.width = width + 'px';
  16546. _canvas.style.height = height + 'px';
  16547. }
  16548. this.setViewport( 0, 0, width, height );
  16549. };
  16550. this.getDrawingBufferSize = function ( target ) {
  16551. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  16552. };
  16553. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  16554. _width = width;
  16555. _height = height;
  16556. _pixelRatio = pixelRatio;
  16557. _canvas.width = Math.floor( width * pixelRatio );
  16558. _canvas.height = Math.floor( height * pixelRatio );
  16559. this.setViewport( 0, 0, width, height );
  16560. };
  16561. this.getCurrentViewport = function ( target ) {
  16562. return target.copy( _currentViewport );
  16563. };
  16564. this.getViewport = function ( target ) {
  16565. return target.copy( _viewport );
  16566. };
  16567. this.setViewport = function ( x, y, width, height ) {
  16568. if ( x.isVector4 ) {
  16569. _viewport.set( x.x, x.y, x.z, x.w );
  16570. } else {
  16571. _viewport.set( x, y, width, height );
  16572. }
  16573. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  16574. };
  16575. this.getScissor = function ( target ) {
  16576. return target.copy( _scissor );
  16577. };
  16578. this.setScissor = function ( x, y, width, height ) {
  16579. if ( x.isVector4 ) {
  16580. _scissor.set( x.x, x.y, x.z, x.w );
  16581. } else {
  16582. _scissor.set( x, y, width, height );
  16583. }
  16584. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  16585. };
  16586. this.getScissorTest = function () {
  16587. return _scissorTest;
  16588. };
  16589. this.setScissorTest = function ( boolean ) {
  16590. state.setScissorTest( _scissorTest = boolean );
  16591. };
  16592. this.setOpaqueSort = function ( method ) {
  16593. _opaqueSort = method;
  16594. };
  16595. this.setTransparentSort = function ( method ) {
  16596. _transparentSort = method;
  16597. };
  16598. // Clearing
  16599. this.getClearColor = function ( target ) {
  16600. return target.copy( background.getClearColor() );
  16601. };
  16602. this.setClearColor = function () {
  16603. background.setClearColor.apply( background, arguments );
  16604. };
  16605. this.getClearAlpha = function () {
  16606. return background.getClearAlpha();
  16607. };
  16608. this.setClearAlpha = function () {
  16609. background.setClearAlpha.apply( background, arguments );
  16610. };
  16611. this.clear = function ( color = true, depth = true, stencil = true ) {
  16612. let bits = 0;
  16613. if ( color ) bits |= 16384;
  16614. if ( depth ) bits |= 256;
  16615. if ( stencil ) bits |= 1024;
  16616. _gl.clear( bits );
  16617. };
  16618. this.clearColor = function () {
  16619. this.clear( true, false, false );
  16620. };
  16621. this.clearDepth = function () {
  16622. this.clear( false, true, false );
  16623. };
  16624. this.clearStencil = function () {
  16625. this.clear( false, false, true );
  16626. };
  16627. //
  16628. this.dispose = function () {
  16629. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  16630. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  16631. _canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16632. renderLists.dispose();
  16633. renderStates.dispose();
  16634. properties.dispose();
  16635. cubemaps.dispose();
  16636. cubeuvmaps.dispose();
  16637. objects.dispose();
  16638. bindingStates.dispose();
  16639. uniformsGroups.dispose();
  16640. programCache.dispose();
  16641. xr.dispose();
  16642. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  16643. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  16644. if ( _transmissionRenderTarget ) {
  16645. _transmissionRenderTarget.dispose();
  16646. _transmissionRenderTarget = null;
  16647. }
  16648. animation.stop();
  16649. };
  16650. // Events
  16651. function onContextLost( event ) {
  16652. event.preventDefault();
  16653. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  16654. _isContextLost = true;
  16655. }
  16656. function onContextRestore( /* event */ ) {
  16657. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  16658. _isContextLost = false;
  16659. const infoAutoReset = info.autoReset;
  16660. const shadowMapEnabled = shadowMap.enabled;
  16661. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  16662. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  16663. const shadowMapType = shadowMap.type;
  16664. initGLContext();
  16665. info.autoReset = infoAutoReset;
  16666. shadowMap.enabled = shadowMapEnabled;
  16667. shadowMap.autoUpdate = shadowMapAutoUpdate;
  16668. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  16669. shadowMap.type = shadowMapType;
  16670. }
  16671. function onContextCreationError( event ) {
  16672. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  16673. }
  16674. function onMaterialDispose( event ) {
  16675. const material = event.target;
  16676. material.removeEventListener( 'dispose', onMaterialDispose );
  16677. deallocateMaterial( material );
  16678. }
  16679. // Buffer deallocation
  16680. function deallocateMaterial( material ) {
  16681. releaseMaterialProgramReferences( material );
  16682. properties.remove( material );
  16683. }
  16684. function releaseMaterialProgramReferences( material ) {
  16685. const programs = properties.get( material ).programs;
  16686. if ( programs !== undefined ) {
  16687. programs.forEach( function ( program ) {
  16688. programCache.releaseProgram( program );
  16689. } );
  16690. if ( material.isShaderMaterial ) {
  16691. programCache.releaseShaderCache( material );
  16692. }
  16693. }
  16694. }
  16695. // Buffer rendering
  16696. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  16697. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  16698. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  16699. const program = setProgram( camera, scene, geometry, material, object );
  16700. state.setMaterial( material, frontFaceCW );
  16701. //
  16702. let index = geometry.index;
  16703. let rangeFactor = 1;
  16704. if ( material.wireframe === true ) {
  16705. index = geometries.getWireframeAttribute( geometry );
  16706. rangeFactor = 2;
  16707. }
  16708. //
  16709. const drawRange = geometry.drawRange;
  16710. const position = geometry.attributes.position;
  16711. let drawStart = drawRange.start * rangeFactor;
  16712. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  16713. if ( group !== null ) {
  16714. drawStart = Math.max( drawStart, group.start * rangeFactor );
  16715. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  16716. }
  16717. if ( index !== null ) {
  16718. drawStart = Math.max( drawStart, 0 );
  16719. drawEnd = Math.min( drawEnd, index.count );
  16720. } else if ( position !== undefined && position !== null ) {
  16721. drawStart = Math.max( drawStart, 0 );
  16722. drawEnd = Math.min( drawEnd, position.count );
  16723. }
  16724. const drawCount = drawEnd - drawStart;
  16725. if ( drawCount < 0 || drawCount === Infinity ) return;
  16726. //
  16727. bindingStates.setup( object, material, program, geometry, index );
  16728. let attribute;
  16729. let renderer = bufferRenderer;
  16730. if ( index !== null ) {
  16731. attribute = attributes.get( index );
  16732. renderer = indexedBufferRenderer;
  16733. renderer.setIndex( attribute );
  16734. }
  16735. //
  16736. if ( object.isMesh ) {
  16737. if ( material.wireframe === true ) {
  16738. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  16739. renderer.setMode( 1 );
  16740. } else {
  16741. renderer.setMode( 4 );
  16742. }
  16743. } else if ( object.isLine ) {
  16744. let lineWidth = material.linewidth;
  16745. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  16746. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  16747. if ( object.isLineSegments ) {
  16748. renderer.setMode( 1 );
  16749. } else if ( object.isLineLoop ) {
  16750. renderer.setMode( 2 );
  16751. } else {
  16752. renderer.setMode( 3 );
  16753. }
  16754. } else if ( object.isPoints ) {
  16755. renderer.setMode( 0 );
  16756. } else if ( object.isSprite ) {
  16757. renderer.setMode( 4 );
  16758. }
  16759. if ( object.isInstancedMesh ) {
  16760. renderer.renderInstances( drawStart, drawCount, object.count );
  16761. } else if ( geometry.isInstancedBufferGeometry ) {
  16762. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  16763. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  16764. renderer.renderInstances( drawStart, drawCount, instanceCount );
  16765. } else {
  16766. renderer.render( drawStart, drawCount );
  16767. }
  16768. };
  16769. // Compile
  16770. this.compile = function ( scene, camera ) {
  16771. function prepare( material, scene, object ) {
  16772. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  16773. material.side = BackSide;
  16774. material.needsUpdate = true;
  16775. getProgram( material, scene, object );
  16776. material.side = FrontSide;
  16777. material.needsUpdate = true;
  16778. getProgram( material, scene, object );
  16779. material.side = DoubleSide;
  16780. } else {
  16781. getProgram( material, scene, object );
  16782. }
  16783. }
  16784. currentRenderState = renderStates.get( scene );
  16785. currentRenderState.init();
  16786. renderStateStack.push( currentRenderState );
  16787. scene.traverseVisible( function ( object ) {
  16788. if ( object.isLight && object.layers.test( camera.layers ) ) {
  16789. currentRenderState.pushLight( object );
  16790. if ( object.castShadow ) {
  16791. currentRenderState.pushShadow( object );
  16792. }
  16793. }
  16794. } );
  16795. currentRenderState.setupLights( _this.useLegacyLights );
  16796. scene.traverse( function ( object ) {
  16797. const material = object.material;
  16798. if ( material ) {
  16799. if ( Array.isArray( material ) ) {
  16800. for ( let i = 0; i < material.length; i ++ ) {
  16801. const material2 = material[ i ];
  16802. prepare( material2, scene, object );
  16803. }
  16804. } else {
  16805. prepare( material, scene, object );
  16806. }
  16807. }
  16808. } );
  16809. renderStateStack.pop();
  16810. currentRenderState = null;
  16811. };
  16812. // Animation Loop
  16813. let onAnimationFrameCallback = null;
  16814. function onAnimationFrame( time ) {
  16815. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  16816. }
  16817. function onXRSessionStart() {
  16818. animation.stop();
  16819. }
  16820. function onXRSessionEnd() {
  16821. animation.start();
  16822. }
  16823. const animation = new WebGLAnimation();
  16824. animation.setAnimationLoop( onAnimationFrame );
  16825. if ( typeof self !== 'undefined' ) animation.setContext( self );
  16826. this.setAnimationLoop = function ( callback ) {
  16827. onAnimationFrameCallback = callback;
  16828. xr.setAnimationLoop( callback );
  16829. ( callback === null ) ? animation.stop() : animation.start();
  16830. };
  16831. xr.addEventListener( 'sessionstart', onXRSessionStart );
  16832. xr.addEventListener( 'sessionend', onXRSessionEnd );
  16833. // Rendering
  16834. this.render = function ( scene, camera ) {
  16835. if ( camera !== undefined && camera.isCamera !== true ) {
  16836. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  16837. return;
  16838. }
  16839. if ( _isContextLost === true ) return;
  16840. // update scene graph
  16841. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  16842. // update camera matrices and frustum
  16843. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  16844. if ( xr.enabled === true && xr.isPresenting === true ) {
  16845. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  16846. camera = xr.getCamera(); // use XR camera for rendering
  16847. }
  16848. //
  16849. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  16850. currentRenderState = renderStates.get( scene, renderStateStack.length );
  16851. currentRenderState.init();
  16852. renderStateStack.push( currentRenderState );
  16853. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16854. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  16855. _localClippingEnabled = this.localClippingEnabled;
  16856. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  16857. currentRenderList = renderLists.get( scene, renderListStack.length );
  16858. currentRenderList.init();
  16859. renderListStack.push( currentRenderList );
  16860. projectObject( scene, camera, 0, _this.sortObjects );
  16861. currentRenderList.finish();
  16862. if ( _this.sortObjects === true ) {
  16863. currentRenderList.sort( _opaqueSort, _transparentSort );
  16864. }
  16865. //
  16866. if ( _clippingEnabled === true ) clipping.beginShadows();
  16867. const shadowsArray = currentRenderState.state.shadowsArray;
  16868. shadowMap.render( shadowsArray, scene, camera );
  16869. if ( _clippingEnabled === true ) clipping.endShadows();
  16870. //
  16871. if ( this.info.autoReset === true ) this.info.reset();
  16872. //
  16873. background.render( currentRenderList, scene );
  16874. // render scene
  16875. currentRenderState.setupLights( _this.useLegacyLights );
  16876. if ( camera.isArrayCamera ) {
  16877. const cameras = camera.cameras;
  16878. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  16879. const camera2 = cameras[ i ];
  16880. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  16881. }
  16882. } else {
  16883. renderScene( currentRenderList, scene, camera );
  16884. }
  16885. //
  16886. if ( _currentRenderTarget !== null ) {
  16887. // resolve multisample renderbuffers to a single-sample texture if necessary
  16888. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  16889. // Generate mipmap if we're using any kind of mipmap filtering
  16890. textures.updateRenderTargetMipmap( _currentRenderTarget );
  16891. }
  16892. //
  16893. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  16894. // _gl.finish();
  16895. bindingStates.resetDefaultState();
  16896. _currentMaterialId = - 1;
  16897. _currentCamera = null;
  16898. renderStateStack.pop();
  16899. if ( renderStateStack.length > 0 ) {
  16900. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  16901. } else {
  16902. currentRenderState = null;
  16903. }
  16904. renderListStack.pop();
  16905. if ( renderListStack.length > 0 ) {
  16906. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  16907. } else {
  16908. currentRenderList = null;
  16909. }
  16910. };
  16911. function projectObject( object, camera, groupOrder, sortObjects ) {
  16912. if ( object.visible === false ) return;
  16913. const visible = object.layers.test( camera.layers );
  16914. if ( visible ) {
  16915. if ( object.isGroup ) {
  16916. groupOrder = object.renderOrder;
  16917. } else if ( object.isLOD ) {
  16918. if ( object.autoUpdate === true ) object.update( camera );
  16919. } else if ( object.isLight ) {
  16920. currentRenderState.pushLight( object );
  16921. if ( object.castShadow ) {
  16922. currentRenderState.pushShadow( object );
  16923. }
  16924. } else if ( object.isSprite ) {
  16925. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  16926. if ( sortObjects ) {
  16927. _vector3.setFromMatrixPosition( object.matrixWorld )
  16928. .applyMatrix4( _projScreenMatrix );
  16929. }
  16930. const geometry = objects.update( object );
  16931. const material = object.material;
  16932. if ( material.visible ) {
  16933. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  16934. }
  16935. }
  16936. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  16937. if ( object.isSkinnedMesh ) {
  16938. // update skeleton only once in a frame
  16939. if ( object.skeleton.frame !== info.render.frame ) {
  16940. object.skeleton.update();
  16941. object.skeleton.frame = info.render.frame;
  16942. }
  16943. }
  16944. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  16945. if ( sortObjects ) {
  16946. _vector3.setFromMatrixPosition( object.matrixWorld )
  16947. .applyMatrix4( _projScreenMatrix );
  16948. }
  16949. const geometry = objects.update( object );
  16950. const material = object.material;
  16951. if ( Array.isArray( material ) ) {
  16952. const groups = geometry.groups;
  16953. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  16954. const group = groups[ i ];
  16955. const groupMaterial = material[ group.materialIndex ];
  16956. if ( groupMaterial && groupMaterial.visible ) {
  16957. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  16958. }
  16959. }
  16960. } else if ( material.visible ) {
  16961. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  16962. }
  16963. }
  16964. }
  16965. }
  16966. const children = object.children;
  16967. for ( let i = 0, l = children.length; i < l; i ++ ) {
  16968. projectObject( children[ i ], camera, groupOrder, sortObjects );
  16969. }
  16970. }
  16971. function renderScene( currentRenderList, scene, camera, viewport ) {
  16972. const opaqueObjects = currentRenderList.opaque;
  16973. const transmissiveObjects = currentRenderList.transmissive;
  16974. const transparentObjects = currentRenderList.transparent;
  16975. currentRenderState.setupLightsView( camera );
  16976. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  16977. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  16978. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  16979. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  16980. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  16981. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  16982. // Ensure depth buffer writing is enabled so it can be cleared on next render
  16983. state.buffers.depth.setTest( true );
  16984. state.buffers.depth.setMask( true );
  16985. state.buffers.color.setMask( true );
  16986. state.setPolygonOffset( false );
  16987. }
  16988. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  16989. if ( _transmissionRenderTarget === null ) {
  16990. const isWebGL2 = capabilities.isWebGL2;
  16991. _transmissionRenderTarget = new WebGLRenderTarget( 1024, 1024, {
  16992. generateMipmaps: true,
  16993. type: extensions.has( 'EXT_color_buffer_half_float' ) ? HalfFloatType : UnsignedByteType,
  16994. minFilter: LinearMipmapLinearFilter,
  16995. samples: ( isWebGL2 && _antialias === true ) ? 4 : 0
  16996. } );
  16997. // debug
  16998. /*
  16999. const geometry = new PlaneGeometry();
  17000. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  17001. const mesh = new Mesh( geometry, material );
  17002. scene.add( mesh );
  17003. */
  17004. }
  17005. //
  17006. const currentRenderTarget = _this.getRenderTarget();
  17007. _this.setRenderTarget( _transmissionRenderTarget );
  17008. _this.clear();
  17009. // Turn off the features which can affect the frag color for opaque objects pass.
  17010. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  17011. const currentToneMapping = _this.toneMapping;
  17012. _this.toneMapping = NoToneMapping;
  17013. renderObjects( opaqueObjects, scene, camera );
  17014. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  17015. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  17016. let renderTargetNeedsUpdate = false;
  17017. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  17018. const renderItem = transmissiveObjects[ i ];
  17019. const object = renderItem.object;
  17020. const geometry = renderItem.geometry;
  17021. const material = renderItem.material;
  17022. const group = renderItem.group;
  17023. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  17024. const currentSide = material.side;
  17025. material.side = BackSide;
  17026. material.needsUpdate = true;
  17027. renderObject( object, scene, camera, geometry, material, group );
  17028. material.side = currentSide;
  17029. material.needsUpdate = true;
  17030. renderTargetNeedsUpdate = true;
  17031. }
  17032. }
  17033. if ( renderTargetNeedsUpdate === true ) {
  17034. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  17035. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  17036. }
  17037. _this.setRenderTarget( currentRenderTarget );
  17038. _this.toneMapping = currentToneMapping;
  17039. }
  17040. function renderObjects( renderList, scene, camera ) {
  17041. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  17042. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  17043. const renderItem = renderList[ i ];
  17044. const object = renderItem.object;
  17045. const geometry = renderItem.geometry;
  17046. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  17047. const group = renderItem.group;
  17048. if ( object.layers.test( camera.layers ) ) {
  17049. renderObject( object, scene, camera, geometry, material, group );
  17050. }
  17051. }
  17052. }
  17053. function renderObject( object, scene, camera, geometry, material, group ) {
  17054. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  17055. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  17056. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  17057. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  17058. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  17059. material.side = BackSide;
  17060. material.needsUpdate = true;
  17061. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17062. material.side = FrontSide;
  17063. material.needsUpdate = true;
  17064. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17065. material.side = DoubleSide;
  17066. } else {
  17067. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  17068. }
  17069. object.onAfterRender( _this, scene, camera, geometry, material, group );
  17070. }
  17071. function getProgram( material, scene, object ) {
  17072. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17073. const materialProperties = properties.get( material );
  17074. const lights = currentRenderState.state.lights;
  17075. const shadowsArray = currentRenderState.state.shadowsArray;
  17076. const lightsStateVersion = lights.state.version;
  17077. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  17078. const programCacheKey = programCache.getProgramCacheKey( parameters );
  17079. let programs = materialProperties.programs;
  17080. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  17081. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  17082. materialProperties.fog = scene.fog;
  17083. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  17084. if ( programs === undefined ) {
  17085. // new material
  17086. material.addEventListener( 'dispose', onMaterialDispose );
  17087. programs = new Map();
  17088. materialProperties.programs = programs;
  17089. }
  17090. let program = programs.get( programCacheKey );
  17091. if ( program !== undefined ) {
  17092. // early out if program and light state is identical
  17093. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  17094. updateCommonMaterialProperties( material, parameters );
  17095. return program;
  17096. }
  17097. } else {
  17098. parameters.uniforms = programCache.getUniforms( material );
  17099. material.onBuild( object, parameters, _this );
  17100. material.onBeforeCompile( parameters, _this );
  17101. program = programCache.acquireProgram( parameters, programCacheKey );
  17102. programs.set( programCacheKey, program );
  17103. materialProperties.uniforms = parameters.uniforms;
  17104. }
  17105. const uniforms = materialProperties.uniforms;
  17106. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  17107. uniforms.clippingPlanes = clipping.uniform;
  17108. }
  17109. updateCommonMaterialProperties( material, parameters );
  17110. // store the light setup it was created for
  17111. materialProperties.needsLights = materialNeedsLights( material );
  17112. materialProperties.lightsStateVersion = lightsStateVersion;
  17113. if ( materialProperties.needsLights ) {
  17114. // wire up the material to this renderer's lighting state
  17115. uniforms.ambientLightColor.value = lights.state.ambient;
  17116. uniforms.lightProbe.value = lights.state.probe;
  17117. uniforms.directionalLights.value = lights.state.directional;
  17118. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  17119. uniforms.spotLights.value = lights.state.spot;
  17120. uniforms.spotLightShadows.value = lights.state.spotShadow;
  17121. uniforms.rectAreaLights.value = lights.state.rectArea;
  17122. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  17123. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  17124. uniforms.pointLights.value = lights.state.point;
  17125. uniforms.pointLightShadows.value = lights.state.pointShadow;
  17126. uniforms.hemisphereLights.value = lights.state.hemi;
  17127. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  17128. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  17129. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  17130. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  17131. uniforms.spotLightMap.value = lights.state.spotLightMap;
  17132. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  17133. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  17134. // TODO (abelnation): add area lights shadow info to uniforms
  17135. }
  17136. const progUniforms = program.getUniforms();
  17137. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  17138. materialProperties.currentProgram = program;
  17139. materialProperties.uniformsList = uniformsList;
  17140. return program;
  17141. }
  17142. function updateCommonMaterialProperties( material, parameters ) {
  17143. const materialProperties = properties.get( material );
  17144. materialProperties.outputEncoding = parameters.outputEncoding;
  17145. materialProperties.instancing = parameters.instancing;
  17146. materialProperties.skinning = parameters.skinning;
  17147. materialProperties.morphTargets = parameters.morphTargets;
  17148. materialProperties.morphNormals = parameters.morphNormals;
  17149. materialProperties.morphColors = parameters.morphColors;
  17150. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  17151. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  17152. materialProperties.numIntersection = parameters.numClipIntersection;
  17153. materialProperties.vertexAlphas = parameters.vertexAlphas;
  17154. materialProperties.vertexTangents = parameters.vertexTangents;
  17155. materialProperties.toneMapping = parameters.toneMapping;
  17156. }
  17157. function setProgram( camera, scene, geometry, material, object ) {
  17158. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  17159. textures.resetTextureUnits();
  17160. const fog = scene.fog;
  17161. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  17162. const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding );
  17163. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  17164. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  17165. const vertexTangents = !! material.normalMap && !! geometry.attributes.tangent;
  17166. const morphTargets = !! geometry.morphAttributes.position;
  17167. const morphNormals = !! geometry.morphAttributes.normal;
  17168. const morphColors = !! geometry.morphAttributes.color;
  17169. const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping;
  17170. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  17171. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  17172. const materialProperties = properties.get( material );
  17173. const lights = currentRenderState.state.lights;
  17174. if ( _clippingEnabled === true ) {
  17175. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  17176. const useCache =
  17177. camera === _currentCamera &&
  17178. material.id === _currentMaterialId;
  17179. // we might want to call this function with some ClippingGroup
  17180. // object instead of the material, once it becomes feasible
  17181. // (#8465, #8379)
  17182. clipping.setState( material, camera, useCache );
  17183. }
  17184. }
  17185. //
  17186. let needsProgramChange = false;
  17187. if ( material.version === materialProperties.__version ) {
  17188. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  17189. needsProgramChange = true;
  17190. } else if ( materialProperties.outputEncoding !== encoding ) {
  17191. needsProgramChange = true;
  17192. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  17193. needsProgramChange = true;
  17194. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  17195. needsProgramChange = true;
  17196. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  17197. needsProgramChange = true;
  17198. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  17199. needsProgramChange = true;
  17200. } else if ( materialProperties.envMap !== envMap ) {
  17201. needsProgramChange = true;
  17202. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  17203. needsProgramChange = true;
  17204. } else if ( materialProperties.numClippingPlanes !== undefined &&
  17205. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  17206. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  17207. needsProgramChange = true;
  17208. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  17209. needsProgramChange = true;
  17210. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  17211. needsProgramChange = true;
  17212. } else if ( materialProperties.morphTargets !== morphTargets ) {
  17213. needsProgramChange = true;
  17214. } else if ( materialProperties.morphNormals !== morphNormals ) {
  17215. needsProgramChange = true;
  17216. } else if ( materialProperties.morphColors !== morphColors ) {
  17217. needsProgramChange = true;
  17218. } else if ( materialProperties.toneMapping !== toneMapping ) {
  17219. needsProgramChange = true;
  17220. } else if ( capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount ) {
  17221. needsProgramChange = true;
  17222. }
  17223. } else {
  17224. needsProgramChange = true;
  17225. materialProperties.__version = material.version;
  17226. }
  17227. //
  17228. let program = materialProperties.currentProgram;
  17229. if ( needsProgramChange === true ) {
  17230. program = getProgram( material, scene, object );
  17231. }
  17232. let refreshProgram = false;
  17233. let refreshMaterial = false;
  17234. let refreshLights = false;
  17235. const p_uniforms = program.getUniforms(),
  17236. m_uniforms = materialProperties.uniforms;
  17237. if ( state.useProgram( program.program ) ) {
  17238. refreshProgram = true;
  17239. refreshMaterial = true;
  17240. refreshLights = true;
  17241. }
  17242. if ( material.id !== _currentMaterialId ) {
  17243. _currentMaterialId = material.id;
  17244. refreshMaterial = true;
  17245. }
  17246. if ( refreshProgram || _currentCamera !== camera ) {
  17247. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  17248. if ( capabilities.logarithmicDepthBuffer ) {
  17249. p_uniforms.setValue( _gl, 'logDepthBufFC',
  17250. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  17251. }
  17252. if ( _currentCamera !== camera ) {
  17253. _currentCamera = camera;
  17254. // lighting uniforms depend on the camera so enforce an update
  17255. // now, in case this material supports lights - or later, when
  17256. // the next material that does gets activated:
  17257. refreshMaterial = true; // set to true on material change
  17258. refreshLights = true; // remains set until update done
  17259. }
  17260. // load material specific uniforms
  17261. // (shader material also gets them for the sake of genericity)
  17262. if ( material.isShaderMaterial ||
  17263. material.isMeshPhongMaterial ||
  17264. material.isMeshToonMaterial ||
  17265. material.isMeshStandardMaterial ||
  17266. material.envMap ) {
  17267. const uCamPos = p_uniforms.map.cameraPosition;
  17268. if ( uCamPos !== undefined ) {
  17269. uCamPos.setValue( _gl,
  17270. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  17271. }
  17272. }
  17273. if ( material.isMeshPhongMaterial ||
  17274. material.isMeshToonMaterial ||
  17275. material.isMeshLambertMaterial ||
  17276. material.isMeshBasicMaterial ||
  17277. material.isMeshStandardMaterial ||
  17278. material.isShaderMaterial ) {
  17279. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  17280. }
  17281. if ( material.isMeshPhongMaterial ||
  17282. material.isMeshToonMaterial ||
  17283. material.isMeshLambertMaterial ||
  17284. material.isMeshBasicMaterial ||
  17285. material.isMeshStandardMaterial ||
  17286. material.isShaderMaterial ||
  17287. material.isShadowMaterial ||
  17288. object.isSkinnedMesh ) {
  17289. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  17290. }
  17291. }
  17292. // skinning and morph target uniforms must be set even if material didn't change
  17293. // auto-setting of texture unit for bone and morph texture must go before other textures
  17294. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  17295. if ( object.isSkinnedMesh ) {
  17296. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  17297. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  17298. const skeleton = object.skeleton;
  17299. if ( skeleton ) {
  17300. if ( capabilities.floatVertexTextures ) {
  17301. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  17302. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  17303. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  17304. } else {
  17305. console.warn( 'THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.' );
  17306. }
  17307. }
  17308. }
  17309. const morphAttributes = geometry.morphAttributes;
  17310. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined && capabilities.isWebGL2 === true ) ) {
  17311. morphtargets.update( object, geometry, program );
  17312. }
  17313. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  17314. materialProperties.receiveShadow = object.receiveShadow;
  17315. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  17316. }
  17317. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  17318. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  17319. m_uniforms.envMap.value = envMap;
  17320. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  17321. }
  17322. if ( refreshMaterial ) {
  17323. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  17324. if ( materialProperties.needsLights ) {
  17325. // the current material requires lighting info
  17326. // note: all lighting uniforms are always set correctly
  17327. // they simply reference the renderer's state for their
  17328. // values
  17329. //
  17330. // use the current material's .needsUpdate flags to set
  17331. // the GL state when required
  17332. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  17333. }
  17334. // refresh uniforms common to several materials
  17335. if ( fog && material.fog === true ) {
  17336. materials.refreshFogUniforms( m_uniforms, fog );
  17337. }
  17338. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget );
  17339. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17340. }
  17341. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  17342. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  17343. material.uniformsNeedUpdate = false;
  17344. }
  17345. if ( material.isSpriteMaterial ) {
  17346. p_uniforms.setValue( _gl, 'center', object.center );
  17347. }
  17348. // common matrices
  17349. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  17350. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  17351. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  17352. // UBOs
  17353. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  17354. const groups = material.uniformsGroups;
  17355. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  17356. if ( capabilities.isWebGL2 ) {
  17357. const group = groups[ i ];
  17358. uniformsGroups.update( group, program );
  17359. uniformsGroups.bind( group, program );
  17360. } else {
  17361. console.warn( 'THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.' );
  17362. }
  17363. }
  17364. }
  17365. return program;
  17366. }
  17367. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  17368. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  17369. uniforms.ambientLightColor.needsUpdate = value;
  17370. uniforms.lightProbe.needsUpdate = value;
  17371. uniforms.directionalLights.needsUpdate = value;
  17372. uniforms.directionalLightShadows.needsUpdate = value;
  17373. uniforms.pointLights.needsUpdate = value;
  17374. uniforms.pointLightShadows.needsUpdate = value;
  17375. uniforms.spotLights.needsUpdate = value;
  17376. uniforms.spotLightShadows.needsUpdate = value;
  17377. uniforms.rectAreaLights.needsUpdate = value;
  17378. uniforms.hemisphereLights.needsUpdate = value;
  17379. }
  17380. function materialNeedsLights( material ) {
  17381. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  17382. material.isMeshStandardMaterial || material.isShadowMaterial ||
  17383. ( material.isShaderMaterial && material.lights === true );
  17384. }
  17385. this.getActiveCubeFace = function () {
  17386. return _currentActiveCubeFace;
  17387. };
  17388. this.getActiveMipmapLevel = function () {
  17389. return _currentActiveMipmapLevel;
  17390. };
  17391. this.getRenderTarget = function () {
  17392. return _currentRenderTarget;
  17393. };
  17394. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  17395. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  17396. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  17397. const renderTargetProperties = properties.get( renderTarget );
  17398. renderTargetProperties.__hasExternalTextures = true;
  17399. if ( renderTargetProperties.__hasExternalTextures ) {
  17400. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  17401. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  17402. // The multisample_render_to_texture extension doesn't work properly if there
  17403. // are midframe flushes and an external depth buffer. Disable use of the extension.
  17404. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  17405. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  17406. renderTargetProperties.__useRenderToTexture = false;
  17407. }
  17408. }
  17409. }
  17410. };
  17411. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  17412. const renderTargetProperties = properties.get( renderTarget );
  17413. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  17414. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  17415. };
  17416. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  17417. _currentRenderTarget = renderTarget;
  17418. _currentActiveCubeFace = activeCubeFace;
  17419. _currentActiveMipmapLevel = activeMipmapLevel;
  17420. let useDefaultFramebuffer = true;
  17421. let framebuffer = null;
  17422. let isCube = false;
  17423. let isRenderTarget3D = false;
  17424. if ( renderTarget ) {
  17425. const renderTargetProperties = properties.get( renderTarget );
  17426. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  17427. // We need to make sure to rebind the framebuffer.
  17428. state.bindFramebuffer( 36160, null );
  17429. useDefaultFramebuffer = false;
  17430. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  17431. textures.setupRenderTarget( renderTarget );
  17432. } else if ( renderTargetProperties.__hasExternalTextures ) {
  17433. // Color and depth texture must be rebound in order for the swapchain to update.
  17434. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  17435. }
  17436. const texture = renderTarget.texture;
  17437. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  17438. isRenderTarget3D = true;
  17439. }
  17440. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17441. if ( renderTarget.isWebGLCubeRenderTarget ) {
  17442. framebuffer = __webglFramebuffer[ activeCubeFace ];
  17443. isCube = true;
  17444. } else if ( ( capabilities.isWebGL2 && renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  17445. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  17446. } else {
  17447. framebuffer = __webglFramebuffer;
  17448. }
  17449. _currentViewport.copy( renderTarget.viewport );
  17450. _currentScissor.copy( renderTarget.scissor );
  17451. _currentScissorTest = renderTarget.scissorTest;
  17452. } else {
  17453. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  17454. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  17455. _currentScissorTest = _scissorTest;
  17456. }
  17457. const framebufferBound = state.bindFramebuffer( 36160, framebuffer );
  17458. if ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) {
  17459. state.drawBuffers( renderTarget, framebuffer );
  17460. }
  17461. state.viewport( _currentViewport );
  17462. state.scissor( _currentScissor );
  17463. state.setScissorTest( _currentScissorTest );
  17464. if ( isCube ) {
  17465. const textureProperties = properties.get( renderTarget.texture );
  17466. _gl.framebufferTexture2D( 36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  17467. } else if ( isRenderTarget3D ) {
  17468. const textureProperties = properties.get( renderTarget.texture );
  17469. const layer = activeCubeFace || 0;
  17470. _gl.framebufferTextureLayer( 36160, 36064, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  17471. }
  17472. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  17473. };
  17474. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  17475. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  17476. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  17477. return;
  17478. }
  17479. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17480. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  17481. framebuffer = framebuffer[ activeCubeFaceIndex ];
  17482. }
  17483. if ( framebuffer ) {
  17484. state.bindFramebuffer( 36160, framebuffer );
  17485. try {
  17486. const texture = renderTarget.texture;
  17487. const textureFormat = texture.format;
  17488. const textureType = texture.type;
  17489. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
  17490. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  17491. return;
  17492. }
  17493. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) );
  17494. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // Edge and Chrome Mac < 52 (#9513)
  17495. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  17496. ! halfFloatSupportedByExt ) {
  17497. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  17498. return;
  17499. }
  17500. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  17501. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  17502. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  17503. }
  17504. } finally {
  17505. // restore framebuffer of current render target if necessary
  17506. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  17507. state.bindFramebuffer( 36160, framebuffer );
  17508. }
  17509. }
  17510. };
  17511. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  17512. const levelScale = Math.pow( 2, - level );
  17513. const width = Math.floor( texture.image.width * levelScale );
  17514. const height = Math.floor( texture.image.height * levelScale );
  17515. textures.setTexture2D( texture, 0 );
  17516. _gl.copyTexSubImage2D( 3553, level, 0, 0, position.x, position.y, width, height );
  17517. state.unbindTexture();
  17518. };
  17519. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  17520. const width = srcTexture.image.width;
  17521. const height = srcTexture.image.height;
  17522. const glFormat = utils.convert( dstTexture.format );
  17523. const glType = utils.convert( dstTexture.type );
  17524. textures.setTexture2D( dstTexture, 0 );
  17525. // As another texture upload may have changed pixelStorei
  17526. // parameters, make sure they are correct for the dstTexture
  17527. _gl.pixelStorei( 37440, dstTexture.flipY );
  17528. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  17529. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  17530. if ( srcTexture.isDataTexture ) {
  17531. _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  17532. } else {
  17533. if ( srcTexture.isCompressedTexture ) {
  17534. _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  17535. } else {
  17536. _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image );
  17537. }
  17538. }
  17539. // Generate mipmaps only when copying level 0
  17540. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 );
  17541. state.unbindTexture();
  17542. };
  17543. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  17544. if ( _this.isWebGL1Renderer ) {
  17545. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' );
  17546. return;
  17547. }
  17548. const width = sourceBox.max.x - sourceBox.min.x + 1;
  17549. const height = sourceBox.max.y - sourceBox.min.y + 1;
  17550. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  17551. const glFormat = utils.convert( dstTexture.format );
  17552. const glType = utils.convert( dstTexture.type );
  17553. let glTarget;
  17554. if ( dstTexture.isData3DTexture ) {
  17555. textures.setTexture3D( dstTexture, 0 );
  17556. glTarget = 32879;
  17557. } else if ( dstTexture.isDataArrayTexture ) {
  17558. textures.setTexture2DArray( dstTexture, 0 );
  17559. glTarget = 35866;
  17560. } else {
  17561. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  17562. return;
  17563. }
  17564. _gl.pixelStorei( 37440, dstTexture.flipY );
  17565. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  17566. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  17567. const unpackRowLen = _gl.getParameter( 3314 );
  17568. const unpackImageHeight = _gl.getParameter( 32878 );
  17569. const unpackSkipPixels = _gl.getParameter( 3316 );
  17570. const unpackSkipRows = _gl.getParameter( 3315 );
  17571. const unpackSkipImages = _gl.getParameter( 32877 );
  17572. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image;
  17573. _gl.pixelStorei( 3314, image.width );
  17574. _gl.pixelStorei( 32878, image.height );
  17575. _gl.pixelStorei( 3316, sourceBox.min.x );
  17576. _gl.pixelStorei( 3315, sourceBox.min.y );
  17577. _gl.pixelStorei( 32877, sourceBox.min.z );
  17578. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  17579. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data );
  17580. } else {
  17581. if ( srcTexture.isCompressedArrayTexture ) {
  17582. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' );
  17583. _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data );
  17584. } else {
  17585. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image );
  17586. }
  17587. }
  17588. _gl.pixelStorei( 3314, unpackRowLen );
  17589. _gl.pixelStorei( 32878, unpackImageHeight );
  17590. _gl.pixelStorei( 3316, unpackSkipPixels );
  17591. _gl.pixelStorei( 3315, unpackSkipRows );
  17592. _gl.pixelStorei( 32877, unpackSkipImages );
  17593. // Generate mipmaps only when copying level 0
  17594. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  17595. state.unbindTexture();
  17596. };
  17597. this.initTexture = function ( texture ) {
  17598. if ( texture.isCubeTexture ) {
  17599. textures.setTextureCube( texture, 0 );
  17600. } else if ( texture.isData3DTexture ) {
  17601. textures.setTexture3D( texture, 0 );
  17602. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  17603. textures.setTexture2DArray( texture, 0 );
  17604. } else {
  17605. textures.setTexture2D( texture, 0 );
  17606. }
  17607. state.unbindTexture();
  17608. };
  17609. this.resetState = function () {
  17610. _currentActiveCubeFace = 0;
  17611. _currentActiveMipmapLevel = 0;
  17612. _currentRenderTarget = null;
  17613. state.reset();
  17614. bindingStates.reset();
  17615. };
  17616. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17617. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17618. }
  17619. }
  17620. Object.defineProperties( WebGLRenderer.prototype, {
  17621. // @deprecated since r150
  17622. physicallyCorrectLights: {
  17623. get: function () {
  17624. console.warn( 'THREE.WebGLRenderer: the property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead.' );
  17625. return ! this.useLegacyLights;
  17626. },
  17627. set: function ( value ) {
  17628. console.warn( 'THREE.WebGLRenderer: the property .physicallyCorrectLights has been removed. Set renderer.useLegacyLights instead.' );
  17629. this.useLegacyLights = ! value;
  17630. }
  17631. }
  17632. } );
  17633. class WebGL1Renderer extends WebGLRenderer {}
  17634. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  17635. class FogExp2 {
  17636. constructor( color, density = 0.00025 ) {
  17637. this.isFogExp2 = true;
  17638. this.name = '';
  17639. this.color = new Color( color );
  17640. this.density = density;
  17641. }
  17642. clone() {
  17643. return new FogExp2( this.color, this.density );
  17644. }
  17645. toJSON( /* meta */ ) {
  17646. return {
  17647. type: 'FogExp2',
  17648. color: this.color.getHex(),
  17649. density: this.density
  17650. };
  17651. }
  17652. }
  17653. class Fog {
  17654. constructor( color, near = 1, far = 1000 ) {
  17655. this.isFog = true;
  17656. this.name = '';
  17657. this.color = new Color( color );
  17658. this.near = near;
  17659. this.far = far;
  17660. }
  17661. clone() {
  17662. return new Fog( this.color, this.near, this.far );
  17663. }
  17664. toJSON( /* meta */ ) {
  17665. return {
  17666. type: 'Fog',
  17667. color: this.color.getHex(),
  17668. near: this.near,
  17669. far: this.far
  17670. };
  17671. }
  17672. }
  17673. class Scene extends Object3D {
  17674. constructor() {
  17675. super();
  17676. this.isScene = true;
  17677. this.type = 'Scene';
  17678. this.background = null;
  17679. this.environment = null;
  17680. this.fog = null;
  17681. this.backgroundBlurriness = 0;
  17682. this.backgroundIntensity = 1;
  17683. this.overrideMaterial = null;
  17684. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17685. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17686. }
  17687. }
  17688. copy( source, recursive ) {
  17689. super.copy( source, recursive );
  17690. if ( source.background !== null ) this.background = source.background.clone();
  17691. if ( source.environment !== null ) this.environment = source.environment.clone();
  17692. if ( source.fog !== null ) this.fog = source.fog.clone();
  17693. this.backgroundBlurriness = source.backgroundBlurriness;
  17694. this.backgroundIntensity = source.backgroundIntensity;
  17695. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17696. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17697. return this;
  17698. }
  17699. toJSON( meta ) {
  17700. const data = super.toJSON( meta );
  17701. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17702. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  17703. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  17704. return data;
  17705. }
  17706. // @deprecated
  17707. get autoUpdate() {
  17708. console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' );
  17709. return this.matrixWorldAutoUpdate;
  17710. }
  17711. set autoUpdate( value ) {
  17712. console.warn( 'THREE.Scene: autoUpdate was renamed to matrixWorldAutoUpdate in r144.' );
  17713. this.matrixWorldAutoUpdate = value;
  17714. }
  17715. }
  17716. class InterleavedBuffer {
  17717. constructor( array, stride ) {
  17718. this.isInterleavedBuffer = true;
  17719. this.array = array;
  17720. this.stride = stride;
  17721. this.count = array !== undefined ? array.length / stride : 0;
  17722. this.usage = StaticDrawUsage;
  17723. this.updateRange = { offset: 0, count: - 1 };
  17724. this.version = 0;
  17725. this.uuid = generateUUID();
  17726. }
  17727. onUploadCallback() {}
  17728. set needsUpdate( value ) {
  17729. if ( value === true ) this.version ++;
  17730. }
  17731. setUsage( value ) {
  17732. this.usage = value;
  17733. return this;
  17734. }
  17735. copy( source ) {
  17736. this.array = new source.array.constructor( source.array );
  17737. this.count = source.count;
  17738. this.stride = source.stride;
  17739. this.usage = source.usage;
  17740. return this;
  17741. }
  17742. copyAt( index1, attribute, index2 ) {
  17743. index1 *= this.stride;
  17744. index2 *= attribute.stride;
  17745. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17746. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  17747. }
  17748. return this;
  17749. }
  17750. set( value, offset = 0 ) {
  17751. this.array.set( value, offset );
  17752. return this;
  17753. }
  17754. clone( data ) {
  17755. if ( data.arrayBuffers === undefined ) {
  17756. data.arrayBuffers = {};
  17757. }
  17758. if ( this.array.buffer._uuid === undefined ) {
  17759. this.array.buffer._uuid = generateUUID();
  17760. }
  17761. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17762. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17763. }
  17764. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17765. const ib = new this.constructor( array, this.stride );
  17766. ib.setUsage( this.usage );
  17767. return ib;
  17768. }
  17769. onUpload( callback ) {
  17770. this.onUploadCallback = callback;
  17771. return this;
  17772. }
  17773. toJSON( data ) {
  17774. if ( data.arrayBuffers === undefined ) {
  17775. data.arrayBuffers = {};
  17776. }
  17777. // generate UUID for array buffer if necessary
  17778. if ( this.array.buffer._uuid === undefined ) {
  17779. this.array.buffer._uuid = generateUUID();
  17780. }
  17781. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17782. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17783. }
  17784. //
  17785. return {
  17786. uuid: this.uuid,
  17787. buffer: this.array.buffer._uuid,
  17788. type: this.array.constructor.name,
  17789. stride: this.stride
  17790. };
  17791. }
  17792. }
  17793. const _vector$6 = /*@__PURE__*/ new Vector3();
  17794. class InterleavedBufferAttribute {
  17795. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17796. this.isInterleavedBufferAttribute = true;
  17797. this.name = '';
  17798. this.data = interleavedBuffer;
  17799. this.itemSize = itemSize;
  17800. this.offset = offset;
  17801. this.normalized = normalized;
  17802. }
  17803. get count() {
  17804. return this.data.count;
  17805. }
  17806. get array() {
  17807. return this.data.array;
  17808. }
  17809. set needsUpdate( value ) {
  17810. this.data.needsUpdate = value;
  17811. }
  17812. applyMatrix4( m ) {
  17813. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17814. _vector$6.fromBufferAttribute( this, i );
  17815. _vector$6.applyMatrix4( m );
  17816. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17817. }
  17818. return this;
  17819. }
  17820. applyNormalMatrix( m ) {
  17821. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17822. _vector$6.fromBufferAttribute( this, i );
  17823. _vector$6.applyNormalMatrix( m );
  17824. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17825. }
  17826. return this;
  17827. }
  17828. transformDirection( m ) {
  17829. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17830. _vector$6.fromBufferAttribute( this, i );
  17831. _vector$6.transformDirection( m );
  17832. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17833. }
  17834. return this;
  17835. }
  17836. setX( index, x ) {
  17837. if ( this.normalized ) x = normalize( x, this.array );
  17838. this.data.array[ index * this.data.stride + this.offset ] = x;
  17839. return this;
  17840. }
  17841. setY( index, y ) {
  17842. if ( this.normalized ) y = normalize( y, this.array );
  17843. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17844. return this;
  17845. }
  17846. setZ( index, z ) {
  17847. if ( this.normalized ) z = normalize( z, this.array );
  17848. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17849. return this;
  17850. }
  17851. setW( index, w ) {
  17852. if ( this.normalized ) w = normalize( w, this.array );
  17853. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17854. return this;
  17855. }
  17856. getX( index ) {
  17857. let x = this.data.array[ index * this.data.stride + this.offset ];
  17858. if ( this.normalized ) x = denormalize( x, this.array );
  17859. return x;
  17860. }
  17861. getY( index ) {
  17862. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17863. if ( this.normalized ) y = denormalize( y, this.array );
  17864. return y;
  17865. }
  17866. getZ( index ) {
  17867. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17868. if ( this.normalized ) z = denormalize( z, this.array );
  17869. return z;
  17870. }
  17871. getW( index ) {
  17872. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17873. if ( this.normalized ) w = denormalize( w, this.array );
  17874. return w;
  17875. }
  17876. setXY( index, x, y ) {
  17877. index = index * this.data.stride + this.offset;
  17878. if ( this.normalized ) {
  17879. x = normalize( x, this.array );
  17880. y = normalize( y, this.array );
  17881. }
  17882. this.data.array[ index + 0 ] = x;
  17883. this.data.array[ index + 1 ] = y;
  17884. return this;
  17885. }
  17886. setXYZ( index, x, y, z ) {
  17887. index = index * this.data.stride + this.offset;
  17888. if ( this.normalized ) {
  17889. x = normalize( x, this.array );
  17890. y = normalize( y, this.array );
  17891. z = normalize( z, this.array );
  17892. }
  17893. this.data.array[ index + 0 ] = x;
  17894. this.data.array[ index + 1 ] = y;
  17895. this.data.array[ index + 2 ] = z;
  17896. return this;
  17897. }
  17898. setXYZW( index, x, y, z, w ) {
  17899. index = index * this.data.stride + this.offset;
  17900. if ( this.normalized ) {
  17901. x = normalize( x, this.array );
  17902. y = normalize( y, this.array );
  17903. z = normalize( z, this.array );
  17904. w = normalize( w, this.array );
  17905. }
  17906. this.data.array[ index + 0 ] = x;
  17907. this.data.array[ index + 1 ] = y;
  17908. this.data.array[ index + 2 ] = z;
  17909. this.data.array[ index + 3 ] = w;
  17910. return this;
  17911. }
  17912. clone( data ) {
  17913. if ( data === undefined ) {
  17914. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  17915. const array = [];
  17916. for ( let i = 0; i < this.count; i ++ ) {
  17917. const index = i * this.data.stride + this.offset;
  17918. for ( let j = 0; j < this.itemSize; j ++ ) {
  17919. array.push( this.data.array[ index + j ] );
  17920. }
  17921. }
  17922. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17923. } else {
  17924. if ( data.interleavedBuffers === undefined ) {
  17925. data.interleavedBuffers = {};
  17926. }
  17927. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17928. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17929. }
  17930. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17931. }
  17932. }
  17933. toJSON( data ) {
  17934. if ( data === undefined ) {
  17935. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  17936. const array = [];
  17937. for ( let i = 0; i < this.count; i ++ ) {
  17938. const index = i * this.data.stride + this.offset;
  17939. for ( let j = 0; j < this.itemSize; j ++ ) {
  17940. array.push( this.data.array[ index + j ] );
  17941. }
  17942. }
  17943. // de-interleave data and save it as an ordinary buffer attribute for now
  17944. return {
  17945. itemSize: this.itemSize,
  17946. type: this.array.constructor.name,
  17947. array: array,
  17948. normalized: this.normalized
  17949. };
  17950. } else {
  17951. // save as true interleaved attribute
  17952. if ( data.interleavedBuffers === undefined ) {
  17953. data.interleavedBuffers = {};
  17954. }
  17955. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17956. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17957. }
  17958. return {
  17959. isInterleavedBufferAttribute: true,
  17960. itemSize: this.itemSize,
  17961. data: this.data.uuid,
  17962. offset: this.offset,
  17963. normalized: this.normalized
  17964. };
  17965. }
  17966. }
  17967. }
  17968. class SpriteMaterial extends Material {
  17969. constructor( parameters ) {
  17970. super();
  17971. this.isSpriteMaterial = true;
  17972. this.type = 'SpriteMaterial';
  17973. this.color = new Color( 0xffffff );
  17974. this.map = null;
  17975. this.alphaMap = null;
  17976. this.rotation = 0;
  17977. this.sizeAttenuation = true;
  17978. this.transparent = true;
  17979. this.fog = true;
  17980. this.setValues( parameters );
  17981. }
  17982. copy( source ) {
  17983. super.copy( source );
  17984. this.color.copy( source.color );
  17985. this.map = source.map;
  17986. this.alphaMap = source.alphaMap;
  17987. this.rotation = source.rotation;
  17988. this.sizeAttenuation = source.sizeAttenuation;
  17989. this.fog = source.fog;
  17990. return this;
  17991. }
  17992. }
  17993. let _geometry;
  17994. const _intersectPoint = /*@__PURE__*/ new Vector3();
  17995. const _worldScale = /*@__PURE__*/ new Vector3();
  17996. const _mvPosition = /*@__PURE__*/ new Vector3();
  17997. const _alignedPosition = /*@__PURE__*/ new Vector2();
  17998. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  17999. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  18000. const _vA = /*@__PURE__*/ new Vector3();
  18001. const _vB = /*@__PURE__*/ new Vector3();
  18002. const _vC = /*@__PURE__*/ new Vector3();
  18003. const _uvA = /*@__PURE__*/ new Vector2();
  18004. const _uvB = /*@__PURE__*/ new Vector2();
  18005. const _uvC = /*@__PURE__*/ new Vector2();
  18006. class Sprite extends Object3D {
  18007. constructor( material ) {
  18008. super();
  18009. this.isSprite = true;
  18010. this.type = 'Sprite';
  18011. if ( _geometry === undefined ) {
  18012. _geometry = new BufferGeometry();
  18013. const float32Array = new Float32Array( [
  18014. - 0.5, - 0.5, 0, 0, 0,
  18015. 0.5, - 0.5, 0, 1, 0,
  18016. 0.5, 0.5, 0, 1, 1,
  18017. - 0.5, 0.5, 0, 0, 1
  18018. ] );
  18019. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  18020. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  18021. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  18022. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  18023. }
  18024. this.geometry = _geometry;
  18025. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  18026. this.center = new Vector2( 0.5, 0.5 );
  18027. }
  18028. raycast( raycaster, intersects ) {
  18029. if ( raycaster.camera === null ) {
  18030. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18031. }
  18032. _worldScale.setFromMatrixScale( this.matrixWorld );
  18033. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18034. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18035. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18036. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18037. _worldScale.multiplyScalar( - _mvPosition.z );
  18038. }
  18039. const rotation = this.material.rotation;
  18040. let sin, cos;
  18041. if ( rotation !== 0 ) {
  18042. cos = Math.cos( rotation );
  18043. sin = Math.sin( rotation );
  18044. }
  18045. const center = this.center;
  18046. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18047. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18048. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18049. _uvA.set( 0, 0 );
  18050. _uvB.set( 1, 0 );
  18051. _uvC.set( 1, 1 );
  18052. // check first triangle
  18053. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18054. if ( intersect === null ) {
  18055. // check second triangle
  18056. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18057. _uvB.set( 0, 1 );
  18058. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18059. if ( intersect === null ) {
  18060. return;
  18061. }
  18062. }
  18063. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18064. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18065. intersects.push( {
  18066. distance: distance,
  18067. point: _intersectPoint.clone(),
  18068. uv: Triangle.getUV( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18069. face: null,
  18070. object: this
  18071. } );
  18072. }
  18073. copy( source, recursive ) {
  18074. super.copy( source, recursive );
  18075. if ( source.center !== undefined ) this.center.copy( source.center );
  18076. this.material = source.material;
  18077. return this;
  18078. }
  18079. }
  18080. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18081. // compute position in camera space
  18082. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18083. // to check if rotation is not zero
  18084. if ( sin !== undefined ) {
  18085. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  18086. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  18087. } else {
  18088. _rotatedPosition.copy( _alignedPosition );
  18089. }
  18090. vertexPosition.copy( mvPosition );
  18091. vertexPosition.x += _rotatedPosition.x;
  18092. vertexPosition.y += _rotatedPosition.y;
  18093. // transform to world space
  18094. vertexPosition.applyMatrix4( _viewWorldMatrix );
  18095. }
  18096. const _v1$2 = /*@__PURE__*/ new Vector3();
  18097. const _v2$1 = /*@__PURE__*/ new Vector3();
  18098. class LOD extends Object3D {
  18099. constructor() {
  18100. super();
  18101. this._currentLevel = 0;
  18102. this.type = 'LOD';
  18103. Object.defineProperties( this, {
  18104. levels: {
  18105. enumerable: true,
  18106. value: []
  18107. },
  18108. isLOD: {
  18109. value: true,
  18110. }
  18111. } );
  18112. this.autoUpdate = true;
  18113. }
  18114. copy( source ) {
  18115. super.copy( source, false );
  18116. const levels = source.levels;
  18117. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18118. const level = levels[ i ];
  18119. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  18120. }
  18121. this.autoUpdate = source.autoUpdate;
  18122. return this;
  18123. }
  18124. addLevel( object, distance = 0, hysteresis = 0 ) {
  18125. distance = Math.abs( distance );
  18126. const levels = this.levels;
  18127. let l;
  18128. for ( l = 0; l < levels.length; l ++ ) {
  18129. if ( distance < levels[ l ].distance ) {
  18130. break;
  18131. }
  18132. }
  18133. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18134. this.add( object );
  18135. return this;
  18136. }
  18137. getCurrentLevel() {
  18138. return this._currentLevel;
  18139. }
  18140. getObjectForDistance( distance ) {
  18141. const levels = this.levels;
  18142. if ( levels.length > 0 ) {
  18143. let i, l;
  18144. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18145. let levelDistance = levels[ i ].distance;
  18146. if ( levels[ i ].object.visible ) {
  18147. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18148. }
  18149. if ( distance < levelDistance ) {
  18150. break;
  18151. }
  18152. }
  18153. return levels[ i - 1 ].object;
  18154. }
  18155. return null;
  18156. }
  18157. raycast( raycaster, intersects ) {
  18158. const levels = this.levels;
  18159. if ( levels.length > 0 ) {
  18160. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18161. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18162. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18163. }
  18164. }
  18165. update( camera ) {
  18166. const levels = this.levels;
  18167. if ( levels.length > 1 ) {
  18168. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18169. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18170. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18171. levels[ 0 ].object.visible = true;
  18172. let i, l;
  18173. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18174. let levelDistance = levels[ i ].distance;
  18175. if ( levels[ i ].object.visible ) {
  18176. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18177. }
  18178. if ( distance >= levelDistance ) {
  18179. levels[ i - 1 ].object.visible = false;
  18180. levels[ i ].object.visible = true;
  18181. } else {
  18182. break;
  18183. }
  18184. }
  18185. this._currentLevel = i - 1;
  18186. for ( ; i < l; i ++ ) {
  18187. levels[ i ].object.visible = false;
  18188. }
  18189. }
  18190. }
  18191. toJSON( meta ) {
  18192. const data = super.toJSON( meta );
  18193. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18194. data.object.levels = [];
  18195. const levels = this.levels;
  18196. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18197. const level = levels[ i ];
  18198. data.object.levels.push( {
  18199. object: level.object.uuid,
  18200. distance: level.distance,
  18201. hysteresis: level.hysteresis
  18202. } );
  18203. }
  18204. return data;
  18205. }
  18206. }
  18207. const _basePosition = /*@__PURE__*/ new Vector3();
  18208. const _skinIndex = /*@__PURE__*/ new Vector4();
  18209. const _skinWeight = /*@__PURE__*/ new Vector4();
  18210. const _vector$5 = /*@__PURE__*/ new Vector3();
  18211. const _matrix = /*@__PURE__*/ new Matrix4();
  18212. class SkinnedMesh extends Mesh {
  18213. constructor( geometry, material ) {
  18214. super( geometry, material );
  18215. this.isSkinnedMesh = true;
  18216. this.type = 'SkinnedMesh';
  18217. this.bindMode = 'attached';
  18218. this.bindMatrix = new Matrix4();
  18219. this.bindMatrixInverse = new Matrix4();
  18220. }
  18221. copy( source, recursive ) {
  18222. super.copy( source, recursive );
  18223. this.bindMode = source.bindMode;
  18224. this.bindMatrix.copy( source.bindMatrix );
  18225. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18226. this.skeleton = source.skeleton;
  18227. return this;
  18228. }
  18229. bind( skeleton, bindMatrix ) {
  18230. this.skeleton = skeleton;
  18231. if ( bindMatrix === undefined ) {
  18232. this.updateMatrixWorld( true );
  18233. this.skeleton.calculateInverses();
  18234. bindMatrix = this.matrixWorld;
  18235. }
  18236. this.bindMatrix.copy( bindMatrix );
  18237. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18238. }
  18239. pose() {
  18240. this.skeleton.pose();
  18241. }
  18242. normalizeSkinWeights() {
  18243. const vector = new Vector4();
  18244. const skinWeight = this.geometry.attributes.skinWeight;
  18245. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18246. vector.fromBufferAttribute( skinWeight, i );
  18247. const scale = 1.0 / vector.manhattanLength();
  18248. if ( scale !== Infinity ) {
  18249. vector.multiplyScalar( scale );
  18250. } else {
  18251. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18252. }
  18253. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18254. }
  18255. }
  18256. updateMatrixWorld( force ) {
  18257. super.updateMatrixWorld( force );
  18258. if ( this.bindMode === 'attached' ) {
  18259. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18260. } else if ( this.bindMode === 'detached' ) {
  18261. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18262. } else {
  18263. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18264. }
  18265. }
  18266. boneTransform( index, target ) {
  18267. const skeleton = this.skeleton;
  18268. const geometry = this.geometry;
  18269. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18270. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18271. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  18272. target.set( 0, 0, 0 );
  18273. for ( let i = 0; i < 4; i ++ ) {
  18274. const weight = _skinWeight.getComponent( i );
  18275. if ( weight !== 0 ) {
  18276. const boneIndex = _skinIndex.getComponent( i );
  18277. _matrix.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18278. target.addScaledVector( _vector$5.copy( _basePosition ).applyMatrix4( _matrix ), weight );
  18279. }
  18280. }
  18281. return target.applyMatrix4( this.bindMatrixInverse );
  18282. }
  18283. }
  18284. class Bone extends Object3D {
  18285. constructor() {
  18286. super();
  18287. this.isBone = true;
  18288. this.type = 'Bone';
  18289. }
  18290. }
  18291. class DataTexture extends Texture {
  18292. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding ) {
  18293. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  18294. this.isDataTexture = true;
  18295. this.image = { data: data, width: width, height: height };
  18296. this.generateMipmaps = false;
  18297. this.flipY = false;
  18298. this.unpackAlignment = 1;
  18299. }
  18300. }
  18301. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18302. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18303. class Skeleton {
  18304. constructor( bones = [], boneInverses = [] ) {
  18305. this.uuid = generateUUID();
  18306. this.bones = bones.slice( 0 );
  18307. this.boneInverses = boneInverses;
  18308. this.boneMatrices = null;
  18309. this.boneTexture = null;
  18310. this.boneTextureSize = 0;
  18311. this.frame = - 1;
  18312. this.init();
  18313. }
  18314. init() {
  18315. const bones = this.bones;
  18316. const boneInverses = this.boneInverses;
  18317. this.boneMatrices = new Float32Array( bones.length * 16 );
  18318. // calculate inverse bone matrices if necessary
  18319. if ( boneInverses.length === 0 ) {
  18320. this.calculateInverses();
  18321. } else {
  18322. // handle special case
  18323. if ( bones.length !== boneInverses.length ) {
  18324. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18325. this.boneInverses = [];
  18326. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18327. this.boneInverses.push( new Matrix4() );
  18328. }
  18329. }
  18330. }
  18331. }
  18332. calculateInverses() {
  18333. this.boneInverses.length = 0;
  18334. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18335. const inverse = new Matrix4();
  18336. if ( this.bones[ i ] ) {
  18337. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18338. }
  18339. this.boneInverses.push( inverse );
  18340. }
  18341. }
  18342. pose() {
  18343. // recover the bind-time world matrices
  18344. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18345. const bone = this.bones[ i ];
  18346. if ( bone ) {
  18347. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18348. }
  18349. }
  18350. // compute the local matrices, positions, rotations and scales
  18351. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18352. const bone = this.bones[ i ];
  18353. if ( bone ) {
  18354. if ( bone.parent && bone.parent.isBone ) {
  18355. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18356. bone.matrix.multiply( bone.matrixWorld );
  18357. } else {
  18358. bone.matrix.copy( bone.matrixWorld );
  18359. }
  18360. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18361. }
  18362. }
  18363. }
  18364. update() {
  18365. const bones = this.bones;
  18366. const boneInverses = this.boneInverses;
  18367. const boneMatrices = this.boneMatrices;
  18368. const boneTexture = this.boneTexture;
  18369. // flatten bone matrices to array
  18370. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18371. // compute the offset between the current and the original transform
  18372. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18373. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18374. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18375. }
  18376. if ( boneTexture !== null ) {
  18377. boneTexture.needsUpdate = true;
  18378. }
  18379. }
  18380. clone() {
  18381. return new Skeleton( this.bones, this.boneInverses );
  18382. }
  18383. computeBoneTexture() {
  18384. // layout (1 matrix = 4 pixels)
  18385. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18386. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18387. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18388. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18389. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18390. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18391. size = ceilPowerOfTwo( size );
  18392. size = Math.max( size, 4 );
  18393. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18394. boneMatrices.set( this.boneMatrices ); // copy current values
  18395. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18396. boneTexture.needsUpdate = true;
  18397. this.boneMatrices = boneMatrices;
  18398. this.boneTexture = boneTexture;
  18399. this.boneTextureSize = size;
  18400. return this;
  18401. }
  18402. getBoneByName( name ) {
  18403. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18404. const bone = this.bones[ i ];
  18405. if ( bone.name === name ) {
  18406. return bone;
  18407. }
  18408. }
  18409. return undefined;
  18410. }
  18411. dispose( ) {
  18412. if ( this.boneTexture !== null ) {
  18413. this.boneTexture.dispose();
  18414. this.boneTexture = null;
  18415. }
  18416. }
  18417. fromJSON( json, bones ) {
  18418. this.uuid = json.uuid;
  18419. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18420. const uuid = json.bones[ i ];
  18421. let bone = bones[ uuid ];
  18422. if ( bone === undefined ) {
  18423. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  18424. bone = new Bone();
  18425. }
  18426. this.bones.push( bone );
  18427. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18428. }
  18429. this.init();
  18430. return this;
  18431. }
  18432. toJSON() {
  18433. const data = {
  18434. metadata: {
  18435. version: 4.5,
  18436. type: 'Skeleton',
  18437. generator: 'Skeleton.toJSON'
  18438. },
  18439. bones: [],
  18440. boneInverses: []
  18441. };
  18442. data.uuid = this.uuid;
  18443. const bones = this.bones;
  18444. const boneInverses = this.boneInverses;
  18445. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18446. const bone = bones[ i ];
  18447. data.bones.push( bone.uuid );
  18448. const boneInverse = boneInverses[ i ];
  18449. data.boneInverses.push( boneInverse.toArray() );
  18450. }
  18451. return data;
  18452. }
  18453. }
  18454. class InstancedBufferAttribute extends BufferAttribute {
  18455. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  18456. super( array, itemSize, normalized );
  18457. this.isInstancedBufferAttribute = true;
  18458. this.meshPerAttribute = meshPerAttribute;
  18459. }
  18460. copy( source ) {
  18461. super.copy( source );
  18462. this.meshPerAttribute = source.meshPerAttribute;
  18463. return this;
  18464. }
  18465. toJSON() {
  18466. const data = super.toJSON();
  18467. data.meshPerAttribute = this.meshPerAttribute;
  18468. data.isInstancedBufferAttribute = true;
  18469. return data;
  18470. }
  18471. }
  18472. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  18473. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  18474. const _instanceIntersects = [];
  18475. const _identity = /*@__PURE__*/ new Matrix4();
  18476. const _mesh = /*@__PURE__*/ new Mesh();
  18477. class InstancedMesh extends Mesh {
  18478. constructor( geometry, material, count ) {
  18479. super( geometry, material );
  18480. this.isInstancedMesh = true;
  18481. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  18482. this.instanceColor = null;
  18483. this.count = count;
  18484. this.frustumCulled = false;
  18485. for ( let i = 0; i < count; i ++ ) {
  18486. this.setMatrixAt( i, _identity );
  18487. }
  18488. }
  18489. copy( source, recursive ) {
  18490. super.copy( source, recursive );
  18491. this.instanceMatrix.copy( source.instanceMatrix );
  18492. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  18493. this.count = source.count;
  18494. return this;
  18495. }
  18496. getColorAt( index, color ) {
  18497. color.fromArray( this.instanceColor.array, index * 3 );
  18498. }
  18499. getMatrixAt( index, matrix ) {
  18500. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  18501. }
  18502. raycast( raycaster, intersects ) {
  18503. const matrixWorld = this.matrixWorld;
  18504. const raycastTimes = this.count;
  18505. _mesh.geometry = this.geometry;
  18506. _mesh.material = this.material;
  18507. if ( _mesh.material === undefined ) return;
  18508. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  18509. // calculate the world matrix for each instance
  18510. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  18511. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  18512. // the mesh represents this single instance
  18513. _mesh.matrixWorld = _instanceWorldMatrix;
  18514. _mesh.raycast( raycaster, _instanceIntersects );
  18515. // process the result of raycast
  18516. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  18517. const intersect = _instanceIntersects[ i ];
  18518. intersect.instanceId = instanceId;
  18519. intersect.object = this;
  18520. intersects.push( intersect );
  18521. }
  18522. _instanceIntersects.length = 0;
  18523. }
  18524. }
  18525. setColorAt( index, color ) {
  18526. if ( this.instanceColor === null ) {
  18527. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  18528. }
  18529. color.toArray( this.instanceColor.array, index * 3 );
  18530. }
  18531. setMatrixAt( index, matrix ) {
  18532. matrix.toArray( this.instanceMatrix.array, index * 16 );
  18533. }
  18534. updateMorphTargets() {
  18535. }
  18536. dispose() {
  18537. this.dispatchEvent( { type: 'dispose' } );
  18538. }
  18539. }
  18540. class LineBasicMaterial extends Material {
  18541. constructor( parameters ) {
  18542. super();
  18543. this.isLineBasicMaterial = true;
  18544. this.type = 'LineBasicMaterial';
  18545. this.color = new Color( 0xffffff );
  18546. this.linewidth = 1;
  18547. this.linecap = 'round';
  18548. this.linejoin = 'round';
  18549. this.fog = true;
  18550. this.setValues( parameters );
  18551. }
  18552. copy( source ) {
  18553. super.copy( source );
  18554. this.color.copy( source.color );
  18555. this.linewidth = source.linewidth;
  18556. this.linecap = source.linecap;
  18557. this.linejoin = source.linejoin;
  18558. this.fog = source.fog;
  18559. return this;
  18560. }
  18561. }
  18562. const _start$1 = /*@__PURE__*/ new Vector3();
  18563. const _end$1 = /*@__PURE__*/ new Vector3();
  18564. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  18565. const _ray$1 = /*@__PURE__*/ new Ray();
  18566. const _sphere$1 = /*@__PURE__*/ new Sphere();
  18567. class Line extends Object3D {
  18568. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  18569. super();
  18570. this.isLine = true;
  18571. this.type = 'Line';
  18572. this.geometry = geometry;
  18573. this.material = material;
  18574. this.updateMorphTargets();
  18575. }
  18576. copy( source, recursive ) {
  18577. super.copy( source, recursive );
  18578. this.material = source.material;
  18579. this.geometry = source.geometry;
  18580. return this;
  18581. }
  18582. computeLineDistances() {
  18583. const geometry = this.geometry;
  18584. // we assume non-indexed geometry
  18585. if ( geometry.index === null ) {
  18586. const positionAttribute = geometry.attributes.position;
  18587. const lineDistances = [ 0 ];
  18588. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  18589. _start$1.fromBufferAttribute( positionAttribute, i - 1 );
  18590. _end$1.fromBufferAttribute( positionAttribute, i );
  18591. lineDistances[ i ] = lineDistances[ i - 1 ];
  18592. lineDistances[ i ] += _start$1.distanceTo( _end$1 );
  18593. }
  18594. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18595. } else {
  18596. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18597. }
  18598. return this;
  18599. }
  18600. raycast( raycaster, intersects ) {
  18601. const geometry = this.geometry;
  18602. const matrixWorld = this.matrixWorld;
  18603. const threshold = raycaster.params.Line.threshold;
  18604. const drawRange = geometry.drawRange;
  18605. // Checking boundingSphere distance to ray
  18606. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18607. _sphere$1.copy( geometry.boundingSphere );
  18608. _sphere$1.applyMatrix4( matrixWorld );
  18609. _sphere$1.radius += threshold;
  18610. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  18611. //
  18612. _inverseMatrix$1.copy( matrixWorld ).invert();
  18613. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  18614. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18615. const localThresholdSq = localThreshold * localThreshold;
  18616. const vStart = new Vector3();
  18617. const vEnd = new Vector3();
  18618. const interSegment = new Vector3();
  18619. const interRay = new Vector3();
  18620. const step = this.isLineSegments ? 2 : 1;
  18621. const index = geometry.index;
  18622. const attributes = geometry.attributes;
  18623. const positionAttribute = attributes.position;
  18624. if ( index !== null ) {
  18625. const start = Math.max( 0, drawRange.start );
  18626. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  18627. for ( let i = start, l = end - 1; i < l; i += step ) {
  18628. const a = index.getX( i );
  18629. const b = index.getX( i + 1 );
  18630. vStart.fromBufferAttribute( positionAttribute, a );
  18631. vEnd.fromBufferAttribute( positionAttribute, b );
  18632. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18633. if ( distSq > localThresholdSq ) continue;
  18634. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18635. const distance = raycaster.ray.origin.distanceTo( interRay );
  18636. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18637. intersects.push( {
  18638. distance: distance,
  18639. // What do we want? intersection point on the ray or on the segment??
  18640. // point: raycaster.ray.at( distance ),
  18641. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18642. index: i,
  18643. face: null,
  18644. faceIndex: null,
  18645. object: this
  18646. } );
  18647. }
  18648. } else {
  18649. const start = Math.max( 0, drawRange.start );
  18650. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  18651. for ( let i = start, l = end - 1; i < l; i += step ) {
  18652. vStart.fromBufferAttribute( positionAttribute, i );
  18653. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  18654. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18655. if ( distSq > localThresholdSq ) continue;
  18656. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18657. const distance = raycaster.ray.origin.distanceTo( interRay );
  18658. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18659. intersects.push( {
  18660. distance: distance,
  18661. // What do we want? intersection point on the ray or on the segment??
  18662. // point: raycaster.ray.at( distance ),
  18663. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18664. index: i,
  18665. face: null,
  18666. faceIndex: null,
  18667. object: this
  18668. } );
  18669. }
  18670. }
  18671. }
  18672. updateMorphTargets() {
  18673. const geometry = this.geometry;
  18674. const morphAttributes = geometry.morphAttributes;
  18675. const keys = Object.keys( morphAttributes );
  18676. if ( keys.length > 0 ) {
  18677. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  18678. if ( morphAttribute !== undefined ) {
  18679. this.morphTargetInfluences = [];
  18680. this.morphTargetDictionary = {};
  18681. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  18682. const name = morphAttribute[ m ].name || String( m );
  18683. this.morphTargetInfluences.push( 0 );
  18684. this.morphTargetDictionary[ name ] = m;
  18685. }
  18686. }
  18687. }
  18688. }
  18689. }
  18690. const _start = /*@__PURE__*/ new Vector3();
  18691. const _end = /*@__PURE__*/ new Vector3();
  18692. class LineSegments extends Line {
  18693. constructor( geometry, material ) {
  18694. super( geometry, material );
  18695. this.isLineSegments = true;
  18696. this.type = 'LineSegments';
  18697. }
  18698. computeLineDistances() {
  18699. const geometry = this.geometry;
  18700. // we assume non-indexed geometry
  18701. if ( geometry.index === null ) {
  18702. const positionAttribute = geometry.attributes.position;
  18703. const lineDistances = [];
  18704. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  18705. _start.fromBufferAttribute( positionAttribute, i );
  18706. _end.fromBufferAttribute( positionAttribute, i + 1 );
  18707. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  18708. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  18709. }
  18710. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18711. } else {
  18712. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18713. }
  18714. return this;
  18715. }
  18716. }
  18717. class LineLoop extends Line {
  18718. constructor( geometry, material ) {
  18719. super( geometry, material );
  18720. this.isLineLoop = true;
  18721. this.type = 'LineLoop';
  18722. }
  18723. }
  18724. class PointsMaterial extends Material {
  18725. constructor( parameters ) {
  18726. super();
  18727. this.isPointsMaterial = true;
  18728. this.type = 'PointsMaterial';
  18729. this.color = new Color( 0xffffff );
  18730. this.map = null;
  18731. this.alphaMap = null;
  18732. this.size = 1;
  18733. this.sizeAttenuation = true;
  18734. this.fog = true;
  18735. this.setValues( parameters );
  18736. }
  18737. copy( source ) {
  18738. super.copy( source );
  18739. this.color.copy( source.color );
  18740. this.map = source.map;
  18741. this.alphaMap = source.alphaMap;
  18742. this.size = source.size;
  18743. this.sizeAttenuation = source.sizeAttenuation;
  18744. this.fog = source.fog;
  18745. return this;
  18746. }
  18747. }
  18748. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  18749. const _ray = /*@__PURE__*/ new Ray();
  18750. const _sphere = /*@__PURE__*/ new Sphere();
  18751. const _position$2 = /*@__PURE__*/ new Vector3();
  18752. class Points extends Object3D {
  18753. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  18754. super();
  18755. this.isPoints = true;
  18756. this.type = 'Points';
  18757. this.geometry = geometry;
  18758. this.material = material;
  18759. this.updateMorphTargets();
  18760. }
  18761. copy( source, recursive ) {
  18762. super.copy( source, recursive );
  18763. this.material = source.material;
  18764. this.geometry = source.geometry;
  18765. return this;
  18766. }
  18767. raycast( raycaster, intersects ) {
  18768. const geometry = this.geometry;
  18769. const matrixWorld = this.matrixWorld;
  18770. const threshold = raycaster.params.Points.threshold;
  18771. const drawRange = geometry.drawRange;
  18772. // Checking boundingSphere distance to ray
  18773. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18774. _sphere.copy( geometry.boundingSphere );
  18775. _sphere.applyMatrix4( matrixWorld );
  18776. _sphere.radius += threshold;
  18777. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  18778. //
  18779. _inverseMatrix.copy( matrixWorld ).invert();
  18780. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  18781. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18782. const localThresholdSq = localThreshold * localThreshold;
  18783. const index = geometry.index;
  18784. const attributes = geometry.attributes;
  18785. const positionAttribute = attributes.position;
  18786. if ( index !== null ) {
  18787. const start = Math.max( 0, drawRange.start );
  18788. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  18789. for ( let i = start, il = end; i < il; i ++ ) {
  18790. const a = index.getX( i );
  18791. _position$2.fromBufferAttribute( positionAttribute, a );
  18792. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  18793. }
  18794. } else {
  18795. const start = Math.max( 0, drawRange.start );
  18796. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  18797. for ( let i = start, l = end; i < l; i ++ ) {
  18798. _position$2.fromBufferAttribute( positionAttribute, i );
  18799. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  18800. }
  18801. }
  18802. }
  18803. updateMorphTargets() {
  18804. const geometry = this.geometry;
  18805. const morphAttributes = geometry.morphAttributes;
  18806. const keys = Object.keys( morphAttributes );
  18807. if ( keys.length > 0 ) {
  18808. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  18809. if ( morphAttribute !== undefined ) {
  18810. this.morphTargetInfluences = [];
  18811. this.morphTargetDictionary = {};
  18812. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  18813. const name = morphAttribute[ m ].name || String( m );
  18814. this.morphTargetInfluences.push( 0 );
  18815. this.morphTargetDictionary[ name ] = m;
  18816. }
  18817. }
  18818. }
  18819. }
  18820. }
  18821. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  18822. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  18823. if ( rayPointDistanceSq < localThresholdSq ) {
  18824. const intersectPoint = new Vector3();
  18825. _ray.closestPointToPoint( point, intersectPoint );
  18826. intersectPoint.applyMatrix4( matrixWorld );
  18827. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  18828. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18829. intersects.push( {
  18830. distance: distance,
  18831. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  18832. point: intersectPoint,
  18833. index: index,
  18834. face: null,
  18835. object: object
  18836. } );
  18837. }
  18838. }
  18839. class VideoTexture extends Texture {
  18840. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18841. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18842. this.isVideoTexture = true;
  18843. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  18844. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  18845. this.generateMipmaps = false;
  18846. const scope = this;
  18847. function updateVideo() {
  18848. scope.needsUpdate = true;
  18849. video.requestVideoFrameCallback( updateVideo );
  18850. }
  18851. if ( 'requestVideoFrameCallback' in video ) {
  18852. video.requestVideoFrameCallback( updateVideo );
  18853. }
  18854. }
  18855. clone() {
  18856. return new this.constructor( this.image ).copy( this );
  18857. }
  18858. update() {
  18859. const video = this.image;
  18860. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  18861. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  18862. this.needsUpdate = true;
  18863. }
  18864. }
  18865. }
  18866. class FramebufferTexture extends Texture {
  18867. constructor( width, height, format ) {
  18868. super( { width, height } );
  18869. this.isFramebufferTexture = true;
  18870. this.format = format;
  18871. this.magFilter = NearestFilter;
  18872. this.minFilter = NearestFilter;
  18873. this.generateMipmaps = false;
  18874. this.needsUpdate = true;
  18875. }
  18876. }
  18877. class CompressedTexture extends Texture {
  18878. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  18879. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  18880. this.isCompressedTexture = true;
  18881. this.image = { width: width, height: height };
  18882. this.mipmaps = mipmaps;
  18883. // no flipping for cube textures
  18884. // (also flipping doesn't work for compressed textures )
  18885. this.flipY = false;
  18886. // can't generate mipmaps for compressed textures
  18887. // mips must be embedded in DDS files
  18888. this.generateMipmaps = false;
  18889. }
  18890. }
  18891. class CompressedArrayTexture extends CompressedTexture {
  18892. constructor( mipmaps, width, height, depth, format, type ) {
  18893. super( mipmaps, width, height, format, type );
  18894. this.isCompressedArrayTexture = true;
  18895. this.image.depth = depth;
  18896. this.wrapR = ClampToEdgeWrapping;
  18897. }
  18898. }
  18899. class CanvasTexture extends Texture {
  18900. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18901. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18902. this.isCanvasTexture = true;
  18903. this.needsUpdate = true;
  18904. }
  18905. }
  18906. /**
  18907. * Extensible curve object.
  18908. *
  18909. * Some common of curve methods:
  18910. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  18911. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  18912. * .getPoints(), .getSpacedPoints()
  18913. * .getLength()
  18914. * .updateArcLengths()
  18915. *
  18916. * This following curves inherit from THREE.Curve:
  18917. *
  18918. * -- 2D curves --
  18919. * THREE.ArcCurve
  18920. * THREE.CubicBezierCurve
  18921. * THREE.EllipseCurve
  18922. * THREE.LineCurve
  18923. * THREE.QuadraticBezierCurve
  18924. * THREE.SplineCurve
  18925. *
  18926. * -- 3D curves --
  18927. * THREE.CatmullRomCurve3
  18928. * THREE.CubicBezierCurve3
  18929. * THREE.LineCurve3
  18930. * THREE.QuadraticBezierCurve3
  18931. *
  18932. * A series of curves can be represented as a THREE.CurvePath.
  18933. *
  18934. **/
  18935. class Curve {
  18936. constructor() {
  18937. this.type = 'Curve';
  18938. this.arcLengthDivisions = 200;
  18939. }
  18940. // Virtual base class method to overwrite and implement in subclasses
  18941. // - t [0 .. 1]
  18942. getPoint( /* t, optionalTarget */ ) {
  18943. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  18944. return null;
  18945. }
  18946. // Get point at relative position in curve according to arc length
  18947. // - u [0 .. 1]
  18948. getPointAt( u, optionalTarget ) {
  18949. const t = this.getUtoTmapping( u );
  18950. return this.getPoint( t, optionalTarget );
  18951. }
  18952. // Get sequence of points using getPoint( t )
  18953. getPoints( divisions = 5 ) {
  18954. const points = [];
  18955. for ( let d = 0; d <= divisions; d ++ ) {
  18956. points.push( this.getPoint( d / divisions ) );
  18957. }
  18958. return points;
  18959. }
  18960. // Get sequence of points using getPointAt( u )
  18961. getSpacedPoints( divisions = 5 ) {
  18962. const points = [];
  18963. for ( let d = 0; d <= divisions; d ++ ) {
  18964. points.push( this.getPointAt( d / divisions ) );
  18965. }
  18966. return points;
  18967. }
  18968. // Get total curve arc length
  18969. getLength() {
  18970. const lengths = this.getLengths();
  18971. return lengths[ lengths.length - 1 ];
  18972. }
  18973. // Get list of cumulative segment lengths
  18974. getLengths( divisions = this.arcLengthDivisions ) {
  18975. if ( this.cacheArcLengths &&
  18976. ( this.cacheArcLengths.length === divisions + 1 ) &&
  18977. ! this.needsUpdate ) {
  18978. return this.cacheArcLengths;
  18979. }
  18980. this.needsUpdate = false;
  18981. const cache = [];
  18982. let current, last = this.getPoint( 0 );
  18983. let sum = 0;
  18984. cache.push( 0 );
  18985. for ( let p = 1; p <= divisions; p ++ ) {
  18986. current = this.getPoint( p / divisions );
  18987. sum += current.distanceTo( last );
  18988. cache.push( sum );
  18989. last = current;
  18990. }
  18991. this.cacheArcLengths = cache;
  18992. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  18993. }
  18994. updateArcLengths() {
  18995. this.needsUpdate = true;
  18996. this.getLengths();
  18997. }
  18998. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  18999. getUtoTmapping( u, distance ) {
  19000. const arcLengths = this.getLengths();
  19001. let i = 0;
  19002. const il = arcLengths.length;
  19003. let targetArcLength; // The targeted u distance value to get
  19004. if ( distance ) {
  19005. targetArcLength = distance;
  19006. } else {
  19007. targetArcLength = u * arcLengths[ il - 1 ];
  19008. }
  19009. // binary search for the index with largest value smaller than target u distance
  19010. let low = 0, high = il - 1, comparison;
  19011. while ( low <= high ) {
  19012. 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
  19013. comparison = arcLengths[ i ] - targetArcLength;
  19014. if ( comparison < 0 ) {
  19015. low = i + 1;
  19016. } else if ( comparison > 0 ) {
  19017. high = i - 1;
  19018. } else {
  19019. high = i;
  19020. break;
  19021. // DONE
  19022. }
  19023. }
  19024. i = high;
  19025. if ( arcLengths[ i ] === targetArcLength ) {
  19026. return i / ( il - 1 );
  19027. }
  19028. // we could get finer grain at lengths, or use simple interpolation between two points
  19029. const lengthBefore = arcLengths[ i ];
  19030. const lengthAfter = arcLengths[ i + 1 ];
  19031. const segmentLength = lengthAfter - lengthBefore;
  19032. // determine where we are between the 'before' and 'after' points
  19033. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  19034. // add that fractional amount to t
  19035. const t = ( i + segmentFraction ) / ( il - 1 );
  19036. return t;
  19037. }
  19038. // Returns a unit vector tangent at t
  19039. // In case any sub curve does not implement its tangent derivation,
  19040. // 2 points a small delta apart will be used to find its gradient
  19041. // which seems to give a reasonable approximation
  19042. getTangent( t, optionalTarget ) {
  19043. const delta = 0.0001;
  19044. let t1 = t - delta;
  19045. let t2 = t + delta;
  19046. // Capping in case of danger
  19047. if ( t1 < 0 ) t1 = 0;
  19048. if ( t2 > 1 ) t2 = 1;
  19049. const pt1 = this.getPoint( t1 );
  19050. const pt2 = this.getPoint( t2 );
  19051. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  19052. tangent.copy( pt2 ).sub( pt1 ).normalize();
  19053. return tangent;
  19054. }
  19055. getTangentAt( u, optionalTarget ) {
  19056. const t = this.getUtoTmapping( u );
  19057. return this.getTangent( t, optionalTarget );
  19058. }
  19059. computeFrenetFrames( segments, closed ) {
  19060. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19061. const normal = new Vector3();
  19062. const tangents = [];
  19063. const normals = [];
  19064. const binormals = [];
  19065. const vec = new Vector3();
  19066. const mat = new Matrix4();
  19067. // compute the tangent vectors for each segment on the curve
  19068. for ( let i = 0; i <= segments; i ++ ) {
  19069. const u = i / segments;
  19070. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  19071. }
  19072. // select an initial normal vector perpendicular to the first tangent vector,
  19073. // and in the direction of the minimum tangent xyz component
  19074. normals[ 0 ] = new Vector3();
  19075. binormals[ 0 ] = new Vector3();
  19076. let min = Number.MAX_VALUE;
  19077. const tx = Math.abs( tangents[ 0 ].x );
  19078. const ty = Math.abs( tangents[ 0 ].y );
  19079. const tz = Math.abs( tangents[ 0 ].z );
  19080. if ( tx <= min ) {
  19081. min = tx;
  19082. normal.set( 1, 0, 0 );
  19083. }
  19084. if ( ty <= min ) {
  19085. min = ty;
  19086. normal.set( 0, 1, 0 );
  19087. }
  19088. if ( tz <= min ) {
  19089. normal.set( 0, 0, 1 );
  19090. }
  19091. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19092. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19093. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19094. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  19095. for ( let i = 1; i <= segments; i ++ ) {
  19096. normals[ i ] = normals[ i - 1 ].clone();
  19097. binormals[ i ] = binormals[ i - 1 ].clone();
  19098. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  19099. if ( vec.length() > Number.EPSILON ) {
  19100. vec.normalize();
  19101. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  19102. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19103. }
  19104. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19105. }
  19106. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19107. if ( closed === true ) {
  19108. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  19109. theta /= segments;
  19110. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  19111. theta = - theta;
  19112. }
  19113. for ( let i = 1; i <= segments; i ++ ) {
  19114. // twist a little...
  19115. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19116. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19117. }
  19118. }
  19119. return {
  19120. tangents: tangents,
  19121. normals: normals,
  19122. binormals: binormals
  19123. };
  19124. }
  19125. clone() {
  19126. return new this.constructor().copy( this );
  19127. }
  19128. copy( source ) {
  19129. this.arcLengthDivisions = source.arcLengthDivisions;
  19130. return this;
  19131. }
  19132. toJSON() {
  19133. const data = {
  19134. metadata: {
  19135. version: 4.5,
  19136. type: 'Curve',
  19137. generator: 'Curve.toJSON'
  19138. }
  19139. };
  19140. data.arcLengthDivisions = this.arcLengthDivisions;
  19141. data.type = this.type;
  19142. return data;
  19143. }
  19144. fromJSON( json ) {
  19145. this.arcLengthDivisions = json.arcLengthDivisions;
  19146. return this;
  19147. }
  19148. }
  19149. class EllipseCurve extends Curve {
  19150. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  19151. super();
  19152. this.isEllipseCurve = true;
  19153. this.type = 'EllipseCurve';
  19154. this.aX = aX;
  19155. this.aY = aY;
  19156. this.xRadius = xRadius;
  19157. this.yRadius = yRadius;
  19158. this.aStartAngle = aStartAngle;
  19159. this.aEndAngle = aEndAngle;
  19160. this.aClockwise = aClockwise;
  19161. this.aRotation = aRotation;
  19162. }
  19163. getPoint( t, optionalTarget ) {
  19164. const point = optionalTarget || new Vector2();
  19165. const twoPi = Math.PI * 2;
  19166. let deltaAngle = this.aEndAngle - this.aStartAngle;
  19167. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  19168. // ensures that deltaAngle is 0 .. 2 PI
  19169. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  19170. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  19171. if ( deltaAngle < Number.EPSILON ) {
  19172. if ( samePoints ) {
  19173. deltaAngle = 0;
  19174. } else {
  19175. deltaAngle = twoPi;
  19176. }
  19177. }
  19178. if ( this.aClockwise === true && ! samePoints ) {
  19179. if ( deltaAngle === twoPi ) {
  19180. deltaAngle = - twoPi;
  19181. } else {
  19182. deltaAngle = deltaAngle - twoPi;
  19183. }
  19184. }
  19185. const angle = this.aStartAngle + t * deltaAngle;
  19186. let x = this.aX + this.xRadius * Math.cos( angle );
  19187. let y = this.aY + this.yRadius * Math.sin( angle );
  19188. if ( this.aRotation !== 0 ) {
  19189. const cos = Math.cos( this.aRotation );
  19190. const sin = Math.sin( this.aRotation );
  19191. const tx = x - this.aX;
  19192. const ty = y - this.aY;
  19193. // Rotate the point about the center of the ellipse.
  19194. x = tx * cos - ty * sin + this.aX;
  19195. y = tx * sin + ty * cos + this.aY;
  19196. }
  19197. return point.set( x, y );
  19198. }
  19199. copy( source ) {
  19200. super.copy( source );
  19201. this.aX = source.aX;
  19202. this.aY = source.aY;
  19203. this.xRadius = source.xRadius;
  19204. this.yRadius = source.yRadius;
  19205. this.aStartAngle = source.aStartAngle;
  19206. this.aEndAngle = source.aEndAngle;
  19207. this.aClockwise = source.aClockwise;
  19208. this.aRotation = source.aRotation;
  19209. return this;
  19210. }
  19211. toJSON() {
  19212. const data = super.toJSON();
  19213. data.aX = this.aX;
  19214. data.aY = this.aY;
  19215. data.xRadius = this.xRadius;
  19216. data.yRadius = this.yRadius;
  19217. data.aStartAngle = this.aStartAngle;
  19218. data.aEndAngle = this.aEndAngle;
  19219. data.aClockwise = this.aClockwise;
  19220. data.aRotation = this.aRotation;
  19221. return data;
  19222. }
  19223. fromJSON( json ) {
  19224. super.fromJSON( json );
  19225. this.aX = json.aX;
  19226. this.aY = json.aY;
  19227. this.xRadius = json.xRadius;
  19228. this.yRadius = json.yRadius;
  19229. this.aStartAngle = json.aStartAngle;
  19230. this.aEndAngle = json.aEndAngle;
  19231. this.aClockwise = json.aClockwise;
  19232. this.aRotation = json.aRotation;
  19233. return this;
  19234. }
  19235. }
  19236. class ArcCurve extends EllipseCurve {
  19237. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19238. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  19239. this.isArcCurve = true;
  19240. this.type = 'ArcCurve';
  19241. }
  19242. }
  19243. /**
  19244. * Centripetal CatmullRom Curve - which is useful for avoiding
  19245. * cusps and self-intersections in non-uniform catmull rom curves.
  19246. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  19247. *
  19248. * curve.type accepts centripetal(default), chordal and catmullrom
  19249. * curve.tension is used for catmullrom which defaults to 0.5
  19250. */
  19251. /*
  19252. Based on an optimized c++ solution in
  19253. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  19254. - http://ideone.com/NoEbVM
  19255. This CubicPoly class could be used for reusing some variables and calculations,
  19256. but for three.js curve use, it could be possible inlined and flatten into a single function call
  19257. which can be placed in CurveUtils.
  19258. */
  19259. function CubicPoly() {
  19260. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  19261. /*
  19262. * Compute coefficients for a cubic polynomial
  19263. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  19264. * such that
  19265. * p(0) = x0, p(1) = x1
  19266. * and
  19267. * p'(0) = t0, p'(1) = t1.
  19268. */
  19269. function init( x0, x1, t0, t1 ) {
  19270. c0 = x0;
  19271. c1 = t0;
  19272. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  19273. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  19274. }
  19275. return {
  19276. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  19277. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  19278. },
  19279. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  19280. // compute tangents when parameterized in [t1,t2]
  19281. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  19282. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  19283. // rescale tangents for parametrization in [0,1]
  19284. t1 *= dt1;
  19285. t2 *= dt1;
  19286. init( x1, x2, t1, t2 );
  19287. },
  19288. calc: function ( t ) {
  19289. const t2 = t * t;
  19290. const t3 = t2 * t;
  19291. return c0 + c1 * t + c2 * t2 + c3 * t3;
  19292. }
  19293. };
  19294. }
  19295. //
  19296. const tmp = /*@__PURE__*/ new Vector3();
  19297. const px = /*@__PURE__*/ new CubicPoly();
  19298. const py = /*@__PURE__*/ new CubicPoly();
  19299. const pz = /*@__PURE__*/ new CubicPoly();
  19300. class CatmullRomCurve3 extends Curve {
  19301. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  19302. super();
  19303. this.isCatmullRomCurve3 = true;
  19304. this.type = 'CatmullRomCurve3';
  19305. this.points = points;
  19306. this.closed = closed;
  19307. this.curveType = curveType;
  19308. this.tension = tension;
  19309. }
  19310. getPoint( t, optionalTarget = new Vector3() ) {
  19311. const point = optionalTarget;
  19312. const points = this.points;
  19313. const l = points.length;
  19314. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  19315. let intPoint = Math.floor( p );
  19316. let weight = p - intPoint;
  19317. if ( this.closed ) {
  19318. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  19319. } else if ( weight === 0 && intPoint === l - 1 ) {
  19320. intPoint = l - 2;
  19321. weight = 1;
  19322. }
  19323. let p0, p3; // 4 points (p1 & p2 defined below)
  19324. if ( this.closed || intPoint > 0 ) {
  19325. p0 = points[ ( intPoint - 1 ) % l ];
  19326. } else {
  19327. // extrapolate first point
  19328. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  19329. p0 = tmp;
  19330. }
  19331. const p1 = points[ intPoint % l ];
  19332. const p2 = points[ ( intPoint + 1 ) % l ];
  19333. if ( this.closed || intPoint + 2 < l ) {
  19334. p3 = points[ ( intPoint + 2 ) % l ];
  19335. } else {
  19336. // extrapolate last point
  19337. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  19338. p3 = tmp;
  19339. }
  19340. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  19341. // init Centripetal / Chordal Catmull-Rom
  19342. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  19343. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  19344. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  19345. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  19346. // safety check for repeated points
  19347. if ( dt1 < 1e-4 ) dt1 = 1.0;
  19348. if ( dt0 < 1e-4 ) dt0 = dt1;
  19349. if ( dt2 < 1e-4 ) dt2 = dt1;
  19350. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  19351. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  19352. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  19353. } else if ( this.curveType === 'catmullrom' ) {
  19354. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  19355. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  19356. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  19357. }
  19358. point.set(
  19359. px.calc( weight ),
  19360. py.calc( weight ),
  19361. pz.calc( weight )
  19362. );
  19363. return point;
  19364. }
  19365. copy( source ) {
  19366. super.copy( source );
  19367. this.points = [];
  19368. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19369. const point = source.points[ i ];
  19370. this.points.push( point.clone() );
  19371. }
  19372. this.closed = source.closed;
  19373. this.curveType = source.curveType;
  19374. this.tension = source.tension;
  19375. return this;
  19376. }
  19377. toJSON() {
  19378. const data = super.toJSON();
  19379. data.points = [];
  19380. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19381. const point = this.points[ i ];
  19382. data.points.push( point.toArray() );
  19383. }
  19384. data.closed = this.closed;
  19385. data.curveType = this.curveType;
  19386. data.tension = this.tension;
  19387. return data;
  19388. }
  19389. fromJSON( json ) {
  19390. super.fromJSON( json );
  19391. this.points = [];
  19392. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19393. const point = json.points[ i ];
  19394. this.points.push( new Vector3().fromArray( point ) );
  19395. }
  19396. this.closed = json.closed;
  19397. this.curveType = json.curveType;
  19398. this.tension = json.tension;
  19399. return this;
  19400. }
  19401. }
  19402. /**
  19403. * Bezier Curves formulas obtained from
  19404. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  19405. */
  19406. function CatmullRom( t, p0, p1, p2, p3 ) {
  19407. const v0 = ( p2 - p0 ) * 0.5;
  19408. const v1 = ( p3 - p1 ) * 0.5;
  19409. const t2 = t * t;
  19410. const t3 = t * t2;
  19411. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  19412. }
  19413. //
  19414. function QuadraticBezierP0( t, p ) {
  19415. const k = 1 - t;
  19416. return k * k * p;
  19417. }
  19418. function QuadraticBezierP1( t, p ) {
  19419. return 2 * ( 1 - t ) * t * p;
  19420. }
  19421. function QuadraticBezierP2( t, p ) {
  19422. return t * t * p;
  19423. }
  19424. function QuadraticBezier( t, p0, p1, p2 ) {
  19425. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  19426. QuadraticBezierP2( t, p2 );
  19427. }
  19428. //
  19429. function CubicBezierP0( t, p ) {
  19430. const k = 1 - t;
  19431. return k * k * k * p;
  19432. }
  19433. function CubicBezierP1( t, p ) {
  19434. const k = 1 - t;
  19435. return 3 * k * k * t * p;
  19436. }
  19437. function CubicBezierP2( t, p ) {
  19438. return 3 * ( 1 - t ) * t * t * p;
  19439. }
  19440. function CubicBezierP3( t, p ) {
  19441. return t * t * t * p;
  19442. }
  19443. function CubicBezier( t, p0, p1, p2, p3 ) {
  19444. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  19445. CubicBezierP3( t, p3 );
  19446. }
  19447. class CubicBezierCurve extends Curve {
  19448. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  19449. super();
  19450. this.isCubicBezierCurve = true;
  19451. this.type = 'CubicBezierCurve';
  19452. this.v0 = v0;
  19453. this.v1 = v1;
  19454. this.v2 = v2;
  19455. this.v3 = v3;
  19456. }
  19457. getPoint( t, optionalTarget = new Vector2() ) {
  19458. const point = optionalTarget;
  19459. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19460. point.set(
  19461. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19462. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  19463. );
  19464. return point;
  19465. }
  19466. copy( source ) {
  19467. super.copy( source );
  19468. this.v0.copy( source.v0 );
  19469. this.v1.copy( source.v1 );
  19470. this.v2.copy( source.v2 );
  19471. this.v3.copy( source.v3 );
  19472. return this;
  19473. }
  19474. toJSON() {
  19475. const data = super.toJSON();
  19476. data.v0 = this.v0.toArray();
  19477. data.v1 = this.v1.toArray();
  19478. data.v2 = this.v2.toArray();
  19479. data.v3 = this.v3.toArray();
  19480. return data;
  19481. }
  19482. fromJSON( json ) {
  19483. super.fromJSON( json );
  19484. this.v0.fromArray( json.v0 );
  19485. this.v1.fromArray( json.v1 );
  19486. this.v2.fromArray( json.v2 );
  19487. this.v3.fromArray( json.v3 );
  19488. return this;
  19489. }
  19490. }
  19491. class CubicBezierCurve3 extends Curve {
  19492. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  19493. super();
  19494. this.isCubicBezierCurve3 = true;
  19495. this.type = 'CubicBezierCurve3';
  19496. this.v0 = v0;
  19497. this.v1 = v1;
  19498. this.v2 = v2;
  19499. this.v3 = v3;
  19500. }
  19501. getPoint( t, optionalTarget = new Vector3() ) {
  19502. const point = optionalTarget;
  19503. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  19504. point.set(
  19505. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  19506. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  19507. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  19508. );
  19509. return point;
  19510. }
  19511. copy( source ) {
  19512. super.copy( source );
  19513. this.v0.copy( source.v0 );
  19514. this.v1.copy( source.v1 );
  19515. this.v2.copy( source.v2 );
  19516. this.v3.copy( source.v3 );
  19517. return this;
  19518. }
  19519. toJSON() {
  19520. const data = super.toJSON();
  19521. data.v0 = this.v0.toArray();
  19522. data.v1 = this.v1.toArray();
  19523. data.v2 = this.v2.toArray();
  19524. data.v3 = this.v3.toArray();
  19525. return data;
  19526. }
  19527. fromJSON( json ) {
  19528. super.fromJSON( json );
  19529. this.v0.fromArray( json.v0 );
  19530. this.v1.fromArray( json.v1 );
  19531. this.v2.fromArray( json.v2 );
  19532. this.v3.fromArray( json.v3 );
  19533. return this;
  19534. }
  19535. }
  19536. class LineCurve extends Curve {
  19537. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  19538. super();
  19539. this.isLineCurve = true;
  19540. this.type = 'LineCurve';
  19541. this.v1 = v1;
  19542. this.v2 = v2;
  19543. }
  19544. getPoint( t, optionalTarget = new Vector2() ) {
  19545. const point = optionalTarget;
  19546. if ( t === 1 ) {
  19547. point.copy( this.v2 );
  19548. } else {
  19549. point.copy( this.v2 ).sub( this.v1 );
  19550. point.multiplyScalar( t ).add( this.v1 );
  19551. }
  19552. return point;
  19553. }
  19554. // Line curve is linear, so we can overwrite default getPointAt
  19555. getPointAt( u, optionalTarget ) {
  19556. return this.getPoint( u, optionalTarget );
  19557. }
  19558. getTangent( t, optionalTarget = new Vector2() ) {
  19559. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  19560. }
  19561. getTangentAt( u, optionalTarget ) {
  19562. return this.getTangent( u, optionalTarget );
  19563. }
  19564. copy( source ) {
  19565. super.copy( source );
  19566. this.v1.copy( source.v1 );
  19567. this.v2.copy( source.v2 );
  19568. return this;
  19569. }
  19570. toJSON() {
  19571. const data = super.toJSON();
  19572. data.v1 = this.v1.toArray();
  19573. data.v2 = this.v2.toArray();
  19574. return data;
  19575. }
  19576. fromJSON( json ) {
  19577. super.fromJSON( json );
  19578. this.v1.fromArray( json.v1 );
  19579. this.v2.fromArray( json.v2 );
  19580. return this;
  19581. }
  19582. }
  19583. class LineCurve3 extends Curve {
  19584. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  19585. super();
  19586. this.isLineCurve3 = true;
  19587. this.type = 'LineCurve3';
  19588. this.v1 = v1;
  19589. this.v2 = v2;
  19590. }
  19591. getPoint( t, optionalTarget = new Vector3() ) {
  19592. const point = optionalTarget;
  19593. if ( t === 1 ) {
  19594. point.copy( this.v2 );
  19595. } else {
  19596. point.copy( this.v2 ).sub( this.v1 );
  19597. point.multiplyScalar( t ).add( this.v1 );
  19598. }
  19599. return point;
  19600. }
  19601. // Line curve is linear, so we can overwrite default getPointAt
  19602. getPointAt( u, optionalTarget ) {
  19603. return this.getPoint( u, optionalTarget );
  19604. }
  19605. getTangent( t, optionalTarget = new Vector3() ) {
  19606. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  19607. }
  19608. getTangentAt( u, optionalTarget ) {
  19609. return this.getTangent( u, optionalTarget );
  19610. }
  19611. copy( source ) {
  19612. super.copy( source );
  19613. this.v1.copy( source.v1 );
  19614. this.v2.copy( source.v2 );
  19615. return this;
  19616. }
  19617. toJSON() {
  19618. const data = super.toJSON();
  19619. data.v1 = this.v1.toArray();
  19620. data.v2 = this.v2.toArray();
  19621. return data;
  19622. }
  19623. fromJSON( json ) {
  19624. super.fromJSON( json );
  19625. this.v1.fromArray( json.v1 );
  19626. this.v2.fromArray( json.v2 );
  19627. return this;
  19628. }
  19629. }
  19630. class QuadraticBezierCurve extends Curve {
  19631. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  19632. super();
  19633. this.isQuadraticBezierCurve = true;
  19634. this.type = 'QuadraticBezierCurve';
  19635. this.v0 = v0;
  19636. this.v1 = v1;
  19637. this.v2 = v2;
  19638. }
  19639. getPoint( t, optionalTarget = new Vector2() ) {
  19640. const point = optionalTarget;
  19641. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19642. point.set(
  19643. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19644. QuadraticBezier( t, v0.y, v1.y, v2.y )
  19645. );
  19646. return point;
  19647. }
  19648. copy( source ) {
  19649. super.copy( source );
  19650. this.v0.copy( source.v0 );
  19651. this.v1.copy( source.v1 );
  19652. this.v2.copy( source.v2 );
  19653. return this;
  19654. }
  19655. toJSON() {
  19656. const data = super.toJSON();
  19657. data.v0 = this.v0.toArray();
  19658. data.v1 = this.v1.toArray();
  19659. data.v2 = this.v2.toArray();
  19660. return data;
  19661. }
  19662. fromJSON( json ) {
  19663. super.fromJSON( json );
  19664. this.v0.fromArray( json.v0 );
  19665. this.v1.fromArray( json.v1 );
  19666. this.v2.fromArray( json.v2 );
  19667. return this;
  19668. }
  19669. }
  19670. class QuadraticBezierCurve3 extends Curve {
  19671. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  19672. super();
  19673. this.isQuadraticBezierCurve3 = true;
  19674. this.type = 'QuadraticBezierCurve3';
  19675. this.v0 = v0;
  19676. this.v1 = v1;
  19677. this.v2 = v2;
  19678. }
  19679. getPoint( t, optionalTarget = new Vector3() ) {
  19680. const point = optionalTarget;
  19681. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19682. point.set(
  19683. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19684. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  19685. QuadraticBezier( t, v0.z, v1.z, v2.z )
  19686. );
  19687. return point;
  19688. }
  19689. copy( source ) {
  19690. super.copy( source );
  19691. this.v0.copy( source.v0 );
  19692. this.v1.copy( source.v1 );
  19693. this.v2.copy( source.v2 );
  19694. return this;
  19695. }
  19696. toJSON() {
  19697. const data = super.toJSON();
  19698. data.v0 = this.v0.toArray();
  19699. data.v1 = this.v1.toArray();
  19700. data.v2 = this.v2.toArray();
  19701. return data;
  19702. }
  19703. fromJSON( json ) {
  19704. super.fromJSON( json );
  19705. this.v0.fromArray( json.v0 );
  19706. this.v1.fromArray( json.v1 );
  19707. this.v2.fromArray( json.v2 );
  19708. return this;
  19709. }
  19710. }
  19711. class SplineCurve extends Curve {
  19712. constructor( points = [] ) {
  19713. super();
  19714. this.isSplineCurve = true;
  19715. this.type = 'SplineCurve';
  19716. this.points = points;
  19717. }
  19718. getPoint( t, optionalTarget = new Vector2() ) {
  19719. const point = optionalTarget;
  19720. const points = this.points;
  19721. const p = ( points.length - 1 ) * t;
  19722. const intPoint = Math.floor( p );
  19723. const weight = p - intPoint;
  19724. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  19725. const p1 = points[ intPoint ];
  19726. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  19727. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  19728. point.set(
  19729. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  19730. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  19731. );
  19732. return point;
  19733. }
  19734. copy( source ) {
  19735. super.copy( source );
  19736. this.points = [];
  19737. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19738. const point = source.points[ i ];
  19739. this.points.push( point.clone() );
  19740. }
  19741. return this;
  19742. }
  19743. toJSON() {
  19744. const data = super.toJSON();
  19745. data.points = [];
  19746. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19747. const point = this.points[ i ];
  19748. data.points.push( point.toArray() );
  19749. }
  19750. return data;
  19751. }
  19752. fromJSON( json ) {
  19753. super.fromJSON( json );
  19754. this.points = [];
  19755. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19756. const point = json.points[ i ];
  19757. this.points.push( new Vector2().fromArray( point ) );
  19758. }
  19759. return this;
  19760. }
  19761. }
  19762. var Curves = /*#__PURE__*/Object.freeze({
  19763. __proto__: null,
  19764. ArcCurve: ArcCurve,
  19765. CatmullRomCurve3: CatmullRomCurve3,
  19766. CubicBezierCurve: CubicBezierCurve,
  19767. CubicBezierCurve3: CubicBezierCurve3,
  19768. EllipseCurve: EllipseCurve,
  19769. LineCurve: LineCurve,
  19770. LineCurve3: LineCurve3,
  19771. QuadraticBezierCurve: QuadraticBezierCurve,
  19772. QuadraticBezierCurve3: QuadraticBezierCurve3,
  19773. SplineCurve: SplineCurve
  19774. });
  19775. /**************************************************************
  19776. * Curved Path - a curve path is simply a array of connected
  19777. * curves, but retains the api of a curve
  19778. **************************************************************/
  19779. class CurvePath extends Curve {
  19780. constructor() {
  19781. super();
  19782. this.type = 'CurvePath';
  19783. this.curves = [];
  19784. this.autoClose = false; // Automatically closes the path
  19785. }
  19786. add( curve ) {
  19787. this.curves.push( curve );
  19788. }
  19789. closePath() {
  19790. // Add a line curve if start and end of lines are not connected
  19791. const startPoint = this.curves[ 0 ].getPoint( 0 );
  19792. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  19793. if ( ! startPoint.equals( endPoint ) ) {
  19794. this.curves.push( new LineCurve( endPoint, startPoint ) );
  19795. }
  19796. }
  19797. // To get accurate point with reference to
  19798. // entire path distance at time t,
  19799. // following has to be done:
  19800. // 1. Length of each sub path have to be known
  19801. // 2. Locate and identify type of curve
  19802. // 3. Get t for the curve
  19803. // 4. Return curve.getPointAt(t')
  19804. getPoint( t, optionalTarget ) {
  19805. const d = t * this.getLength();
  19806. const curveLengths = this.getCurveLengths();
  19807. let i = 0;
  19808. // To think about boundaries points.
  19809. while ( i < curveLengths.length ) {
  19810. if ( curveLengths[ i ] >= d ) {
  19811. const diff = curveLengths[ i ] - d;
  19812. const curve = this.curves[ i ];
  19813. const segmentLength = curve.getLength();
  19814. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  19815. return curve.getPointAt( u, optionalTarget );
  19816. }
  19817. i ++;
  19818. }
  19819. return null;
  19820. // loop where sum != 0, sum > d , sum+1 <d
  19821. }
  19822. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  19823. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  19824. // getPoint() depends on getLength
  19825. getLength() {
  19826. const lens = this.getCurveLengths();
  19827. return lens[ lens.length - 1 ];
  19828. }
  19829. // cacheLengths must be recalculated.
  19830. updateArcLengths() {
  19831. this.needsUpdate = true;
  19832. this.cacheLengths = null;
  19833. this.getCurveLengths();
  19834. }
  19835. // Compute lengths and cache them
  19836. // We cannot overwrite getLengths() because UtoT mapping uses it.
  19837. getCurveLengths() {
  19838. // We use cache values if curves and cache array are same length
  19839. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  19840. return this.cacheLengths;
  19841. }
  19842. // Get length of sub-curve
  19843. // Push sums into cached array
  19844. const lengths = [];
  19845. let sums = 0;
  19846. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19847. sums += this.curves[ i ].getLength();
  19848. lengths.push( sums );
  19849. }
  19850. this.cacheLengths = lengths;
  19851. return lengths;
  19852. }
  19853. getSpacedPoints( divisions = 40 ) {
  19854. const points = [];
  19855. for ( let i = 0; i <= divisions; i ++ ) {
  19856. points.push( this.getPoint( i / divisions ) );
  19857. }
  19858. if ( this.autoClose ) {
  19859. points.push( points[ 0 ] );
  19860. }
  19861. return points;
  19862. }
  19863. getPoints( divisions = 12 ) {
  19864. const points = [];
  19865. let last;
  19866. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  19867. const curve = curves[ i ];
  19868. const resolution = curve.isEllipseCurve ? divisions * 2
  19869. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  19870. : curve.isSplineCurve ? divisions * curve.points.length
  19871. : divisions;
  19872. const pts = curve.getPoints( resolution );
  19873. for ( let j = 0; j < pts.length; j ++ ) {
  19874. const point = pts[ j ];
  19875. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  19876. points.push( point );
  19877. last = point;
  19878. }
  19879. }
  19880. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  19881. points.push( points[ 0 ] );
  19882. }
  19883. return points;
  19884. }
  19885. copy( source ) {
  19886. super.copy( source );
  19887. this.curves = [];
  19888. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  19889. const curve = source.curves[ i ];
  19890. this.curves.push( curve.clone() );
  19891. }
  19892. this.autoClose = source.autoClose;
  19893. return this;
  19894. }
  19895. toJSON() {
  19896. const data = super.toJSON();
  19897. data.autoClose = this.autoClose;
  19898. data.curves = [];
  19899. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19900. const curve = this.curves[ i ];
  19901. data.curves.push( curve.toJSON() );
  19902. }
  19903. return data;
  19904. }
  19905. fromJSON( json ) {
  19906. super.fromJSON( json );
  19907. this.autoClose = json.autoClose;
  19908. this.curves = [];
  19909. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  19910. const curve = json.curves[ i ];
  19911. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  19912. }
  19913. return this;
  19914. }
  19915. }
  19916. class Path extends CurvePath {
  19917. constructor( points ) {
  19918. super();
  19919. this.type = 'Path';
  19920. this.currentPoint = new Vector2();
  19921. if ( points ) {
  19922. this.setFromPoints( points );
  19923. }
  19924. }
  19925. setFromPoints( points ) {
  19926. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  19927. for ( let i = 1, l = points.length; i < l; i ++ ) {
  19928. this.lineTo( points[ i ].x, points[ i ].y );
  19929. }
  19930. return this;
  19931. }
  19932. moveTo( x, y ) {
  19933. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  19934. return this;
  19935. }
  19936. lineTo( x, y ) {
  19937. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  19938. this.curves.push( curve );
  19939. this.currentPoint.set( x, y );
  19940. return this;
  19941. }
  19942. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  19943. const curve = new QuadraticBezierCurve(
  19944. this.currentPoint.clone(),
  19945. new Vector2( aCPx, aCPy ),
  19946. new Vector2( aX, aY )
  19947. );
  19948. this.curves.push( curve );
  19949. this.currentPoint.set( aX, aY );
  19950. return this;
  19951. }
  19952. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  19953. const curve = new CubicBezierCurve(
  19954. this.currentPoint.clone(),
  19955. new Vector2( aCP1x, aCP1y ),
  19956. new Vector2( aCP2x, aCP2y ),
  19957. new Vector2( aX, aY )
  19958. );
  19959. this.curves.push( curve );
  19960. this.currentPoint.set( aX, aY );
  19961. return this;
  19962. }
  19963. splineThru( pts /*Array of Vector*/ ) {
  19964. const npts = [ this.currentPoint.clone() ].concat( pts );
  19965. const curve = new SplineCurve( npts );
  19966. this.curves.push( curve );
  19967. this.currentPoint.copy( pts[ pts.length - 1 ] );
  19968. return this;
  19969. }
  19970. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19971. const x0 = this.currentPoint.x;
  19972. const y0 = this.currentPoint.y;
  19973. this.absarc( aX + x0, aY + y0, aRadius,
  19974. aStartAngle, aEndAngle, aClockwise );
  19975. return this;
  19976. }
  19977. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19978. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  19979. return this;
  19980. }
  19981. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19982. const x0 = this.currentPoint.x;
  19983. const y0 = this.currentPoint.y;
  19984. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19985. return this;
  19986. }
  19987. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19988. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19989. if ( this.curves.length > 0 ) {
  19990. // if a previous curve is present, attempt to join
  19991. const firstPoint = curve.getPoint( 0 );
  19992. if ( ! firstPoint.equals( this.currentPoint ) ) {
  19993. this.lineTo( firstPoint.x, firstPoint.y );
  19994. }
  19995. }
  19996. this.curves.push( curve );
  19997. const lastPoint = curve.getPoint( 1 );
  19998. this.currentPoint.copy( lastPoint );
  19999. return this;
  20000. }
  20001. copy( source ) {
  20002. super.copy( source );
  20003. this.currentPoint.copy( source.currentPoint );
  20004. return this;
  20005. }
  20006. toJSON() {
  20007. const data = super.toJSON();
  20008. data.currentPoint = this.currentPoint.toArray();
  20009. return data;
  20010. }
  20011. fromJSON( json ) {
  20012. super.fromJSON( json );
  20013. this.currentPoint.fromArray( json.currentPoint );
  20014. return this;
  20015. }
  20016. }
  20017. class LatheGeometry extends BufferGeometry {
  20018. 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 ) {
  20019. super();
  20020. this.type = 'LatheGeometry';
  20021. this.parameters = {
  20022. points: points,
  20023. segments: segments,
  20024. phiStart: phiStart,
  20025. phiLength: phiLength
  20026. };
  20027. segments = Math.floor( segments );
  20028. // clamp phiLength so it's in range of [ 0, 2PI ]
  20029. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  20030. // buffers
  20031. const indices = [];
  20032. const vertices = [];
  20033. const uvs = [];
  20034. const initNormals = [];
  20035. const normals = [];
  20036. // helper variables
  20037. const inverseSegments = 1.0 / segments;
  20038. const vertex = new Vector3();
  20039. const uv = new Vector2();
  20040. const normal = new Vector3();
  20041. const curNormal = new Vector3();
  20042. const prevNormal = new Vector3();
  20043. let dx = 0;
  20044. let dy = 0;
  20045. // pre-compute normals for initial "meridian"
  20046. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  20047. switch ( j ) {
  20048. case 0: // special handling for 1st vertex on path
  20049. dx = points[ j + 1 ].x - points[ j ].x;
  20050. dy = points[ j + 1 ].y - points[ j ].y;
  20051. normal.x = dy * 1.0;
  20052. normal.y = - dx;
  20053. normal.z = dy * 0.0;
  20054. prevNormal.copy( normal );
  20055. normal.normalize();
  20056. initNormals.push( normal.x, normal.y, normal.z );
  20057. break;
  20058. case ( points.length - 1 ): // special handling for last Vertex on path
  20059. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  20060. break;
  20061. default: // default handling for all vertices in between
  20062. dx = points[ j + 1 ].x - points[ j ].x;
  20063. dy = points[ j + 1 ].y - points[ j ].y;
  20064. normal.x = dy * 1.0;
  20065. normal.y = - dx;
  20066. normal.z = dy * 0.0;
  20067. curNormal.copy( normal );
  20068. normal.x += prevNormal.x;
  20069. normal.y += prevNormal.y;
  20070. normal.z += prevNormal.z;
  20071. normal.normalize();
  20072. initNormals.push( normal.x, normal.y, normal.z );
  20073. prevNormal.copy( curNormal );
  20074. }
  20075. }
  20076. // generate vertices, uvs and normals
  20077. for ( let i = 0; i <= segments; i ++ ) {
  20078. const phi = phiStart + i * inverseSegments * phiLength;
  20079. const sin = Math.sin( phi );
  20080. const cos = Math.cos( phi );
  20081. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  20082. // vertex
  20083. vertex.x = points[ j ].x * sin;
  20084. vertex.y = points[ j ].y;
  20085. vertex.z = points[ j ].x * cos;
  20086. vertices.push( vertex.x, vertex.y, vertex.z );
  20087. // uv
  20088. uv.x = i / segments;
  20089. uv.y = j / ( points.length - 1 );
  20090. uvs.push( uv.x, uv.y );
  20091. // normal
  20092. const x = initNormals[ 3 * j + 0 ] * sin;
  20093. const y = initNormals[ 3 * j + 1 ];
  20094. const z = initNormals[ 3 * j + 0 ] * cos;
  20095. normals.push( x, y, z );
  20096. }
  20097. }
  20098. // indices
  20099. for ( let i = 0; i < segments; i ++ ) {
  20100. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  20101. const base = j + i * points.length;
  20102. const a = base;
  20103. const b = base + points.length;
  20104. const c = base + points.length + 1;
  20105. const d = base + 1;
  20106. // faces
  20107. indices.push( a, b, d );
  20108. indices.push( c, d, b );
  20109. }
  20110. }
  20111. // build geometry
  20112. this.setIndex( indices );
  20113. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20114. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20115. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20116. }
  20117. copy( source ) {
  20118. super.copy( source );
  20119. this.parameters = Object.assign( {}, source.parameters );
  20120. return this;
  20121. }
  20122. static fromJSON( data ) {
  20123. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  20124. }
  20125. }
  20126. class CapsuleGeometry extends LatheGeometry {
  20127. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  20128. const path = new Path();
  20129. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  20130. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  20131. super( path.getPoints( capSegments ), radialSegments );
  20132. this.type = 'CapsuleGeometry';
  20133. this.parameters = {
  20134. radius: radius,
  20135. height: length,
  20136. capSegments: capSegments,
  20137. radialSegments: radialSegments,
  20138. };
  20139. }
  20140. static fromJSON( data ) {
  20141. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  20142. }
  20143. }
  20144. class CircleGeometry extends BufferGeometry {
  20145. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20146. super();
  20147. this.type = 'CircleGeometry';
  20148. this.parameters = {
  20149. radius: radius,
  20150. segments: segments,
  20151. thetaStart: thetaStart,
  20152. thetaLength: thetaLength
  20153. };
  20154. segments = Math.max( 3, segments );
  20155. // buffers
  20156. const indices = [];
  20157. const vertices = [];
  20158. const normals = [];
  20159. const uvs = [];
  20160. // helper variables
  20161. const vertex = new Vector3();
  20162. const uv = new Vector2();
  20163. // center point
  20164. vertices.push( 0, 0, 0 );
  20165. normals.push( 0, 0, 1 );
  20166. uvs.push( 0.5, 0.5 );
  20167. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  20168. const segment = thetaStart + s / segments * thetaLength;
  20169. // vertex
  20170. vertex.x = radius * Math.cos( segment );
  20171. vertex.y = radius * Math.sin( segment );
  20172. vertices.push( vertex.x, vertex.y, vertex.z );
  20173. // normal
  20174. normals.push( 0, 0, 1 );
  20175. // uvs
  20176. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  20177. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  20178. uvs.push( uv.x, uv.y );
  20179. }
  20180. // indices
  20181. for ( let i = 1; i <= segments; i ++ ) {
  20182. indices.push( i, i + 1, 0 );
  20183. }
  20184. // build geometry
  20185. this.setIndex( indices );
  20186. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20187. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20188. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20189. }
  20190. copy( source ) {
  20191. super.copy( source );
  20192. this.parameters = Object.assign( {}, source.parameters );
  20193. return this;
  20194. }
  20195. static fromJSON( data ) {
  20196. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  20197. }
  20198. }
  20199. class CylinderGeometry extends BufferGeometry {
  20200. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20201. super();
  20202. this.type = 'CylinderGeometry';
  20203. this.parameters = {
  20204. radiusTop: radiusTop,
  20205. radiusBottom: radiusBottom,
  20206. height: height,
  20207. radialSegments: radialSegments,
  20208. heightSegments: heightSegments,
  20209. openEnded: openEnded,
  20210. thetaStart: thetaStart,
  20211. thetaLength: thetaLength
  20212. };
  20213. const scope = this;
  20214. radialSegments = Math.floor( radialSegments );
  20215. heightSegments = Math.floor( heightSegments );
  20216. // buffers
  20217. const indices = [];
  20218. const vertices = [];
  20219. const normals = [];
  20220. const uvs = [];
  20221. // helper variables
  20222. let index = 0;
  20223. const indexArray = [];
  20224. const halfHeight = height / 2;
  20225. let groupStart = 0;
  20226. // generate geometry
  20227. generateTorso();
  20228. if ( openEnded === false ) {
  20229. if ( radiusTop > 0 ) generateCap( true );
  20230. if ( radiusBottom > 0 ) generateCap( false );
  20231. }
  20232. // build geometry
  20233. this.setIndex( indices );
  20234. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20235. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20236. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20237. function generateTorso() {
  20238. const normal = new Vector3();
  20239. const vertex = new Vector3();
  20240. let groupCount = 0;
  20241. // this will be used to calculate the normal
  20242. const slope = ( radiusBottom - radiusTop ) / height;
  20243. // generate vertices, normals and uvs
  20244. for ( let y = 0; y <= heightSegments; y ++ ) {
  20245. const indexRow = [];
  20246. const v = y / heightSegments;
  20247. // calculate the radius of the current row
  20248. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  20249. for ( let x = 0; x <= radialSegments; x ++ ) {
  20250. const u = x / radialSegments;
  20251. const theta = u * thetaLength + thetaStart;
  20252. const sinTheta = Math.sin( theta );
  20253. const cosTheta = Math.cos( theta );
  20254. // vertex
  20255. vertex.x = radius * sinTheta;
  20256. vertex.y = - v * height + halfHeight;
  20257. vertex.z = radius * cosTheta;
  20258. vertices.push( vertex.x, vertex.y, vertex.z );
  20259. // normal
  20260. normal.set( sinTheta, slope, cosTheta ).normalize();
  20261. normals.push( normal.x, normal.y, normal.z );
  20262. // uv
  20263. uvs.push( u, 1 - v );
  20264. // save index of vertex in respective row
  20265. indexRow.push( index ++ );
  20266. }
  20267. // now save vertices of the row in our index array
  20268. indexArray.push( indexRow );
  20269. }
  20270. // generate indices
  20271. for ( let x = 0; x < radialSegments; x ++ ) {
  20272. for ( let y = 0; y < heightSegments; y ++ ) {
  20273. // we use the index array to access the correct indices
  20274. const a = indexArray[ y ][ x ];
  20275. const b = indexArray[ y + 1 ][ x ];
  20276. const c = indexArray[ y + 1 ][ x + 1 ];
  20277. const d = indexArray[ y ][ x + 1 ];
  20278. // faces
  20279. indices.push( a, b, d );
  20280. indices.push( b, c, d );
  20281. // update group counter
  20282. groupCount += 6;
  20283. }
  20284. }
  20285. // add a group to the geometry. this will ensure multi material support
  20286. scope.addGroup( groupStart, groupCount, 0 );
  20287. // calculate new start value for groups
  20288. groupStart += groupCount;
  20289. }
  20290. function generateCap( top ) {
  20291. // save the index of the first center vertex
  20292. const centerIndexStart = index;
  20293. const uv = new Vector2();
  20294. const vertex = new Vector3();
  20295. let groupCount = 0;
  20296. const radius = ( top === true ) ? radiusTop : radiusBottom;
  20297. const sign = ( top === true ) ? 1 : - 1;
  20298. // first we generate the center vertex data of the cap.
  20299. // because the geometry needs one set of uvs per face,
  20300. // we must generate a center vertex per face/segment
  20301. for ( let x = 1; x <= radialSegments; x ++ ) {
  20302. // vertex
  20303. vertices.push( 0, halfHeight * sign, 0 );
  20304. // normal
  20305. normals.push( 0, sign, 0 );
  20306. // uv
  20307. uvs.push( 0.5, 0.5 );
  20308. // increase index
  20309. index ++;
  20310. }
  20311. // save the index of the last center vertex
  20312. const centerIndexEnd = index;
  20313. // now we generate the surrounding vertices, normals and uvs
  20314. for ( let x = 0; x <= radialSegments; x ++ ) {
  20315. const u = x / radialSegments;
  20316. const theta = u * thetaLength + thetaStart;
  20317. const cosTheta = Math.cos( theta );
  20318. const sinTheta = Math.sin( theta );
  20319. // vertex
  20320. vertex.x = radius * sinTheta;
  20321. vertex.y = halfHeight * sign;
  20322. vertex.z = radius * cosTheta;
  20323. vertices.push( vertex.x, vertex.y, vertex.z );
  20324. // normal
  20325. normals.push( 0, sign, 0 );
  20326. // uv
  20327. uv.x = ( cosTheta * 0.5 ) + 0.5;
  20328. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  20329. uvs.push( uv.x, uv.y );
  20330. // increase index
  20331. index ++;
  20332. }
  20333. // generate indices
  20334. for ( let x = 0; x < radialSegments; x ++ ) {
  20335. const c = centerIndexStart + x;
  20336. const i = centerIndexEnd + x;
  20337. if ( top === true ) {
  20338. // face top
  20339. indices.push( i, i + 1, c );
  20340. } else {
  20341. // face bottom
  20342. indices.push( i + 1, i, c );
  20343. }
  20344. groupCount += 3;
  20345. }
  20346. // add a group to the geometry. this will ensure multi material support
  20347. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  20348. // calculate new start value for groups
  20349. groupStart += groupCount;
  20350. }
  20351. }
  20352. copy( source ) {
  20353. super.copy( source );
  20354. this.parameters = Object.assign( {}, source.parameters );
  20355. return this;
  20356. }
  20357. static fromJSON( data ) {
  20358. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  20359. }
  20360. }
  20361. class ConeGeometry extends CylinderGeometry {
  20362. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  20363. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  20364. this.type = 'ConeGeometry';
  20365. this.parameters = {
  20366. radius: radius,
  20367. height: height,
  20368. radialSegments: radialSegments,
  20369. heightSegments: heightSegments,
  20370. openEnded: openEnded,
  20371. thetaStart: thetaStart,
  20372. thetaLength: thetaLength
  20373. };
  20374. }
  20375. static fromJSON( data ) {
  20376. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  20377. }
  20378. }
  20379. class PolyhedronGeometry extends BufferGeometry {
  20380. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  20381. super();
  20382. this.type = 'PolyhedronGeometry';
  20383. this.parameters = {
  20384. vertices: vertices,
  20385. indices: indices,
  20386. radius: radius,
  20387. detail: detail
  20388. };
  20389. // default buffer data
  20390. const vertexBuffer = [];
  20391. const uvBuffer = [];
  20392. // the subdivision creates the vertex buffer data
  20393. subdivide( detail );
  20394. // all vertices should lie on a conceptual sphere with a given radius
  20395. applyRadius( radius );
  20396. // finally, create the uv data
  20397. generateUVs();
  20398. // build non-indexed geometry
  20399. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  20400. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  20401. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  20402. if ( detail === 0 ) {
  20403. this.computeVertexNormals(); // flat normals
  20404. } else {
  20405. this.normalizeNormals(); // smooth normals
  20406. }
  20407. // helper functions
  20408. function subdivide( detail ) {
  20409. const a = new Vector3();
  20410. const b = new Vector3();
  20411. const c = new Vector3();
  20412. // iterate over all faces and apply a subdivision with the given detail value
  20413. for ( let i = 0; i < indices.length; i += 3 ) {
  20414. // get the vertices of the face
  20415. getVertexByIndex( indices[ i + 0 ], a );
  20416. getVertexByIndex( indices[ i + 1 ], b );
  20417. getVertexByIndex( indices[ i + 2 ], c );
  20418. // perform subdivision
  20419. subdivideFace( a, b, c, detail );
  20420. }
  20421. }
  20422. function subdivideFace( a, b, c, detail ) {
  20423. const cols = detail + 1;
  20424. // we use this multidimensional array as a data structure for creating the subdivision
  20425. const v = [];
  20426. // construct all of the vertices for this subdivision
  20427. for ( let i = 0; i <= cols; i ++ ) {
  20428. v[ i ] = [];
  20429. const aj = a.clone().lerp( c, i / cols );
  20430. const bj = b.clone().lerp( c, i / cols );
  20431. const rows = cols - i;
  20432. for ( let j = 0; j <= rows; j ++ ) {
  20433. if ( j === 0 && i === cols ) {
  20434. v[ i ][ j ] = aj;
  20435. } else {
  20436. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  20437. }
  20438. }
  20439. }
  20440. // construct all of the faces
  20441. for ( let i = 0; i < cols; i ++ ) {
  20442. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  20443. const k = Math.floor( j / 2 );
  20444. if ( j % 2 === 0 ) {
  20445. pushVertex( v[ i ][ k + 1 ] );
  20446. pushVertex( v[ i + 1 ][ k ] );
  20447. pushVertex( v[ i ][ k ] );
  20448. } else {
  20449. pushVertex( v[ i ][ k + 1 ] );
  20450. pushVertex( v[ i + 1 ][ k + 1 ] );
  20451. pushVertex( v[ i + 1 ][ k ] );
  20452. }
  20453. }
  20454. }
  20455. }
  20456. function applyRadius( radius ) {
  20457. const vertex = new Vector3();
  20458. // iterate over the entire buffer and apply the radius to each vertex
  20459. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  20460. vertex.x = vertexBuffer[ i + 0 ];
  20461. vertex.y = vertexBuffer[ i + 1 ];
  20462. vertex.z = vertexBuffer[ i + 2 ];
  20463. vertex.normalize().multiplyScalar( radius );
  20464. vertexBuffer[ i + 0 ] = vertex.x;
  20465. vertexBuffer[ i + 1 ] = vertex.y;
  20466. vertexBuffer[ i + 2 ] = vertex.z;
  20467. }
  20468. }
  20469. function generateUVs() {
  20470. const vertex = new Vector3();
  20471. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  20472. vertex.x = vertexBuffer[ i + 0 ];
  20473. vertex.y = vertexBuffer[ i + 1 ];
  20474. vertex.z = vertexBuffer[ i + 2 ];
  20475. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  20476. const v = inclination( vertex ) / Math.PI + 0.5;
  20477. uvBuffer.push( u, 1 - v );
  20478. }
  20479. correctUVs();
  20480. correctSeam();
  20481. }
  20482. function correctSeam() {
  20483. // handle case when face straddles the seam, see #3269
  20484. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  20485. // uv data of a single face
  20486. const x0 = uvBuffer[ i + 0 ];
  20487. const x1 = uvBuffer[ i + 2 ];
  20488. const x2 = uvBuffer[ i + 4 ];
  20489. const max = Math.max( x0, x1, x2 );
  20490. const min = Math.min( x0, x1, x2 );
  20491. // 0.9 is somewhat arbitrary
  20492. if ( max > 0.9 && min < 0.1 ) {
  20493. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  20494. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  20495. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  20496. }
  20497. }
  20498. }
  20499. function pushVertex( vertex ) {
  20500. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  20501. }
  20502. function getVertexByIndex( index, vertex ) {
  20503. const stride = index * 3;
  20504. vertex.x = vertices[ stride + 0 ];
  20505. vertex.y = vertices[ stride + 1 ];
  20506. vertex.z = vertices[ stride + 2 ];
  20507. }
  20508. function correctUVs() {
  20509. const a = new Vector3();
  20510. const b = new Vector3();
  20511. const c = new Vector3();
  20512. const centroid = new Vector3();
  20513. const uvA = new Vector2();
  20514. const uvB = new Vector2();
  20515. const uvC = new Vector2();
  20516. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  20517. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  20518. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  20519. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  20520. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  20521. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  20522. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  20523. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  20524. const azi = azimuth( centroid );
  20525. correctUV( uvA, j + 0, a, azi );
  20526. correctUV( uvB, j + 2, b, azi );
  20527. correctUV( uvC, j + 4, c, azi );
  20528. }
  20529. }
  20530. function correctUV( uv, stride, vector, azimuth ) {
  20531. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  20532. uvBuffer[ stride ] = uv.x - 1;
  20533. }
  20534. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  20535. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  20536. }
  20537. }
  20538. // Angle around the Y axis, counter-clockwise when looking from above.
  20539. function azimuth( vector ) {
  20540. return Math.atan2( vector.z, - vector.x );
  20541. }
  20542. // Angle above the XZ plane.
  20543. function inclination( vector ) {
  20544. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20545. }
  20546. }
  20547. copy( source ) {
  20548. super.copy( source );
  20549. this.parameters = Object.assign( {}, source.parameters );
  20550. return this;
  20551. }
  20552. static fromJSON( data ) {
  20553. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  20554. }
  20555. }
  20556. class DodecahedronGeometry extends PolyhedronGeometry {
  20557. constructor( radius = 1, detail = 0 ) {
  20558. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20559. const r = 1 / t;
  20560. const vertices = [
  20561. // (±1, ±1, ±1)
  20562. - 1, - 1, - 1, - 1, - 1, 1,
  20563. - 1, 1, - 1, - 1, 1, 1,
  20564. 1, - 1, - 1, 1, - 1, 1,
  20565. 1, 1, - 1, 1, 1, 1,
  20566. // (0, ±1/φ, ±φ)
  20567. 0, - r, - t, 0, - r, t,
  20568. 0, r, - t, 0, r, t,
  20569. // (±1/φ, ±φ, 0)
  20570. - r, - t, 0, - r, t, 0,
  20571. r, - t, 0, r, t, 0,
  20572. // (±φ, 0, ±1/φ)
  20573. - t, 0, - r, t, 0, - r,
  20574. - t, 0, r, t, 0, r
  20575. ];
  20576. const indices = [
  20577. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  20578. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  20579. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  20580. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  20581. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  20582. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  20583. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  20584. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  20585. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  20586. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  20587. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  20588. 1, 12, 14, 1, 14, 5, 1, 5, 9
  20589. ];
  20590. super( vertices, indices, radius, detail );
  20591. this.type = 'DodecahedronGeometry';
  20592. this.parameters = {
  20593. radius: radius,
  20594. detail: detail
  20595. };
  20596. }
  20597. static fromJSON( data ) {
  20598. return new DodecahedronGeometry( data.radius, data.detail );
  20599. }
  20600. }
  20601. const _v0 = /*@__PURE__*/ new Vector3();
  20602. const _v1$1 = /*@__PURE__*/ new Vector3();
  20603. const _normal = /*@__PURE__*/ new Vector3();
  20604. const _triangle = /*@__PURE__*/ new Triangle();
  20605. class EdgesGeometry extends BufferGeometry {
  20606. constructor( geometry = null, thresholdAngle = 1 ) {
  20607. super();
  20608. this.type = 'EdgesGeometry';
  20609. this.parameters = {
  20610. geometry: geometry,
  20611. thresholdAngle: thresholdAngle
  20612. };
  20613. if ( geometry !== null ) {
  20614. const precisionPoints = 4;
  20615. const precision = Math.pow( 10, precisionPoints );
  20616. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  20617. const indexAttr = geometry.getIndex();
  20618. const positionAttr = geometry.getAttribute( 'position' );
  20619. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  20620. const indexArr = [ 0, 0, 0 ];
  20621. const vertKeys = [ 'a', 'b', 'c' ];
  20622. const hashes = new Array( 3 );
  20623. const edgeData = {};
  20624. const vertices = [];
  20625. for ( let i = 0; i < indexCount; i += 3 ) {
  20626. if ( indexAttr ) {
  20627. indexArr[ 0 ] = indexAttr.getX( i );
  20628. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  20629. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  20630. } else {
  20631. indexArr[ 0 ] = i;
  20632. indexArr[ 1 ] = i + 1;
  20633. indexArr[ 2 ] = i + 2;
  20634. }
  20635. const { a, b, c } = _triangle;
  20636. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  20637. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  20638. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  20639. _triangle.getNormal( _normal );
  20640. // create hashes for the edge from the vertices
  20641. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  20642. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  20643. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  20644. // skip degenerate triangles
  20645. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  20646. continue;
  20647. }
  20648. // iterate over every edge
  20649. for ( let j = 0; j < 3; j ++ ) {
  20650. // get the first and next vertex making up the edge
  20651. const jNext = ( j + 1 ) % 3;
  20652. const vecHash0 = hashes[ j ];
  20653. const vecHash1 = hashes[ jNext ];
  20654. const v0 = _triangle[ vertKeys[ j ] ];
  20655. const v1 = _triangle[ vertKeys[ jNext ] ];
  20656. const hash = `${ vecHash0 }_${ vecHash1 }`;
  20657. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  20658. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  20659. // if we found a sibling edge add it into the vertex array if
  20660. // it meets the angle threshold and delete the edge from the map.
  20661. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  20662. vertices.push( v0.x, v0.y, v0.z );
  20663. vertices.push( v1.x, v1.y, v1.z );
  20664. }
  20665. edgeData[ reverseHash ] = null;
  20666. } else if ( ! ( hash in edgeData ) ) {
  20667. // if we've already got an edge here then skip adding a new one
  20668. edgeData[ hash ] = {
  20669. index0: indexArr[ j ],
  20670. index1: indexArr[ jNext ],
  20671. normal: _normal.clone(),
  20672. };
  20673. }
  20674. }
  20675. }
  20676. // iterate over all remaining, unmatched edges and add them to the vertex array
  20677. for ( const key in edgeData ) {
  20678. if ( edgeData[ key ] ) {
  20679. const { index0, index1 } = edgeData[ key ];
  20680. _v0.fromBufferAttribute( positionAttr, index0 );
  20681. _v1$1.fromBufferAttribute( positionAttr, index1 );
  20682. vertices.push( _v0.x, _v0.y, _v0.z );
  20683. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  20684. }
  20685. }
  20686. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20687. }
  20688. }
  20689. copy( source ) {
  20690. super.copy( source );
  20691. this.parameters = Object.assign( {}, source.parameters );
  20692. return this;
  20693. }
  20694. }
  20695. class Shape extends Path {
  20696. constructor( points ) {
  20697. super( points );
  20698. this.uuid = generateUUID();
  20699. this.type = 'Shape';
  20700. this.holes = [];
  20701. }
  20702. getPointsHoles( divisions ) {
  20703. const holesPts = [];
  20704. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20705. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  20706. }
  20707. return holesPts;
  20708. }
  20709. // get points of shape and holes (keypoints based on segments parameter)
  20710. extractPoints( divisions ) {
  20711. return {
  20712. shape: this.getPoints( divisions ),
  20713. holes: this.getPointsHoles( divisions )
  20714. };
  20715. }
  20716. copy( source ) {
  20717. super.copy( source );
  20718. this.holes = [];
  20719. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  20720. const hole = source.holes[ i ];
  20721. this.holes.push( hole.clone() );
  20722. }
  20723. return this;
  20724. }
  20725. toJSON() {
  20726. const data = super.toJSON();
  20727. data.uuid = this.uuid;
  20728. data.holes = [];
  20729. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20730. const hole = this.holes[ i ];
  20731. data.holes.push( hole.toJSON() );
  20732. }
  20733. return data;
  20734. }
  20735. fromJSON( json ) {
  20736. super.fromJSON( json );
  20737. this.uuid = json.uuid;
  20738. this.holes = [];
  20739. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  20740. const hole = json.holes[ i ];
  20741. this.holes.push( new Path().fromJSON( hole ) );
  20742. }
  20743. return this;
  20744. }
  20745. }
  20746. /**
  20747. * Port from https://github.com/mapbox/earcut (v2.2.4)
  20748. */
  20749. const Earcut = {
  20750. triangulate: function ( data, holeIndices, dim = 2 ) {
  20751. const hasHoles = holeIndices && holeIndices.length;
  20752. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  20753. let outerNode = linkedList( data, 0, outerLen, dim, true );
  20754. const triangles = [];
  20755. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  20756. let minX, minY, maxX, maxY, x, y, invSize;
  20757. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  20758. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  20759. if ( data.length > 80 * dim ) {
  20760. minX = maxX = data[ 0 ];
  20761. minY = maxY = data[ 1 ];
  20762. for ( let i = dim; i < outerLen; i += dim ) {
  20763. x = data[ i ];
  20764. y = data[ i + 1 ];
  20765. if ( x < minX ) minX = x;
  20766. if ( y < minY ) minY = y;
  20767. if ( x > maxX ) maxX = x;
  20768. if ( y > maxY ) maxY = y;
  20769. }
  20770. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  20771. invSize = Math.max( maxX - minX, maxY - minY );
  20772. invSize = invSize !== 0 ? 32767 / invSize : 0;
  20773. }
  20774. earcutLinked( outerNode, triangles, dim, minX, minY, invSize, 0 );
  20775. return triangles;
  20776. }
  20777. };
  20778. // create a circular doubly linked list from polygon points in the specified winding order
  20779. function linkedList( data, start, end, dim, clockwise ) {
  20780. let i, last;
  20781. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  20782. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20783. } else {
  20784. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20785. }
  20786. if ( last && equals( last, last.next ) ) {
  20787. removeNode( last );
  20788. last = last.next;
  20789. }
  20790. return last;
  20791. }
  20792. // eliminate colinear or duplicate points
  20793. function filterPoints( start, end ) {
  20794. if ( ! start ) return start;
  20795. if ( ! end ) end = start;
  20796. let p = start,
  20797. again;
  20798. do {
  20799. again = false;
  20800. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  20801. removeNode( p );
  20802. p = end = p.prev;
  20803. if ( p === p.next ) break;
  20804. again = true;
  20805. } else {
  20806. p = p.next;
  20807. }
  20808. } while ( again || p !== end );
  20809. return end;
  20810. }
  20811. // main ear slicing loop which triangulates a polygon (given as a linked list)
  20812. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  20813. if ( ! ear ) return;
  20814. // interlink polygon nodes in z-order
  20815. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  20816. let stop = ear,
  20817. prev, next;
  20818. // iterate through ears, slicing them one by one
  20819. while ( ear.prev !== ear.next ) {
  20820. prev = ear.prev;
  20821. next = ear.next;
  20822. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  20823. // cut off the triangle
  20824. triangles.push( prev.i / dim | 0 );
  20825. triangles.push( ear.i / dim | 0 );
  20826. triangles.push( next.i / dim | 0 );
  20827. removeNode( ear );
  20828. // skipping the next vertex leads to less sliver triangles
  20829. ear = next.next;
  20830. stop = next.next;
  20831. continue;
  20832. }
  20833. ear = next;
  20834. // if we looped through the whole remaining polygon and can't find any more ears
  20835. if ( ear === stop ) {
  20836. // try filtering points and slicing again
  20837. if ( ! pass ) {
  20838. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  20839. // if this didn't work, try curing all small self-intersections locally
  20840. } else if ( pass === 1 ) {
  20841. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  20842. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  20843. // as a last resort, try splitting the remaining polygon into two
  20844. } else if ( pass === 2 ) {
  20845. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  20846. }
  20847. break;
  20848. }
  20849. }
  20850. }
  20851. // check whether a polygon node forms a valid ear with adjacent nodes
  20852. function isEar( ear ) {
  20853. const a = ear.prev,
  20854. b = ear,
  20855. c = ear.next;
  20856. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20857. // now make sure we don't have other points inside the potential ear
  20858. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  20859. // triangle bbox; min & max are calculated like this for speed
  20860. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  20861. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  20862. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  20863. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  20864. let p = c.next;
  20865. while ( p !== a ) {
  20866. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  20867. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) &&
  20868. area( p.prev, p, p.next ) >= 0 ) return false;
  20869. p = p.next;
  20870. }
  20871. return true;
  20872. }
  20873. function isEarHashed( ear, minX, minY, invSize ) {
  20874. const a = ear.prev,
  20875. b = ear,
  20876. c = ear.next;
  20877. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20878. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  20879. // triangle bbox; min & max are calculated like this for speed
  20880. const x0 = ax < bx ? ( ax < cx ? ax : cx ) : ( bx < cx ? bx : cx ),
  20881. y0 = ay < by ? ( ay < cy ? ay : cy ) : ( by < cy ? by : cy ),
  20882. x1 = ax > bx ? ( ax > cx ? ax : cx ) : ( bx > cx ? bx : cx ),
  20883. y1 = ay > by ? ( ay > cy ? ay : cy ) : ( by > cy ? by : cy );
  20884. // z-order range for the current triangle bbox;
  20885. const minZ = zOrder( x0, y0, minX, minY, invSize ),
  20886. maxZ = zOrder( x1, y1, minX, minY, invSize );
  20887. let p = ear.prevZ,
  20888. n = ear.nextZ;
  20889. // look for points inside the triangle in both directions
  20890. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  20891. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  20892. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  20893. p = p.prevZ;
  20894. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  20895. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  20896. n = n.nextZ;
  20897. }
  20898. // look for remaining points in decreasing z-order
  20899. while ( p && p.z >= minZ ) {
  20900. if ( p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  20901. pointInTriangle( ax, ay, bx, by, cx, cy, p.x, p.y ) && area( p.prev, p, p.next ) >= 0 ) return false;
  20902. p = p.prevZ;
  20903. }
  20904. // look for remaining points in increasing z-order
  20905. while ( n && n.z <= maxZ ) {
  20906. if ( n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  20907. pointInTriangle( ax, ay, bx, by, cx, cy, n.x, n.y ) && area( n.prev, n, n.next ) >= 0 ) return false;
  20908. n = n.nextZ;
  20909. }
  20910. return true;
  20911. }
  20912. // go through all polygon nodes and cure small local self-intersections
  20913. function cureLocalIntersections( start, triangles, dim ) {
  20914. let p = start;
  20915. do {
  20916. const a = p.prev,
  20917. b = p.next.next;
  20918. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  20919. triangles.push( a.i / dim | 0 );
  20920. triangles.push( p.i / dim | 0 );
  20921. triangles.push( b.i / dim | 0 );
  20922. // remove two nodes involved
  20923. removeNode( p );
  20924. removeNode( p.next );
  20925. p = start = b;
  20926. }
  20927. p = p.next;
  20928. } while ( p !== start );
  20929. return filterPoints( p );
  20930. }
  20931. // try splitting polygon into two and triangulate them independently
  20932. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  20933. // look for a valid diagonal that divides the polygon into two
  20934. let a = start;
  20935. do {
  20936. let b = a.next.next;
  20937. while ( b !== a.prev ) {
  20938. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  20939. // split the polygon in two by the diagonal
  20940. let c = splitPolygon( a, b );
  20941. // filter colinear points around the cuts
  20942. a = filterPoints( a, a.next );
  20943. c = filterPoints( c, c.next );
  20944. // run earcut on each half
  20945. earcutLinked( a, triangles, dim, minX, minY, invSize, 0 );
  20946. earcutLinked( c, triangles, dim, minX, minY, invSize, 0 );
  20947. return;
  20948. }
  20949. b = b.next;
  20950. }
  20951. a = a.next;
  20952. } while ( a !== start );
  20953. }
  20954. // link every hole into the outer loop, producing a single-ring polygon without holes
  20955. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  20956. const queue = [];
  20957. let i, len, start, end, list;
  20958. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  20959. start = holeIndices[ i ] * dim;
  20960. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  20961. list = linkedList( data, start, end, dim, false );
  20962. if ( list === list.next ) list.steiner = true;
  20963. queue.push( getLeftmost( list ) );
  20964. }
  20965. queue.sort( compareX );
  20966. // process holes from left to right
  20967. for ( i = 0; i < queue.length; i ++ ) {
  20968. outerNode = eliminateHole( queue[ i ], outerNode );
  20969. }
  20970. return outerNode;
  20971. }
  20972. function compareX( a, b ) {
  20973. return a.x - b.x;
  20974. }
  20975. // find a bridge between vertices that connects hole with an outer ring and link it
  20976. function eliminateHole( hole, outerNode ) {
  20977. const bridge = findHoleBridge( hole, outerNode );
  20978. if ( ! bridge ) {
  20979. return outerNode;
  20980. }
  20981. const bridgeReverse = splitPolygon( bridge, hole );
  20982. // filter collinear points around the cuts
  20983. filterPoints( bridgeReverse, bridgeReverse.next );
  20984. return filterPoints( bridge, bridge.next );
  20985. }
  20986. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  20987. function findHoleBridge( hole, outerNode ) {
  20988. let p = outerNode,
  20989. qx = - Infinity,
  20990. m;
  20991. const hx = hole.x, hy = hole.y;
  20992. // find a segment intersected by a ray from the hole's leftmost point to the left;
  20993. // segment's endpoint with lesser x will be potential connection point
  20994. do {
  20995. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  20996. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  20997. if ( x <= hx && x > qx ) {
  20998. qx = x;
  20999. m = p.x < p.next.x ? p : p.next;
  21000. if ( x === hx ) return m; // hole touches outer segment; pick leftmost endpoint
  21001. }
  21002. }
  21003. p = p.next;
  21004. } while ( p !== outerNode );
  21005. if ( ! m ) return null;
  21006. // look for points inside the triangle of hole point, segment intersection and endpoint;
  21007. // if there are no points found, we have a valid connection;
  21008. // otherwise choose the point of the minimum angle with the ray as connection point
  21009. const stop = m,
  21010. mx = m.x,
  21011. my = m.y;
  21012. let tanMin = Infinity, tan;
  21013. p = m;
  21014. do {
  21015. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  21016. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  21017. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  21018. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  21019. m = p;
  21020. tanMin = tan;
  21021. }
  21022. }
  21023. p = p.next;
  21024. } while ( p !== stop );
  21025. return m;
  21026. }
  21027. // whether sector in vertex m contains sector in vertex p in the same coordinates
  21028. function sectorContainsSector( m, p ) {
  21029. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  21030. }
  21031. // interlink polygon nodes in z-order
  21032. function indexCurve( start, minX, minY, invSize ) {
  21033. let p = start;
  21034. do {
  21035. if ( p.z === 0 ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  21036. p.prevZ = p.prev;
  21037. p.nextZ = p.next;
  21038. p = p.next;
  21039. } while ( p !== start );
  21040. p.prevZ.nextZ = null;
  21041. p.prevZ = null;
  21042. sortLinked( p );
  21043. }
  21044. // Simon Tatham's linked list merge sort algorithm
  21045. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  21046. function sortLinked( list ) {
  21047. let i, p, q, e, tail, numMerges, pSize, qSize,
  21048. inSize = 1;
  21049. do {
  21050. p = list;
  21051. list = null;
  21052. tail = null;
  21053. numMerges = 0;
  21054. while ( p ) {
  21055. numMerges ++;
  21056. q = p;
  21057. pSize = 0;
  21058. for ( i = 0; i < inSize; i ++ ) {
  21059. pSize ++;
  21060. q = q.nextZ;
  21061. if ( ! q ) break;
  21062. }
  21063. qSize = inSize;
  21064. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  21065. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  21066. e = p;
  21067. p = p.nextZ;
  21068. pSize --;
  21069. } else {
  21070. e = q;
  21071. q = q.nextZ;
  21072. qSize --;
  21073. }
  21074. if ( tail ) tail.nextZ = e;
  21075. else list = e;
  21076. e.prevZ = tail;
  21077. tail = e;
  21078. }
  21079. p = q;
  21080. }
  21081. tail.nextZ = null;
  21082. inSize *= 2;
  21083. } while ( numMerges > 1 );
  21084. return list;
  21085. }
  21086. // z-order of a point given coords and inverse of the longer side of data bbox
  21087. function zOrder( x, y, minX, minY, invSize ) {
  21088. // coords are transformed into non-negative 15-bit integer range
  21089. x = ( x - minX ) * invSize | 0;
  21090. y = ( y - minY ) * invSize | 0;
  21091. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  21092. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  21093. x = ( x | ( x << 2 ) ) & 0x33333333;
  21094. x = ( x | ( x << 1 ) ) & 0x55555555;
  21095. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  21096. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  21097. y = ( y | ( y << 2 ) ) & 0x33333333;
  21098. y = ( y | ( y << 1 ) ) & 0x55555555;
  21099. return x | ( y << 1 );
  21100. }
  21101. // find the leftmost node of a polygon ring
  21102. function getLeftmost( start ) {
  21103. let p = start,
  21104. leftmost = start;
  21105. do {
  21106. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  21107. p = p.next;
  21108. } while ( p !== start );
  21109. return leftmost;
  21110. }
  21111. // check if a point lies within a convex triangle
  21112. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  21113. return ( cx - px ) * ( ay - py ) >= ( ax - px ) * ( cy - py ) &&
  21114. ( ax - px ) * ( by - py ) >= ( bx - px ) * ( ay - py ) &&
  21115. ( bx - px ) * ( cy - py ) >= ( cx - px ) * ( by - py );
  21116. }
  21117. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  21118. function isValidDiagonal( a, b ) {
  21119. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // dones't intersect other edges
  21120. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  21121. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  21122. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  21123. }
  21124. // signed area of a triangle
  21125. function area( p, q, r ) {
  21126. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  21127. }
  21128. // check if two points are equal
  21129. function equals( p1, p2 ) {
  21130. return p1.x === p2.x && p1.y === p2.y;
  21131. }
  21132. // check if two segments intersect
  21133. function intersects( p1, q1, p2, q2 ) {
  21134. const o1 = sign( area( p1, q1, p2 ) );
  21135. const o2 = sign( area( p1, q1, q2 ) );
  21136. const o3 = sign( area( p2, q2, p1 ) );
  21137. const o4 = sign( area( p2, q2, q1 ) );
  21138. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  21139. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  21140. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  21141. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  21142. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  21143. return false;
  21144. }
  21145. // for collinear points p, q, r, check if point q lies on segment pr
  21146. function onSegment( p, q, r ) {
  21147. 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 );
  21148. }
  21149. function sign( num ) {
  21150. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  21151. }
  21152. // check if a polygon diagonal intersects any polygon segments
  21153. function intersectsPolygon( a, b ) {
  21154. let p = a;
  21155. do {
  21156. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  21157. intersects( p, p.next, a, b ) ) return true;
  21158. p = p.next;
  21159. } while ( p !== a );
  21160. return false;
  21161. }
  21162. // check if a polygon diagonal is locally inside the polygon
  21163. function locallyInside( a, b ) {
  21164. return area( a.prev, a, a.next ) < 0 ?
  21165. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  21166. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  21167. }
  21168. // check if the middle point of a polygon diagonal is inside the polygon
  21169. function middleInside( a, b ) {
  21170. let p = a,
  21171. inside = false;
  21172. const px = ( a.x + b.x ) / 2,
  21173. py = ( a.y + b.y ) / 2;
  21174. do {
  21175. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  21176. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  21177. inside = ! inside;
  21178. p = p.next;
  21179. } while ( p !== a );
  21180. return inside;
  21181. }
  21182. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  21183. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  21184. function splitPolygon( a, b ) {
  21185. const a2 = new Node( a.i, a.x, a.y ),
  21186. b2 = new Node( b.i, b.x, b.y ),
  21187. an = a.next,
  21188. bp = b.prev;
  21189. a.next = b;
  21190. b.prev = a;
  21191. a2.next = an;
  21192. an.prev = a2;
  21193. b2.next = a2;
  21194. a2.prev = b2;
  21195. bp.next = b2;
  21196. b2.prev = bp;
  21197. return b2;
  21198. }
  21199. // create a node and optionally link it with previous one (in a circular doubly linked list)
  21200. function insertNode( i, x, y, last ) {
  21201. const p = new Node( i, x, y );
  21202. if ( ! last ) {
  21203. p.prev = p;
  21204. p.next = p;
  21205. } else {
  21206. p.next = last.next;
  21207. p.prev = last;
  21208. last.next.prev = p;
  21209. last.next = p;
  21210. }
  21211. return p;
  21212. }
  21213. function removeNode( p ) {
  21214. p.next.prev = p.prev;
  21215. p.prev.next = p.next;
  21216. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  21217. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  21218. }
  21219. function Node( i, x, y ) {
  21220. // vertex index in coordinates array
  21221. this.i = i;
  21222. // vertex coordinates
  21223. this.x = x;
  21224. this.y = y;
  21225. // previous and next vertex nodes in a polygon ring
  21226. this.prev = null;
  21227. this.next = null;
  21228. // z-order curve value
  21229. this.z = 0;
  21230. // previous and next nodes in z-order
  21231. this.prevZ = null;
  21232. this.nextZ = null;
  21233. // indicates whether this is a steiner point
  21234. this.steiner = false;
  21235. }
  21236. function signedArea( data, start, end, dim ) {
  21237. let sum = 0;
  21238. for ( let i = start, j = end - dim; i < end; i += dim ) {
  21239. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  21240. j = i;
  21241. }
  21242. return sum;
  21243. }
  21244. class ShapeUtils {
  21245. // calculate area of the contour polygon
  21246. static area( contour ) {
  21247. const n = contour.length;
  21248. let a = 0.0;
  21249. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  21250. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  21251. }
  21252. return a * 0.5;
  21253. }
  21254. static isClockWise( pts ) {
  21255. return ShapeUtils.area( pts ) < 0;
  21256. }
  21257. static triangulateShape( contour, holes ) {
  21258. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  21259. const holeIndices = []; // array of hole indices
  21260. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  21261. removeDupEndPts( contour );
  21262. addContour( vertices, contour );
  21263. //
  21264. let holeIndex = contour.length;
  21265. holes.forEach( removeDupEndPts );
  21266. for ( let i = 0; i < holes.length; i ++ ) {
  21267. holeIndices.push( holeIndex );
  21268. holeIndex += holes[ i ].length;
  21269. addContour( vertices, holes[ i ] );
  21270. }
  21271. //
  21272. const triangles = Earcut.triangulate( vertices, holeIndices );
  21273. //
  21274. for ( let i = 0; i < triangles.length; i += 3 ) {
  21275. faces.push( triangles.slice( i, i + 3 ) );
  21276. }
  21277. return faces;
  21278. }
  21279. }
  21280. function removeDupEndPts( points ) {
  21281. const l = points.length;
  21282. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  21283. points.pop();
  21284. }
  21285. }
  21286. function addContour( vertices, contour ) {
  21287. for ( let i = 0; i < contour.length; i ++ ) {
  21288. vertices.push( contour[ i ].x );
  21289. vertices.push( contour[ i ].y );
  21290. }
  21291. }
  21292. /**
  21293. * Creates extruded geometry from a path shape.
  21294. *
  21295. * parameters = {
  21296. *
  21297. * curveSegments: <int>, // number of points on the curves
  21298. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  21299. * depth: <float>, // Depth to extrude the shape
  21300. *
  21301. * bevelEnabled: <bool>, // turn on bevel
  21302. * bevelThickness: <float>, // how deep into the original shape bevel goes
  21303. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  21304. * bevelOffset: <float>, // how far from shape outline does bevel start
  21305. * bevelSegments: <int>, // number of bevel layers
  21306. *
  21307. * extrudePath: <THREE.Curve> // curve to extrude shape along
  21308. *
  21309. * UVGenerator: <Object> // object that provides UV generator functions
  21310. *
  21311. * }
  21312. */
  21313. class ExtrudeGeometry extends BufferGeometry {
  21314. 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 = {} ) {
  21315. super();
  21316. this.type = 'ExtrudeGeometry';
  21317. this.parameters = {
  21318. shapes: shapes,
  21319. options: options
  21320. };
  21321. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  21322. const scope = this;
  21323. const verticesArray = [];
  21324. const uvArray = [];
  21325. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21326. const shape = shapes[ i ];
  21327. addShape( shape );
  21328. }
  21329. // build geometry
  21330. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  21331. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  21332. this.computeVertexNormals();
  21333. // functions
  21334. function addShape( shape ) {
  21335. const placeholder = [];
  21336. // options
  21337. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  21338. const steps = options.steps !== undefined ? options.steps : 1;
  21339. const depth = options.depth !== undefined ? options.depth : 1;
  21340. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  21341. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  21342. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  21343. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  21344. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  21345. const extrudePath = options.extrudePath;
  21346. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  21347. //
  21348. let extrudePts, extrudeByPath = false;
  21349. let splineTube, binormal, normal, position2;
  21350. if ( extrudePath ) {
  21351. extrudePts = extrudePath.getSpacedPoints( steps );
  21352. extrudeByPath = true;
  21353. bevelEnabled = false; // bevels not supported for path extrusion
  21354. // SETUP TNB variables
  21355. // TODO1 - have a .isClosed in spline?
  21356. splineTube = extrudePath.computeFrenetFrames( steps, false );
  21357. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  21358. binormal = new Vector3();
  21359. normal = new Vector3();
  21360. position2 = new Vector3();
  21361. }
  21362. // Safeguards if bevels are not enabled
  21363. if ( ! bevelEnabled ) {
  21364. bevelSegments = 0;
  21365. bevelThickness = 0;
  21366. bevelSize = 0;
  21367. bevelOffset = 0;
  21368. }
  21369. // Variables initialization
  21370. const shapePoints = shape.extractPoints( curveSegments );
  21371. let vertices = shapePoints.shape;
  21372. const holes = shapePoints.holes;
  21373. const reverse = ! ShapeUtils.isClockWise( vertices );
  21374. if ( reverse ) {
  21375. vertices = vertices.reverse();
  21376. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  21377. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21378. const ahole = holes[ h ];
  21379. if ( ShapeUtils.isClockWise( ahole ) ) {
  21380. holes[ h ] = ahole.reverse();
  21381. }
  21382. }
  21383. }
  21384. const faces = ShapeUtils.triangulateShape( vertices, holes );
  21385. /* Vertices */
  21386. const contour = vertices; // vertices has all points but contour has only points of circumference
  21387. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21388. const ahole = holes[ h ];
  21389. vertices = vertices.concat( ahole );
  21390. }
  21391. function scalePt2( pt, vec, size ) {
  21392. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  21393. return pt.clone().addScaledVector( vec, size );
  21394. }
  21395. const vlen = vertices.length, flen = faces.length;
  21396. // Find directions for point movement
  21397. function getBevelVec( inPt, inPrev, inNext ) {
  21398. // computes for inPt the corresponding point inPt' on a new contour
  21399. // shifted by 1 unit (length of normalized vector) to the left
  21400. // if we walk along contour clockwise, this new contour is outside the old one
  21401. //
  21402. // inPt' is the intersection of the two lines parallel to the two
  21403. // adjacent edges of inPt at a distance of 1 unit on the left side.
  21404. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  21405. // good reading for geometry algorithms (here: line-line intersection)
  21406. // http://geomalgorithms.com/a05-_intersect-1.html
  21407. const v_prev_x = inPt.x - inPrev.x,
  21408. v_prev_y = inPt.y - inPrev.y;
  21409. const v_next_x = inNext.x - inPt.x,
  21410. v_next_y = inNext.y - inPt.y;
  21411. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  21412. // check for collinear edges
  21413. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21414. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  21415. // not collinear
  21416. // length of vectors for normalizing
  21417. const v_prev_len = Math.sqrt( v_prev_lensq );
  21418. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  21419. // shift adjacent points by unit vectors to the left
  21420. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  21421. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  21422. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  21423. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  21424. // scaling factor for v_prev to intersection point
  21425. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  21426. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  21427. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  21428. // vector from inPt to intersection point
  21429. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  21430. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  21431. // Don't normalize!, otherwise sharp corners become ugly
  21432. // but prevent crazy spikes
  21433. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  21434. if ( v_trans_lensq <= 2 ) {
  21435. return new Vector2( v_trans_x, v_trans_y );
  21436. } else {
  21437. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  21438. }
  21439. } else {
  21440. // handle special case of collinear edges
  21441. let direction_eq = false; // assumes: opposite
  21442. if ( v_prev_x > Number.EPSILON ) {
  21443. if ( v_next_x > Number.EPSILON ) {
  21444. direction_eq = true;
  21445. }
  21446. } else {
  21447. if ( v_prev_x < - Number.EPSILON ) {
  21448. if ( v_next_x < - Number.EPSILON ) {
  21449. direction_eq = true;
  21450. }
  21451. } else {
  21452. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  21453. direction_eq = true;
  21454. }
  21455. }
  21456. }
  21457. if ( direction_eq ) {
  21458. // console.log("Warning: lines are a straight sequence");
  21459. v_trans_x = - v_prev_y;
  21460. v_trans_y = v_prev_x;
  21461. shrink_by = Math.sqrt( v_prev_lensq );
  21462. } else {
  21463. // console.log("Warning: lines are a straight spike");
  21464. v_trans_x = v_prev_x;
  21465. v_trans_y = v_prev_y;
  21466. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  21467. }
  21468. }
  21469. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  21470. }
  21471. const contourMovements = [];
  21472. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21473. if ( j === il ) j = 0;
  21474. if ( k === il ) k = 0;
  21475. // (j)---(i)---(k)
  21476. // console.log('i,j,k', i, j , k)
  21477. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  21478. }
  21479. const holesMovements = [];
  21480. let oneHoleMovements, verticesMovements = contourMovements.concat();
  21481. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21482. const ahole = holes[ h ];
  21483. oneHoleMovements = [];
  21484. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21485. if ( j === il ) j = 0;
  21486. if ( k === il ) k = 0;
  21487. // (j)---(i)---(k)
  21488. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  21489. }
  21490. holesMovements.push( oneHoleMovements );
  21491. verticesMovements = verticesMovements.concat( oneHoleMovements );
  21492. }
  21493. // Loop bevelSegments, 1 for the front, 1 for the back
  21494. for ( let b = 0; b < bevelSegments; b ++ ) {
  21495. //for ( b = bevelSegments; b > 0; b -- ) {
  21496. const t = b / bevelSegments;
  21497. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21498. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21499. // contract shape
  21500. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21501. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21502. v( vert.x, vert.y, - z );
  21503. }
  21504. // expand holes
  21505. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21506. const ahole = holes[ h ];
  21507. oneHoleMovements = holesMovements[ h ];
  21508. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21509. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21510. v( vert.x, vert.y, - z );
  21511. }
  21512. }
  21513. }
  21514. const bs = bevelSize + bevelOffset;
  21515. // Back facing vertices
  21516. for ( let i = 0; i < vlen; i ++ ) {
  21517. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21518. if ( ! extrudeByPath ) {
  21519. v( vert.x, vert.y, 0 );
  21520. } else {
  21521. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  21522. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  21523. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  21524. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  21525. v( position2.x, position2.y, position2.z );
  21526. }
  21527. }
  21528. // Add stepped vertices...
  21529. // Including front facing vertices
  21530. for ( let s = 1; s <= steps; s ++ ) {
  21531. for ( let i = 0; i < vlen; i ++ ) {
  21532. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21533. if ( ! extrudeByPath ) {
  21534. v( vert.x, vert.y, depth / steps * s );
  21535. } else {
  21536. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  21537. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  21538. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  21539. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  21540. v( position2.x, position2.y, position2.z );
  21541. }
  21542. }
  21543. }
  21544. // Add bevel segments planes
  21545. //for ( b = 1; b <= bevelSegments; b ++ ) {
  21546. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  21547. const t = b / bevelSegments;
  21548. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21549. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  21550. // contract shape
  21551. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  21552. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21553. v( vert.x, vert.y, depth + z );
  21554. }
  21555. // expand holes
  21556. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21557. const ahole = holes[ h ];
  21558. oneHoleMovements = holesMovements[ h ];
  21559. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  21560. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21561. if ( ! extrudeByPath ) {
  21562. v( vert.x, vert.y, depth + z );
  21563. } else {
  21564. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  21565. }
  21566. }
  21567. }
  21568. }
  21569. /* Faces */
  21570. // Top and bottom faces
  21571. buildLidFaces();
  21572. // Sides faces
  21573. buildSideFaces();
  21574. ///// Internal functions
  21575. function buildLidFaces() {
  21576. const start = verticesArray.length / 3;
  21577. if ( bevelEnabled ) {
  21578. let layer = 0; // steps + 1
  21579. let offset = vlen * layer;
  21580. // Bottom faces
  21581. for ( let i = 0; i < flen; i ++ ) {
  21582. const face = faces[ i ];
  21583. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  21584. }
  21585. layer = steps + bevelSegments * 2;
  21586. offset = vlen * layer;
  21587. // Top faces
  21588. for ( let i = 0; i < flen; i ++ ) {
  21589. const face = faces[ i ];
  21590. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  21591. }
  21592. } else {
  21593. // Bottom faces
  21594. for ( let i = 0; i < flen; i ++ ) {
  21595. const face = faces[ i ];
  21596. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  21597. }
  21598. // Top faces
  21599. for ( let i = 0; i < flen; i ++ ) {
  21600. const face = faces[ i ];
  21601. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  21602. }
  21603. }
  21604. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  21605. }
  21606. // Create faces for the z-sides of the shape
  21607. function buildSideFaces() {
  21608. const start = verticesArray.length / 3;
  21609. let layeroffset = 0;
  21610. sidewalls( contour, layeroffset );
  21611. layeroffset += contour.length;
  21612. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  21613. const ahole = holes[ h ];
  21614. sidewalls( ahole, layeroffset );
  21615. //, true
  21616. layeroffset += ahole.length;
  21617. }
  21618. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  21619. }
  21620. function sidewalls( contour, layeroffset ) {
  21621. let i = contour.length;
  21622. while ( -- i >= 0 ) {
  21623. const j = i;
  21624. let k = i - 1;
  21625. if ( k < 0 ) k = contour.length - 1;
  21626. //console.log('b', i,j, i-1, k,vertices.length);
  21627. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  21628. const slen1 = vlen * s;
  21629. const slen2 = vlen * ( s + 1 );
  21630. const a = layeroffset + j + slen1,
  21631. b = layeroffset + k + slen1,
  21632. c = layeroffset + k + slen2,
  21633. d = layeroffset + j + slen2;
  21634. f4( a, b, c, d );
  21635. }
  21636. }
  21637. }
  21638. function v( x, y, z ) {
  21639. placeholder.push( x );
  21640. placeholder.push( y );
  21641. placeholder.push( z );
  21642. }
  21643. function f3( a, b, c ) {
  21644. addVertex( a );
  21645. addVertex( b );
  21646. addVertex( c );
  21647. const nextIndex = verticesArray.length / 3;
  21648. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21649. addUV( uvs[ 0 ] );
  21650. addUV( uvs[ 1 ] );
  21651. addUV( uvs[ 2 ] );
  21652. }
  21653. function f4( a, b, c, d ) {
  21654. addVertex( a );
  21655. addVertex( b );
  21656. addVertex( d );
  21657. addVertex( b );
  21658. addVertex( c );
  21659. addVertex( d );
  21660. const nextIndex = verticesArray.length / 3;
  21661. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21662. addUV( uvs[ 0 ] );
  21663. addUV( uvs[ 1 ] );
  21664. addUV( uvs[ 3 ] );
  21665. addUV( uvs[ 1 ] );
  21666. addUV( uvs[ 2 ] );
  21667. addUV( uvs[ 3 ] );
  21668. }
  21669. function addVertex( index ) {
  21670. verticesArray.push( placeholder[ index * 3 + 0 ] );
  21671. verticesArray.push( placeholder[ index * 3 + 1 ] );
  21672. verticesArray.push( placeholder[ index * 3 + 2 ] );
  21673. }
  21674. function addUV( vector2 ) {
  21675. uvArray.push( vector2.x );
  21676. uvArray.push( vector2.y );
  21677. }
  21678. }
  21679. }
  21680. copy( source ) {
  21681. super.copy( source );
  21682. this.parameters = Object.assign( {}, source.parameters );
  21683. return this;
  21684. }
  21685. toJSON() {
  21686. const data = super.toJSON();
  21687. const shapes = this.parameters.shapes;
  21688. const options = this.parameters.options;
  21689. return toJSON$1( shapes, options, data );
  21690. }
  21691. static fromJSON( data, shapes ) {
  21692. const geometryShapes = [];
  21693. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21694. const shape = shapes[ data.shapes[ j ] ];
  21695. geometryShapes.push( shape );
  21696. }
  21697. const extrudePath = data.options.extrudePath;
  21698. if ( extrudePath !== undefined ) {
  21699. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  21700. }
  21701. return new ExtrudeGeometry( geometryShapes, data.options );
  21702. }
  21703. }
  21704. const WorldUVGenerator = {
  21705. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  21706. const a_x = vertices[ indexA * 3 ];
  21707. const a_y = vertices[ indexA * 3 + 1 ];
  21708. const b_x = vertices[ indexB * 3 ];
  21709. const b_y = vertices[ indexB * 3 + 1 ];
  21710. const c_x = vertices[ indexC * 3 ];
  21711. const c_y = vertices[ indexC * 3 + 1 ];
  21712. return [
  21713. new Vector2( a_x, a_y ),
  21714. new Vector2( b_x, b_y ),
  21715. new Vector2( c_x, c_y )
  21716. ];
  21717. },
  21718. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  21719. const a_x = vertices[ indexA * 3 ];
  21720. const a_y = vertices[ indexA * 3 + 1 ];
  21721. const a_z = vertices[ indexA * 3 + 2 ];
  21722. const b_x = vertices[ indexB * 3 ];
  21723. const b_y = vertices[ indexB * 3 + 1 ];
  21724. const b_z = vertices[ indexB * 3 + 2 ];
  21725. const c_x = vertices[ indexC * 3 ];
  21726. const c_y = vertices[ indexC * 3 + 1 ];
  21727. const c_z = vertices[ indexC * 3 + 2 ];
  21728. const d_x = vertices[ indexD * 3 ];
  21729. const d_y = vertices[ indexD * 3 + 1 ];
  21730. const d_z = vertices[ indexD * 3 + 2 ];
  21731. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  21732. return [
  21733. new Vector2( a_x, 1 - a_z ),
  21734. new Vector2( b_x, 1 - b_z ),
  21735. new Vector2( c_x, 1 - c_z ),
  21736. new Vector2( d_x, 1 - d_z )
  21737. ];
  21738. } else {
  21739. return [
  21740. new Vector2( a_y, 1 - a_z ),
  21741. new Vector2( b_y, 1 - b_z ),
  21742. new Vector2( c_y, 1 - c_z ),
  21743. new Vector2( d_y, 1 - d_z )
  21744. ];
  21745. }
  21746. }
  21747. };
  21748. function toJSON$1( shapes, options, data ) {
  21749. data.shapes = [];
  21750. if ( Array.isArray( shapes ) ) {
  21751. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21752. const shape = shapes[ i ];
  21753. data.shapes.push( shape.uuid );
  21754. }
  21755. } else {
  21756. data.shapes.push( shapes.uuid );
  21757. }
  21758. data.options = Object.assign( {}, options );
  21759. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  21760. return data;
  21761. }
  21762. class IcosahedronGeometry extends PolyhedronGeometry {
  21763. constructor( radius = 1, detail = 0 ) {
  21764. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21765. const vertices = [
  21766. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  21767. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  21768. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  21769. ];
  21770. const indices = [
  21771. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  21772. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  21773. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  21774. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  21775. ];
  21776. super( vertices, indices, radius, detail );
  21777. this.type = 'IcosahedronGeometry';
  21778. this.parameters = {
  21779. radius: radius,
  21780. detail: detail
  21781. };
  21782. }
  21783. static fromJSON( data ) {
  21784. return new IcosahedronGeometry( data.radius, data.detail );
  21785. }
  21786. }
  21787. class OctahedronGeometry extends PolyhedronGeometry {
  21788. constructor( radius = 1, detail = 0 ) {
  21789. const vertices = [
  21790. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  21791. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  21792. ];
  21793. const indices = [
  21794. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  21795. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  21796. 1, 3, 4, 1, 4, 2
  21797. ];
  21798. super( vertices, indices, radius, detail );
  21799. this.type = 'OctahedronGeometry';
  21800. this.parameters = {
  21801. radius: radius,
  21802. detail: detail
  21803. };
  21804. }
  21805. static fromJSON( data ) {
  21806. return new OctahedronGeometry( data.radius, data.detail );
  21807. }
  21808. }
  21809. class RingGeometry extends BufferGeometry {
  21810. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21811. super();
  21812. this.type = 'RingGeometry';
  21813. this.parameters = {
  21814. innerRadius: innerRadius,
  21815. outerRadius: outerRadius,
  21816. thetaSegments: thetaSegments,
  21817. phiSegments: phiSegments,
  21818. thetaStart: thetaStart,
  21819. thetaLength: thetaLength
  21820. };
  21821. thetaSegments = Math.max( 3, thetaSegments );
  21822. phiSegments = Math.max( 1, phiSegments );
  21823. // buffers
  21824. const indices = [];
  21825. const vertices = [];
  21826. const normals = [];
  21827. const uvs = [];
  21828. // some helper variables
  21829. let radius = innerRadius;
  21830. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  21831. const vertex = new Vector3();
  21832. const uv = new Vector2();
  21833. // generate vertices, normals and uvs
  21834. for ( let j = 0; j <= phiSegments; j ++ ) {
  21835. for ( let i = 0; i <= thetaSegments; i ++ ) {
  21836. // values are generate from the inside of the ring to the outside
  21837. const segment = thetaStart + i / thetaSegments * thetaLength;
  21838. // vertex
  21839. vertex.x = radius * Math.cos( segment );
  21840. vertex.y = radius * Math.sin( segment );
  21841. vertices.push( vertex.x, vertex.y, vertex.z );
  21842. // normal
  21843. normals.push( 0, 0, 1 );
  21844. // uv
  21845. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  21846. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  21847. uvs.push( uv.x, uv.y );
  21848. }
  21849. // increase the radius for next row of vertices
  21850. radius += radiusStep;
  21851. }
  21852. // indices
  21853. for ( let j = 0; j < phiSegments; j ++ ) {
  21854. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  21855. for ( let i = 0; i < thetaSegments; i ++ ) {
  21856. const segment = i + thetaSegmentLevel;
  21857. const a = segment;
  21858. const b = segment + thetaSegments + 1;
  21859. const c = segment + thetaSegments + 2;
  21860. const d = segment + 1;
  21861. // faces
  21862. indices.push( a, b, d );
  21863. indices.push( b, c, d );
  21864. }
  21865. }
  21866. // build geometry
  21867. this.setIndex( indices );
  21868. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21869. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21870. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21871. }
  21872. copy( source ) {
  21873. super.copy( source );
  21874. this.parameters = Object.assign( {}, source.parameters );
  21875. return this;
  21876. }
  21877. static fromJSON( data ) {
  21878. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  21879. }
  21880. }
  21881. class ShapeGeometry extends BufferGeometry {
  21882. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  21883. super();
  21884. this.type = 'ShapeGeometry';
  21885. this.parameters = {
  21886. shapes: shapes,
  21887. curveSegments: curveSegments
  21888. };
  21889. // buffers
  21890. const indices = [];
  21891. const vertices = [];
  21892. const normals = [];
  21893. const uvs = [];
  21894. // helper variables
  21895. let groupStart = 0;
  21896. let groupCount = 0;
  21897. // allow single and array values for "shapes" parameter
  21898. if ( Array.isArray( shapes ) === false ) {
  21899. addShape( shapes );
  21900. } else {
  21901. for ( let i = 0; i < shapes.length; i ++ ) {
  21902. addShape( shapes[ i ] );
  21903. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  21904. groupStart += groupCount;
  21905. groupCount = 0;
  21906. }
  21907. }
  21908. // build geometry
  21909. this.setIndex( indices );
  21910. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21911. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21912. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21913. // helper functions
  21914. function addShape( shape ) {
  21915. const indexOffset = vertices.length / 3;
  21916. const points = shape.extractPoints( curveSegments );
  21917. let shapeVertices = points.shape;
  21918. const shapeHoles = points.holes;
  21919. // check direction of vertices
  21920. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  21921. shapeVertices = shapeVertices.reverse();
  21922. }
  21923. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21924. const shapeHole = shapeHoles[ i ];
  21925. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  21926. shapeHoles[ i ] = shapeHole.reverse();
  21927. }
  21928. }
  21929. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  21930. // join vertices of inner and outer paths to a single array
  21931. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21932. const shapeHole = shapeHoles[ i ];
  21933. shapeVertices = shapeVertices.concat( shapeHole );
  21934. }
  21935. // vertices, normals, uvs
  21936. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  21937. const vertex = shapeVertices[ i ];
  21938. vertices.push( vertex.x, vertex.y, 0 );
  21939. normals.push( 0, 0, 1 );
  21940. uvs.push( vertex.x, vertex.y ); // world uvs
  21941. }
  21942. // indices
  21943. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  21944. const face = faces[ i ];
  21945. const a = face[ 0 ] + indexOffset;
  21946. const b = face[ 1 ] + indexOffset;
  21947. const c = face[ 2 ] + indexOffset;
  21948. indices.push( a, b, c );
  21949. groupCount += 3;
  21950. }
  21951. }
  21952. }
  21953. copy( source ) {
  21954. super.copy( source );
  21955. this.parameters = Object.assign( {}, source.parameters );
  21956. return this;
  21957. }
  21958. toJSON() {
  21959. const data = super.toJSON();
  21960. const shapes = this.parameters.shapes;
  21961. return toJSON( shapes, data );
  21962. }
  21963. static fromJSON( data, shapes ) {
  21964. const geometryShapes = [];
  21965. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21966. const shape = shapes[ data.shapes[ j ] ];
  21967. geometryShapes.push( shape );
  21968. }
  21969. return new ShapeGeometry( geometryShapes, data.curveSegments );
  21970. }
  21971. }
  21972. function toJSON( shapes, data ) {
  21973. data.shapes = [];
  21974. if ( Array.isArray( shapes ) ) {
  21975. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21976. const shape = shapes[ i ];
  21977. data.shapes.push( shape.uuid );
  21978. }
  21979. } else {
  21980. data.shapes.push( shapes.uuid );
  21981. }
  21982. return data;
  21983. }
  21984. class SphereGeometry extends BufferGeometry {
  21985. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  21986. super();
  21987. this.type = 'SphereGeometry';
  21988. this.parameters = {
  21989. radius: radius,
  21990. widthSegments: widthSegments,
  21991. heightSegments: heightSegments,
  21992. phiStart: phiStart,
  21993. phiLength: phiLength,
  21994. thetaStart: thetaStart,
  21995. thetaLength: thetaLength
  21996. };
  21997. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  21998. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  21999. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  22000. let index = 0;
  22001. const grid = [];
  22002. const vertex = new Vector3();
  22003. const normal = new Vector3();
  22004. // buffers
  22005. const indices = [];
  22006. const vertices = [];
  22007. const normals = [];
  22008. const uvs = [];
  22009. // generate vertices, normals and uvs
  22010. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  22011. const verticesRow = [];
  22012. const v = iy / heightSegments;
  22013. // special case for the poles
  22014. let uOffset = 0;
  22015. if ( iy == 0 && thetaStart == 0 ) {
  22016. uOffset = 0.5 / widthSegments;
  22017. } else if ( iy == heightSegments && thetaEnd == Math.PI ) {
  22018. uOffset = - 0.5 / widthSegments;
  22019. }
  22020. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  22021. const u = ix / widthSegments;
  22022. // vertex
  22023. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22024. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  22025. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  22026. vertices.push( vertex.x, vertex.y, vertex.z );
  22027. // normal
  22028. normal.copy( vertex ).normalize();
  22029. normals.push( normal.x, normal.y, normal.z );
  22030. // uv
  22031. uvs.push( u + uOffset, 1 - v );
  22032. verticesRow.push( index ++ );
  22033. }
  22034. grid.push( verticesRow );
  22035. }
  22036. // indices
  22037. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  22038. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  22039. const a = grid[ iy ][ ix + 1 ];
  22040. const b = grid[ iy ][ ix ];
  22041. const c = grid[ iy + 1 ][ ix ];
  22042. const d = grid[ iy + 1 ][ ix + 1 ];
  22043. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  22044. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  22045. }
  22046. }
  22047. // build geometry
  22048. this.setIndex( indices );
  22049. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22050. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22051. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22052. }
  22053. copy( source ) {
  22054. super.copy( source );
  22055. this.parameters = Object.assign( {}, source.parameters );
  22056. return this;
  22057. }
  22058. static fromJSON( data ) {
  22059. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  22060. }
  22061. }
  22062. class TetrahedronGeometry extends PolyhedronGeometry {
  22063. constructor( radius = 1, detail = 0 ) {
  22064. const vertices = [
  22065. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  22066. ];
  22067. const indices = [
  22068. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  22069. ];
  22070. super( vertices, indices, radius, detail );
  22071. this.type = 'TetrahedronGeometry';
  22072. this.parameters = {
  22073. radius: radius,
  22074. detail: detail
  22075. };
  22076. }
  22077. static fromJSON( data ) {
  22078. return new TetrahedronGeometry( data.radius, data.detail );
  22079. }
  22080. }
  22081. class TorusGeometry extends BufferGeometry {
  22082. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  22083. super();
  22084. this.type = 'TorusGeometry';
  22085. this.parameters = {
  22086. radius: radius,
  22087. tube: tube,
  22088. radialSegments: radialSegments,
  22089. tubularSegments: tubularSegments,
  22090. arc: arc
  22091. };
  22092. radialSegments = Math.floor( radialSegments );
  22093. tubularSegments = Math.floor( tubularSegments );
  22094. // buffers
  22095. const indices = [];
  22096. const vertices = [];
  22097. const normals = [];
  22098. const uvs = [];
  22099. // helper variables
  22100. const center = new Vector3();
  22101. const vertex = new Vector3();
  22102. const normal = new Vector3();
  22103. // generate vertices, normals and uvs
  22104. for ( let j = 0; j <= radialSegments; j ++ ) {
  22105. for ( let i = 0; i <= tubularSegments; i ++ ) {
  22106. const u = i / tubularSegments * arc;
  22107. const v = j / radialSegments * Math.PI * 2;
  22108. // vertex
  22109. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  22110. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  22111. vertex.z = tube * Math.sin( v );
  22112. vertices.push( vertex.x, vertex.y, vertex.z );
  22113. // normal
  22114. center.x = radius * Math.cos( u );
  22115. center.y = radius * Math.sin( u );
  22116. normal.subVectors( vertex, center ).normalize();
  22117. normals.push( normal.x, normal.y, normal.z );
  22118. // uv
  22119. uvs.push( i / tubularSegments );
  22120. uvs.push( j / radialSegments );
  22121. }
  22122. }
  22123. // generate indices
  22124. for ( let j = 1; j <= radialSegments; j ++ ) {
  22125. for ( let i = 1; i <= tubularSegments; i ++ ) {
  22126. // indices
  22127. const a = ( tubularSegments + 1 ) * j + i - 1;
  22128. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  22129. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  22130. const d = ( tubularSegments + 1 ) * j + i;
  22131. // faces
  22132. indices.push( a, b, d );
  22133. indices.push( b, c, d );
  22134. }
  22135. }
  22136. // build geometry
  22137. this.setIndex( indices );
  22138. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22139. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22140. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22141. }
  22142. copy( source ) {
  22143. super.copy( source );
  22144. this.parameters = Object.assign( {}, source.parameters );
  22145. return this;
  22146. }
  22147. static fromJSON( data ) {
  22148. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  22149. }
  22150. }
  22151. class TorusKnotGeometry extends BufferGeometry {
  22152. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  22153. super();
  22154. this.type = 'TorusKnotGeometry';
  22155. this.parameters = {
  22156. radius: radius,
  22157. tube: tube,
  22158. tubularSegments: tubularSegments,
  22159. radialSegments: radialSegments,
  22160. p: p,
  22161. q: q
  22162. };
  22163. tubularSegments = Math.floor( tubularSegments );
  22164. radialSegments = Math.floor( radialSegments );
  22165. // buffers
  22166. const indices = [];
  22167. const vertices = [];
  22168. const normals = [];
  22169. const uvs = [];
  22170. // helper variables
  22171. const vertex = new Vector3();
  22172. const normal = new Vector3();
  22173. const P1 = new Vector3();
  22174. const P2 = new Vector3();
  22175. const B = new Vector3();
  22176. const T = new Vector3();
  22177. const N = new Vector3();
  22178. // generate vertices, normals and uvs
  22179. for ( let i = 0; i <= tubularSegments; ++ i ) {
  22180. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  22181. const u = i / tubularSegments * p * Math.PI * 2;
  22182. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  22183. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  22184. calculatePositionOnCurve( u, p, q, radius, P1 );
  22185. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  22186. // calculate orthonormal basis
  22187. T.subVectors( P2, P1 );
  22188. N.addVectors( P2, P1 );
  22189. B.crossVectors( T, N );
  22190. N.crossVectors( B, T );
  22191. // normalize B, N. T can be ignored, we don't use it
  22192. B.normalize();
  22193. N.normalize();
  22194. for ( let j = 0; j <= radialSegments; ++ j ) {
  22195. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  22196. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  22197. const v = j / radialSegments * Math.PI * 2;
  22198. const cx = - tube * Math.cos( v );
  22199. const cy = tube * Math.sin( v );
  22200. // now calculate the final vertex position.
  22201. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  22202. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  22203. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  22204. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  22205. vertices.push( vertex.x, vertex.y, vertex.z );
  22206. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  22207. normal.subVectors( vertex, P1 ).normalize();
  22208. normals.push( normal.x, normal.y, normal.z );
  22209. // uv
  22210. uvs.push( i / tubularSegments );
  22211. uvs.push( j / radialSegments );
  22212. }
  22213. }
  22214. // generate indices
  22215. for ( let j = 1; j <= tubularSegments; j ++ ) {
  22216. for ( let i = 1; i <= radialSegments; i ++ ) {
  22217. // indices
  22218. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  22219. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  22220. const c = ( radialSegments + 1 ) * j + i;
  22221. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  22222. // faces
  22223. indices.push( a, b, d );
  22224. indices.push( b, c, d );
  22225. }
  22226. }
  22227. // build geometry
  22228. this.setIndex( indices );
  22229. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22230. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22231. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22232. // this function calculates the current position on the torus curve
  22233. function calculatePositionOnCurve( u, p, q, radius, position ) {
  22234. const cu = Math.cos( u );
  22235. const su = Math.sin( u );
  22236. const quOverP = q / p * u;
  22237. const cs = Math.cos( quOverP );
  22238. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  22239. position.y = radius * ( 2 + cs ) * su * 0.5;
  22240. position.z = radius * Math.sin( quOverP ) * 0.5;
  22241. }
  22242. }
  22243. copy( source ) {
  22244. super.copy( source );
  22245. this.parameters = Object.assign( {}, source.parameters );
  22246. return this;
  22247. }
  22248. static fromJSON( data ) {
  22249. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  22250. }
  22251. }
  22252. class TubeGeometry extends BufferGeometry {
  22253. 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 ) {
  22254. super();
  22255. this.type = 'TubeGeometry';
  22256. this.parameters = {
  22257. path: path,
  22258. tubularSegments: tubularSegments,
  22259. radius: radius,
  22260. radialSegments: radialSegments,
  22261. closed: closed
  22262. };
  22263. const frames = path.computeFrenetFrames( tubularSegments, closed );
  22264. // expose internals
  22265. this.tangents = frames.tangents;
  22266. this.normals = frames.normals;
  22267. this.binormals = frames.binormals;
  22268. // helper variables
  22269. const vertex = new Vector3();
  22270. const normal = new Vector3();
  22271. const uv = new Vector2();
  22272. let P = new Vector3();
  22273. // buffer
  22274. const vertices = [];
  22275. const normals = [];
  22276. const uvs = [];
  22277. const indices = [];
  22278. // create buffer data
  22279. generateBufferData();
  22280. // build geometry
  22281. this.setIndex( indices );
  22282. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22283. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22284. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22285. // functions
  22286. function generateBufferData() {
  22287. for ( let i = 0; i < tubularSegments; i ++ ) {
  22288. generateSegment( i );
  22289. }
  22290. // if the geometry is not closed, generate the last row of vertices and normals
  22291. // at the regular position on the given path
  22292. //
  22293. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  22294. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  22295. // uvs are generated in a separate function.
  22296. // this makes it easy compute correct values for closed geometries
  22297. generateUVs();
  22298. // finally create faces
  22299. generateIndices();
  22300. }
  22301. function generateSegment( i ) {
  22302. // we use getPointAt to sample evenly distributed points from the given path
  22303. P = path.getPointAt( i / tubularSegments, P );
  22304. // retrieve corresponding normal and binormal
  22305. const N = frames.normals[ i ];
  22306. const B = frames.binormals[ i ];
  22307. // generate normals and vertices for the current segment
  22308. for ( let j = 0; j <= radialSegments; j ++ ) {
  22309. const v = j / radialSegments * Math.PI * 2;
  22310. const sin = Math.sin( v );
  22311. const cos = - Math.cos( v );
  22312. // normal
  22313. normal.x = ( cos * N.x + sin * B.x );
  22314. normal.y = ( cos * N.y + sin * B.y );
  22315. normal.z = ( cos * N.z + sin * B.z );
  22316. normal.normalize();
  22317. normals.push( normal.x, normal.y, normal.z );
  22318. // vertex
  22319. vertex.x = P.x + radius * normal.x;
  22320. vertex.y = P.y + radius * normal.y;
  22321. vertex.z = P.z + radius * normal.z;
  22322. vertices.push( vertex.x, vertex.y, vertex.z );
  22323. }
  22324. }
  22325. function generateIndices() {
  22326. for ( let j = 1; j <= tubularSegments; j ++ ) {
  22327. for ( let i = 1; i <= radialSegments; i ++ ) {
  22328. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  22329. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  22330. const c = ( radialSegments + 1 ) * j + i;
  22331. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  22332. // faces
  22333. indices.push( a, b, d );
  22334. indices.push( b, c, d );
  22335. }
  22336. }
  22337. }
  22338. function generateUVs() {
  22339. for ( let i = 0; i <= tubularSegments; i ++ ) {
  22340. for ( let j = 0; j <= radialSegments; j ++ ) {
  22341. uv.x = i / tubularSegments;
  22342. uv.y = j / radialSegments;
  22343. uvs.push( uv.x, uv.y );
  22344. }
  22345. }
  22346. }
  22347. }
  22348. copy( source ) {
  22349. super.copy( source );
  22350. this.parameters = Object.assign( {}, source.parameters );
  22351. return this;
  22352. }
  22353. toJSON() {
  22354. const data = super.toJSON();
  22355. data.path = this.parameters.path.toJSON();
  22356. return data;
  22357. }
  22358. static fromJSON( data ) {
  22359. // This only works for built-in curves (e.g. CatmullRomCurve3).
  22360. // User defined curves or instances of CurvePath will not be deserialized.
  22361. return new TubeGeometry(
  22362. new Curves[ data.path.type ]().fromJSON( data.path ),
  22363. data.tubularSegments,
  22364. data.radius,
  22365. data.radialSegments,
  22366. data.closed
  22367. );
  22368. }
  22369. }
  22370. class WireframeGeometry extends BufferGeometry {
  22371. constructor( geometry = null ) {
  22372. super();
  22373. this.type = 'WireframeGeometry';
  22374. this.parameters = {
  22375. geometry: geometry
  22376. };
  22377. if ( geometry !== null ) {
  22378. // buffer
  22379. const vertices = [];
  22380. const edges = new Set();
  22381. // helper variables
  22382. const start = new Vector3();
  22383. const end = new Vector3();
  22384. if ( geometry.index !== null ) {
  22385. // indexed BufferGeometry
  22386. const position = geometry.attributes.position;
  22387. const indices = geometry.index;
  22388. let groups = geometry.groups;
  22389. if ( groups.length === 0 ) {
  22390. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  22391. }
  22392. // create a data structure that contains all edges without duplicates
  22393. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  22394. const group = groups[ o ];
  22395. const groupStart = group.start;
  22396. const groupCount = group.count;
  22397. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  22398. for ( let j = 0; j < 3; j ++ ) {
  22399. const index1 = indices.getX( i + j );
  22400. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  22401. start.fromBufferAttribute( position, index1 );
  22402. end.fromBufferAttribute( position, index2 );
  22403. if ( isUniqueEdge( start, end, edges ) === true ) {
  22404. vertices.push( start.x, start.y, start.z );
  22405. vertices.push( end.x, end.y, end.z );
  22406. }
  22407. }
  22408. }
  22409. }
  22410. } else {
  22411. // non-indexed BufferGeometry
  22412. const position = geometry.attributes.position;
  22413. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  22414. for ( let j = 0; j < 3; j ++ ) {
  22415. // three edges per triangle, an edge is represented as (index1, index2)
  22416. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  22417. const index1 = 3 * i + j;
  22418. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  22419. start.fromBufferAttribute( position, index1 );
  22420. end.fromBufferAttribute( position, index2 );
  22421. if ( isUniqueEdge( start, end, edges ) === true ) {
  22422. vertices.push( start.x, start.y, start.z );
  22423. vertices.push( end.x, end.y, end.z );
  22424. }
  22425. }
  22426. }
  22427. }
  22428. // build geometry
  22429. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22430. }
  22431. }
  22432. copy( source ) {
  22433. super.copy( source );
  22434. this.parameters = Object.assign( {}, source.parameters );
  22435. return this;
  22436. }
  22437. }
  22438. function isUniqueEdge( start, end, edges ) {
  22439. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  22440. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  22441. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  22442. return false;
  22443. } else {
  22444. edges.add( hash1 );
  22445. edges.add( hash2 );
  22446. return true;
  22447. }
  22448. }
  22449. var Geometries = /*#__PURE__*/Object.freeze({
  22450. __proto__: null,
  22451. BoxGeometry: BoxGeometry,
  22452. CapsuleGeometry: CapsuleGeometry,
  22453. CircleGeometry: CircleGeometry,
  22454. ConeGeometry: ConeGeometry,
  22455. CylinderGeometry: CylinderGeometry,
  22456. DodecahedronGeometry: DodecahedronGeometry,
  22457. EdgesGeometry: EdgesGeometry,
  22458. ExtrudeGeometry: ExtrudeGeometry,
  22459. IcosahedronGeometry: IcosahedronGeometry,
  22460. LatheGeometry: LatheGeometry,
  22461. OctahedronGeometry: OctahedronGeometry,
  22462. PlaneGeometry: PlaneGeometry,
  22463. PolyhedronGeometry: PolyhedronGeometry,
  22464. RingGeometry: RingGeometry,
  22465. ShapeGeometry: ShapeGeometry,
  22466. SphereGeometry: SphereGeometry,
  22467. TetrahedronGeometry: TetrahedronGeometry,
  22468. TorusGeometry: TorusGeometry,
  22469. TorusKnotGeometry: TorusKnotGeometry,
  22470. TubeGeometry: TubeGeometry,
  22471. WireframeGeometry: WireframeGeometry
  22472. });
  22473. class ShadowMaterial extends Material {
  22474. constructor( parameters ) {
  22475. super();
  22476. this.isShadowMaterial = true;
  22477. this.type = 'ShadowMaterial';
  22478. this.color = new Color( 0x000000 );
  22479. this.transparent = true;
  22480. this.fog = true;
  22481. this.setValues( parameters );
  22482. }
  22483. copy( source ) {
  22484. super.copy( source );
  22485. this.color.copy( source.color );
  22486. this.fog = source.fog;
  22487. return this;
  22488. }
  22489. }
  22490. class RawShaderMaterial extends ShaderMaterial {
  22491. constructor( parameters ) {
  22492. super( parameters );
  22493. this.isRawShaderMaterial = true;
  22494. this.type = 'RawShaderMaterial';
  22495. }
  22496. }
  22497. class MeshStandardMaterial extends Material {
  22498. constructor( parameters ) {
  22499. super();
  22500. this.isMeshStandardMaterial = true;
  22501. this.defines = { 'STANDARD': '' };
  22502. this.type = 'MeshStandardMaterial';
  22503. this.color = new Color( 0xffffff ); // diffuse
  22504. this.roughness = 1.0;
  22505. this.metalness = 0.0;
  22506. this.map = null;
  22507. this.lightMap = null;
  22508. this.lightMapIntensity = 1.0;
  22509. this.aoMap = null;
  22510. this.aoMapIntensity = 1.0;
  22511. this.emissive = new Color( 0x000000 );
  22512. this.emissiveIntensity = 1.0;
  22513. this.emissiveMap = null;
  22514. this.bumpMap = null;
  22515. this.bumpScale = 1;
  22516. this.normalMap = null;
  22517. this.normalMapType = TangentSpaceNormalMap;
  22518. this.normalScale = new Vector2( 1, 1 );
  22519. this.displacementMap = null;
  22520. this.displacementScale = 1;
  22521. this.displacementBias = 0;
  22522. this.roughnessMap = null;
  22523. this.metalnessMap = null;
  22524. this.alphaMap = null;
  22525. this.envMap = null;
  22526. this.envMapIntensity = 1.0;
  22527. this.wireframe = false;
  22528. this.wireframeLinewidth = 1;
  22529. this.wireframeLinecap = 'round';
  22530. this.wireframeLinejoin = 'round';
  22531. this.flatShading = false;
  22532. this.fog = true;
  22533. this.setValues( parameters );
  22534. }
  22535. copy( source ) {
  22536. super.copy( source );
  22537. this.defines = { 'STANDARD': '' };
  22538. this.color.copy( source.color );
  22539. this.roughness = source.roughness;
  22540. this.metalness = source.metalness;
  22541. this.map = source.map;
  22542. this.lightMap = source.lightMap;
  22543. this.lightMapIntensity = source.lightMapIntensity;
  22544. this.aoMap = source.aoMap;
  22545. this.aoMapIntensity = source.aoMapIntensity;
  22546. this.emissive.copy( source.emissive );
  22547. this.emissiveMap = source.emissiveMap;
  22548. this.emissiveIntensity = source.emissiveIntensity;
  22549. this.bumpMap = source.bumpMap;
  22550. this.bumpScale = source.bumpScale;
  22551. this.normalMap = source.normalMap;
  22552. this.normalMapType = source.normalMapType;
  22553. this.normalScale.copy( source.normalScale );
  22554. this.displacementMap = source.displacementMap;
  22555. this.displacementScale = source.displacementScale;
  22556. this.displacementBias = source.displacementBias;
  22557. this.roughnessMap = source.roughnessMap;
  22558. this.metalnessMap = source.metalnessMap;
  22559. this.alphaMap = source.alphaMap;
  22560. this.envMap = source.envMap;
  22561. this.envMapIntensity = source.envMapIntensity;
  22562. this.wireframe = source.wireframe;
  22563. this.wireframeLinewidth = source.wireframeLinewidth;
  22564. this.wireframeLinecap = source.wireframeLinecap;
  22565. this.wireframeLinejoin = source.wireframeLinejoin;
  22566. this.flatShading = source.flatShading;
  22567. this.fog = source.fog;
  22568. return this;
  22569. }
  22570. }
  22571. class MeshPhysicalMaterial extends MeshStandardMaterial {
  22572. constructor( parameters ) {
  22573. super();
  22574. this.isMeshPhysicalMaterial = true;
  22575. this.defines = {
  22576. 'STANDARD': '',
  22577. 'PHYSICAL': ''
  22578. };
  22579. this.type = 'MeshPhysicalMaterial';
  22580. this.clearcoatMap = null;
  22581. this.clearcoatRoughness = 0.0;
  22582. this.clearcoatRoughnessMap = null;
  22583. this.clearcoatNormalScale = new Vector2( 1, 1 );
  22584. this.clearcoatNormalMap = null;
  22585. this.ior = 1.5;
  22586. Object.defineProperty( this, 'reflectivity', {
  22587. get: function () {
  22588. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  22589. },
  22590. set: function ( reflectivity ) {
  22591. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  22592. }
  22593. } );
  22594. this.iridescenceMap = null;
  22595. this.iridescenceIOR = 1.3;
  22596. this.iridescenceThicknessRange = [ 100, 400 ];
  22597. this.iridescenceThicknessMap = null;
  22598. this.sheenColor = new Color( 0x000000 );
  22599. this.sheenColorMap = null;
  22600. this.sheenRoughness = 1.0;
  22601. this.sheenRoughnessMap = null;
  22602. this.transmissionMap = null;
  22603. this.thickness = 0;
  22604. this.thicknessMap = null;
  22605. this.attenuationDistance = Infinity;
  22606. this.attenuationColor = new Color( 1, 1, 1 );
  22607. this.specularIntensity = 1.0;
  22608. this.specularIntensityMap = null;
  22609. this.specularColor = new Color( 1, 1, 1 );
  22610. this.specularColorMap = null;
  22611. this._sheen = 0.0;
  22612. this._clearcoat = 0;
  22613. this._iridescence = 0;
  22614. this._transmission = 0;
  22615. this.setValues( parameters );
  22616. }
  22617. get sheen() {
  22618. return this._sheen;
  22619. }
  22620. set sheen( value ) {
  22621. if ( this._sheen > 0 !== value > 0 ) {
  22622. this.version ++;
  22623. }
  22624. this._sheen = value;
  22625. }
  22626. get clearcoat() {
  22627. return this._clearcoat;
  22628. }
  22629. set clearcoat( value ) {
  22630. if ( this._clearcoat > 0 !== value > 0 ) {
  22631. this.version ++;
  22632. }
  22633. this._clearcoat = value;
  22634. }
  22635. get iridescence() {
  22636. return this._iridescence;
  22637. }
  22638. set iridescence( value ) {
  22639. if ( this._iridescence > 0 !== value > 0 ) {
  22640. this.version ++;
  22641. }
  22642. this._iridescence = value;
  22643. }
  22644. get transmission() {
  22645. return this._transmission;
  22646. }
  22647. set transmission( value ) {
  22648. if ( this._transmission > 0 !== value > 0 ) {
  22649. this.version ++;
  22650. }
  22651. this._transmission = value;
  22652. }
  22653. copy( source ) {
  22654. super.copy( source );
  22655. this.defines = {
  22656. 'STANDARD': '',
  22657. 'PHYSICAL': ''
  22658. };
  22659. this.clearcoat = source.clearcoat;
  22660. this.clearcoatMap = source.clearcoatMap;
  22661. this.clearcoatRoughness = source.clearcoatRoughness;
  22662. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  22663. this.clearcoatNormalMap = source.clearcoatNormalMap;
  22664. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  22665. this.ior = source.ior;
  22666. this.iridescence = source.iridescence;
  22667. this.iridescenceMap = source.iridescenceMap;
  22668. this.iridescenceIOR = source.iridescenceIOR;
  22669. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  22670. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  22671. this.sheen = source.sheen;
  22672. this.sheenColor.copy( source.sheenColor );
  22673. this.sheenColorMap = source.sheenColorMap;
  22674. this.sheenRoughness = source.sheenRoughness;
  22675. this.sheenRoughnessMap = source.sheenRoughnessMap;
  22676. this.transmission = source.transmission;
  22677. this.transmissionMap = source.transmissionMap;
  22678. this.thickness = source.thickness;
  22679. this.thicknessMap = source.thicknessMap;
  22680. this.attenuationDistance = source.attenuationDistance;
  22681. this.attenuationColor.copy( source.attenuationColor );
  22682. this.specularIntensity = source.specularIntensity;
  22683. this.specularIntensityMap = source.specularIntensityMap;
  22684. this.specularColor.copy( source.specularColor );
  22685. this.specularColorMap = source.specularColorMap;
  22686. return this;
  22687. }
  22688. }
  22689. class MeshPhongMaterial extends Material {
  22690. constructor( parameters ) {
  22691. super();
  22692. this.isMeshPhongMaterial = true;
  22693. this.type = 'MeshPhongMaterial';
  22694. this.color = new Color( 0xffffff ); // diffuse
  22695. this.specular = new Color( 0x111111 );
  22696. this.shininess = 30;
  22697. this.map = null;
  22698. this.lightMap = null;
  22699. this.lightMapIntensity = 1.0;
  22700. this.aoMap = null;
  22701. this.aoMapIntensity = 1.0;
  22702. this.emissive = new Color( 0x000000 );
  22703. this.emissiveIntensity = 1.0;
  22704. this.emissiveMap = null;
  22705. this.bumpMap = null;
  22706. this.bumpScale = 1;
  22707. this.normalMap = null;
  22708. this.normalMapType = TangentSpaceNormalMap;
  22709. this.normalScale = new Vector2( 1, 1 );
  22710. this.displacementMap = null;
  22711. this.displacementScale = 1;
  22712. this.displacementBias = 0;
  22713. this.specularMap = null;
  22714. this.alphaMap = null;
  22715. this.envMap = null;
  22716. this.combine = MultiplyOperation;
  22717. this.reflectivity = 1;
  22718. this.refractionRatio = 0.98;
  22719. this.wireframe = false;
  22720. this.wireframeLinewidth = 1;
  22721. this.wireframeLinecap = 'round';
  22722. this.wireframeLinejoin = 'round';
  22723. this.flatShading = false;
  22724. this.fog = true;
  22725. this.setValues( parameters );
  22726. }
  22727. copy( source ) {
  22728. super.copy( source );
  22729. this.color.copy( source.color );
  22730. this.specular.copy( source.specular );
  22731. this.shininess = source.shininess;
  22732. this.map = source.map;
  22733. this.lightMap = source.lightMap;
  22734. this.lightMapIntensity = source.lightMapIntensity;
  22735. this.aoMap = source.aoMap;
  22736. this.aoMapIntensity = source.aoMapIntensity;
  22737. this.emissive.copy( source.emissive );
  22738. this.emissiveMap = source.emissiveMap;
  22739. this.emissiveIntensity = source.emissiveIntensity;
  22740. this.bumpMap = source.bumpMap;
  22741. this.bumpScale = source.bumpScale;
  22742. this.normalMap = source.normalMap;
  22743. this.normalMapType = source.normalMapType;
  22744. this.normalScale.copy( source.normalScale );
  22745. this.displacementMap = source.displacementMap;
  22746. this.displacementScale = source.displacementScale;
  22747. this.displacementBias = source.displacementBias;
  22748. this.specularMap = source.specularMap;
  22749. this.alphaMap = source.alphaMap;
  22750. this.envMap = source.envMap;
  22751. this.combine = source.combine;
  22752. this.reflectivity = source.reflectivity;
  22753. this.refractionRatio = source.refractionRatio;
  22754. this.wireframe = source.wireframe;
  22755. this.wireframeLinewidth = source.wireframeLinewidth;
  22756. this.wireframeLinecap = source.wireframeLinecap;
  22757. this.wireframeLinejoin = source.wireframeLinejoin;
  22758. this.flatShading = source.flatShading;
  22759. this.fog = source.fog;
  22760. return this;
  22761. }
  22762. }
  22763. class MeshToonMaterial extends Material {
  22764. constructor( parameters ) {
  22765. super();
  22766. this.isMeshToonMaterial = true;
  22767. this.defines = { 'TOON': '' };
  22768. this.type = 'MeshToonMaterial';
  22769. this.color = new Color( 0xffffff );
  22770. this.map = null;
  22771. this.gradientMap = null;
  22772. this.lightMap = null;
  22773. this.lightMapIntensity = 1.0;
  22774. this.aoMap = null;
  22775. this.aoMapIntensity = 1.0;
  22776. this.emissive = new Color( 0x000000 );
  22777. this.emissiveIntensity = 1.0;
  22778. this.emissiveMap = null;
  22779. this.bumpMap = null;
  22780. this.bumpScale = 1;
  22781. this.normalMap = null;
  22782. this.normalMapType = TangentSpaceNormalMap;
  22783. this.normalScale = new Vector2( 1, 1 );
  22784. this.displacementMap = null;
  22785. this.displacementScale = 1;
  22786. this.displacementBias = 0;
  22787. this.alphaMap = null;
  22788. this.wireframe = false;
  22789. this.wireframeLinewidth = 1;
  22790. this.wireframeLinecap = 'round';
  22791. this.wireframeLinejoin = 'round';
  22792. this.fog = true;
  22793. this.setValues( parameters );
  22794. }
  22795. copy( source ) {
  22796. super.copy( source );
  22797. this.color.copy( source.color );
  22798. this.map = source.map;
  22799. this.gradientMap = source.gradientMap;
  22800. this.lightMap = source.lightMap;
  22801. this.lightMapIntensity = source.lightMapIntensity;
  22802. this.aoMap = source.aoMap;
  22803. this.aoMapIntensity = source.aoMapIntensity;
  22804. this.emissive.copy( source.emissive );
  22805. this.emissiveMap = source.emissiveMap;
  22806. this.emissiveIntensity = source.emissiveIntensity;
  22807. this.bumpMap = source.bumpMap;
  22808. this.bumpScale = source.bumpScale;
  22809. this.normalMap = source.normalMap;
  22810. this.normalMapType = source.normalMapType;
  22811. this.normalScale.copy( source.normalScale );
  22812. this.displacementMap = source.displacementMap;
  22813. this.displacementScale = source.displacementScale;
  22814. this.displacementBias = source.displacementBias;
  22815. this.alphaMap = source.alphaMap;
  22816. this.wireframe = source.wireframe;
  22817. this.wireframeLinewidth = source.wireframeLinewidth;
  22818. this.wireframeLinecap = source.wireframeLinecap;
  22819. this.wireframeLinejoin = source.wireframeLinejoin;
  22820. this.fog = source.fog;
  22821. return this;
  22822. }
  22823. }
  22824. class MeshNormalMaterial extends Material {
  22825. constructor( parameters ) {
  22826. super();
  22827. this.isMeshNormalMaterial = true;
  22828. this.type = 'MeshNormalMaterial';
  22829. this.bumpMap = null;
  22830. this.bumpScale = 1;
  22831. this.normalMap = null;
  22832. this.normalMapType = TangentSpaceNormalMap;
  22833. this.normalScale = new Vector2( 1, 1 );
  22834. this.displacementMap = null;
  22835. this.displacementScale = 1;
  22836. this.displacementBias = 0;
  22837. this.wireframe = false;
  22838. this.wireframeLinewidth = 1;
  22839. this.flatShading = false;
  22840. this.setValues( parameters );
  22841. }
  22842. copy( source ) {
  22843. super.copy( source );
  22844. this.bumpMap = source.bumpMap;
  22845. this.bumpScale = source.bumpScale;
  22846. this.normalMap = source.normalMap;
  22847. this.normalMapType = source.normalMapType;
  22848. this.normalScale.copy( source.normalScale );
  22849. this.displacementMap = source.displacementMap;
  22850. this.displacementScale = source.displacementScale;
  22851. this.displacementBias = source.displacementBias;
  22852. this.wireframe = source.wireframe;
  22853. this.wireframeLinewidth = source.wireframeLinewidth;
  22854. this.flatShading = source.flatShading;
  22855. return this;
  22856. }
  22857. }
  22858. class MeshLambertMaterial extends Material {
  22859. constructor( parameters ) {
  22860. super();
  22861. this.isMeshLambertMaterial = true;
  22862. this.type = 'MeshLambertMaterial';
  22863. this.color = new Color( 0xffffff ); // diffuse
  22864. this.map = null;
  22865. this.lightMap = null;
  22866. this.lightMapIntensity = 1.0;
  22867. this.aoMap = null;
  22868. this.aoMapIntensity = 1.0;
  22869. this.emissive = new Color( 0x000000 );
  22870. this.emissiveIntensity = 1.0;
  22871. this.emissiveMap = null;
  22872. this.bumpMap = null;
  22873. this.bumpScale = 1;
  22874. this.normalMap = null;
  22875. this.normalMapType = TangentSpaceNormalMap;
  22876. this.normalScale = new Vector2( 1, 1 );
  22877. this.displacementMap = null;
  22878. this.displacementScale = 1;
  22879. this.displacementBias = 0;
  22880. this.specularMap = null;
  22881. this.alphaMap = null;
  22882. this.envMap = null;
  22883. this.combine = MultiplyOperation;
  22884. this.reflectivity = 1;
  22885. this.refractionRatio = 0.98;
  22886. this.wireframe = false;
  22887. this.wireframeLinewidth = 1;
  22888. this.wireframeLinecap = 'round';
  22889. this.wireframeLinejoin = 'round';
  22890. this.flatShading = false;
  22891. this.fog = true;
  22892. this.setValues( parameters );
  22893. }
  22894. copy( source ) {
  22895. super.copy( source );
  22896. this.color.copy( source.color );
  22897. this.map = source.map;
  22898. this.lightMap = source.lightMap;
  22899. this.lightMapIntensity = source.lightMapIntensity;
  22900. this.aoMap = source.aoMap;
  22901. this.aoMapIntensity = source.aoMapIntensity;
  22902. this.emissive.copy( source.emissive );
  22903. this.emissiveMap = source.emissiveMap;
  22904. this.emissiveIntensity = source.emissiveIntensity;
  22905. this.bumpMap = source.bumpMap;
  22906. this.bumpScale = source.bumpScale;
  22907. this.normalMap = source.normalMap;
  22908. this.normalMapType = source.normalMapType;
  22909. this.normalScale.copy( source.normalScale );
  22910. this.displacementMap = source.displacementMap;
  22911. this.displacementScale = source.displacementScale;
  22912. this.displacementBias = source.displacementBias;
  22913. this.specularMap = source.specularMap;
  22914. this.alphaMap = source.alphaMap;
  22915. this.envMap = source.envMap;
  22916. this.combine = source.combine;
  22917. this.reflectivity = source.reflectivity;
  22918. this.refractionRatio = source.refractionRatio;
  22919. this.wireframe = source.wireframe;
  22920. this.wireframeLinewidth = source.wireframeLinewidth;
  22921. this.wireframeLinecap = source.wireframeLinecap;
  22922. this.wireframeLinejoin = source.wireframeLinejoin;
  22923. this.flatShading = source.flatShading;
  22924. this.fog = source.fog;
  22925. return this;
  22926. }
  22927. }
  22928. class MeshMatcapMaterial extends Material {
  22929. constructor( parameters ) {
  22930. super();
  22931. this.isMeshMatcapMaterial = true;
  22932. this.defines = { 'MATCAP': '' };
  22933. this.type = 'MeshMatcapMaterial';
  22934. this.color = new Color( 0xffffff ); // diffuse
  22935. this.matcap = null;
  22936. this.map = null;
  22937. this.bumpMap = null;
  22938. this.bumpScale = 1;
  22939. this.normalMap = null;
  22940. this.normalMapType = TangentSpaceNormalMap;
  22941. this.normalScale = new Vector2( 1, 1 );
  22942. this.displacementMap = null;
  22943. this.displacementScale = 1;
  22944. this.displacementBias = 0;
  22945. this.alphaMap = null;
  22946. this.flatShading = false;
  22947. this.fog = true;
  22948. this.setValues( parameters );
  22949. }
  22950. copy( source ) {
  22951. super.copy( source );
  22952. this.defines = { 'MATCAP': '' };
  22953. this.color.copy( source.color );
  22954. this.matcap = source.matcap;
  22955. this.map = source.map;
  22956. this.bumpMap = source.bumpMap;
  22957. this.bumpScale = source.bumpScale;
  22958. this.normalMap = source.normalMap;
  22959. this.normalMapType = source.normalMapType;
  22960. this.normalScale.copy( source.normalScale );
  22961. this.displacementMap = source.displacementMap;
  22962. this.displacementScale = source.displacementScale;
  22963. this.displacementBias = source.displacementBias;
  22964. this.alphaMap = source.alphaMap;
  22965. this.flatShading = source.flatShading;
  22966. this.fog = source.fog;
  22967. return this;
  22968. }
  22969. }
  22970. class LineDashedMaterial extends LineBasicMaterial {
  22971. constructor( parameters ) {
  22972. super();
  22973. this.isLineDashedMaterial = true;
  22974. this.type = 'LineDashedMaterial';
  22975. this.scale = 1;
  22976. this.dashSize = 3;
  22977. this.gapSize = 1;
  22978. this.setValues( parameters );
  22979. }
  22980. copy( source ) {
  22981. super.copy( source );
  22982. this.scale = source.scale;
  22983. this.dashSize = source.dashSize;
  22984. this.gapSize = source.gapSize;
  22985. return this;
  22986. }
  22987. }
  22988. // same as Array.prototype.slice, but also works on typed arrays
  22989. function arraySlice( array, from, to ) {
  22990. if ( isTypedArray( array ) ) {
  22991. // in ios9 array.subarray(from, undefined) will return empty array
  22992. // but array.subarray(from) or array.subarray(from, len) is correct
  22993. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  22994. }
  22995. return array.slice( from, to );
  22996. }
  22997. // converts an array to a specific type
  22998. function convertArray( array, type, forceClone ) {
  22999. if ( ! array || // let 'undefined' and 'null' pass
  23000. ! forceClone && array.constructor === type ) return array;
  23001. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  23002. return new type( array ); // create typed array
  23003. }
  23004. return Array.prototype.slice.call( array ); // create Array
  23005. }
  23006. function isTypedArray( object ) {
  23007. return ArrayBuffer.isView( object ) &&
  23008. ! ( object instanceof DataView );
  23009. }
  23010. // returns an array by which times and values can be sorted
  23011. function getKeyframeOrder( times ) {
  23012. function compareTime( i, j ) {
  23013. return times[ i ] - times[ j ];
  23014. }
  23015. const n = times.length;
  23016. const result = new Array( n );
  23017. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  23018. result.sort( compareTime );
  23019. return result;
  23020. }
  23021. // uses the array previously returned by 'getKeyframeOrder' to sort data
  23022. function sortedArray( values, stride, order ) {
  23023. const nValues = values.length;
  23024. const result = new values.constructor( nValues );
  23025. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  23026. const srcOffset = order[ i ] * stride;
  23027. for ( let j = 0; j !== stride; ++ j ) {
  23028. result[ dstOffset ++ ] = values[ srcOffset + j ];
  23029. }
  23030. }
  23031. return result;
  23032. }
  23033. // function for parsing AOS keyframe formats
  23034. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  23035. let i = 1, key = jsonKeys[ 0 ];
  23036. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  23037. key = jsonKeys[ i ++ ];
  23038. }
  23039. if ( key === undefined ) return; // no data
  23040. let value = key[ valuePropertyName ];
  23041. if ( value === undefined ) return; // no data
  23042. if ( Array.isArray( value ) ) {
  23043. do {
  23044. value = key[ valuePropertyName ];
  23045. if ( value !== undefined ) {
  23046. times.push( key.time );
  23047. values.push.apply( values, value ); // push all elements
  23048. }
  23049. key = jsonKeys[ i ++ ];
  23050. } while ( key !== undefined );
  23051. } else if ( value.toArray !== undefined ) {
  23052. // ...assume THREE.Math-ish
  23053. do {
  23054. value = key[ valuePropertyName ];
  23055. if ( value !== undefined ) {
  23056. times.push( key.time );
  23057. value.toArray( values, values.length );
  23058. }
  23059. key = jsonKeys[ i ++ ];
  23060. } while ( key !== undefined );
  23061. } else {
  23062. // otherwise push as-is
  23063. do {
  23064. value = key[ valuePropertyName ];
  23065. if ( value !== undefined ) {
  23066. times.push( key.time );
  23067. values.push( value );
  23068. }
  23069. key = jsonKeys[ i ++ ];
  23070. } while ( key !== undefined );
  23071. }
  23072. }
  23073. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  23074. const clip = sourceClip.clone();
  23075. clip.name = name;
  23076. const tracks = [];
  23077. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23078. const track = clip.tracks[ i ];
  23079. const valueSize = track.getValueSize();
  23080. const times = [];
  23081. const values = [];
  23082. for ( let j = 0; j < track.times.length; ++ j ) {
  23083. const frame = track.times[ j ] * fps;
  23084. if ( frame < startFrame || frame >= endFrame ) continue;
  23085. times.push( track.times[ j ] );
  23086. for ( let k = 0; k < valueSize; ++ k ) {
  23087. values.push( track.values[ j * valueSize + k ] );
  23088. }
  23089. }
  23090. if ( times.length === 0 ) continue;
  23091. track.times = convertArray( times, track.times.constructor );
  23092. track.values = convertArray( values, track.values.constructor );
  23093. tracks.push( track );
  23094. }
  23095. clip.tracks = tracks;
  23096. // find minimum .times value across all tracks in the trimmed clip
  23097. let minStartTime = Infinity;
  23098. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23099. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  23100. minStartTime = clip.tracks[ i ].times[ 0 ];
  23101. }
  23102. }
  23103. // shift all tracks such that clip begins at t=0
  23104. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  23105. clip.tracks[ i ].shift( - 1 * minStartTime );
  23106. }
  23107. clip.resetDuration();
  23108. return clip;
  23109. }
  23110. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  23111. if ( fps <= 0 ) fps = 30;
  23112. const numTracks = referenceClip.tracks.length;
  23113. const referenceTime = referenceFrame / fps;
  23114. // Make each track's values relative to the values at the reference frame
  23115. for ( let i = 0; i < numTracks; ++ i ) {
  23116. const referenceTrack = referenceClip.tracks[ i ];
  23117. const referenceTrackType = referenceTrack.ValueTypeName;
  23118. // Skip this track if it's non-numeric
  23119. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  23120. // Find the track in the target clip whose name and type matches the reference track
  23121. const targetTrack = targetClip.tracks.find( function ( track ) {
  23122. return track.name === referenceTrack.name
  23123. && track.ValueTypeName === referenceTrackType;
  23124. } );
  23125. if ( targetTrack === undefined ) continue;
  23126. let referenceOffset = 0;
  23127. const referenceValueSize = referenceTrack.getValueSize();
  23128. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  23129. referenceOffset = referenceValueSize / 3;
  23130. }
  23131. let targetOffset = 0;
  23132. const targetValueSize = targetTrack.getValueSize();
  23133. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  23134. targetOffset = targetValueSize / 3;
  23135. }
  23136. const lastIndex = referenceTrack.times.length - 1;
  23137. let referenceValue;
  23138. // Find the value to subtract out of the track
  23139. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  23140. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  23141. const startIndex = referenceOffset;
  23142. const endIndex = referenceValueSize - referenceOffset;
  23143. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  23144. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  23145. // Reference frame is after the last keyframe, so just use the last keyframe
  23146. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  23147. const endIndex = startIndex + referenceValueSize - referenceOffset;
  23148. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  23149. } else {
  23150. // Interpolate to the reference value
  23151. const interpolant = referenceTrack.createInterpolant();
  23152. const startIndex = referenceOffset;
  23153. const endIndex = referenceValueSize - referenceOffset;
  23154. interpolant.evaluate( referenceTime );
  23155. referenceValue = arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  23156. }
  23157. // Conjugate the quaternion
  23158. if ( referenceTrackType === 'quaternion' ) {
  23159. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  23160. referenceQuat.toArray( referenceValue );
  23161. }
  23162. // Subtract the reference value from all of the track values
  23163. const numTimes = targetTrack.times.length;
  23164. for ( let j = 0; j < numTimes; ++ j ) {
  23165. const valueStart = j * targetValueSize + targetOffset;
  23166. if ( referenceTrackType === 'quaternion' ) {
  23167. // Multiply the conjugate for quaternion track types
  23168. Quaternion.multiplyQuaternionsFlat(
  23169. targetTrack.values,
  23170. valueStart,
  23171. referenceValue,
  23172. 0,
  23173. targetTrack.values,
  23174. valueStart
  23175. );
  23176. } else {
  23177. const valueEnd = targetValueSize - targetOffset * 2;
  23178. // Subtract each value for all other numeric track types
  23179. for ( let k = 0; k < valueEnd; ++ k ) {
  23180. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  23181. }
  23182. }
  23183. }
  23184. }
  23185. targetClip.blendMode = AdditiveAnimationBlendMode;
  23186. return targetClip;
  23187. }
  23188. const AnimationUtils = {
  23189. arraySlice: arraySlice,
  23190. convertArray: convertArray,
  23191. isTypedArray: isTypedArray,
  23192. getKeyframeOrder: getKeyframeOrder,
  23193. sortedArray: sortedArray,
  23194. flattenJSON: flattenJSON,
  23195. subclip: subclip,
  23196. makeClipAdditive: makeClipAdditive
  23197. };
  23198. /**
  23199. * Abstract base class of interpolants over parametric samples.
  23200. *
  23201. * The parameter domain is one dimensional, typically the time or a path
  23202. * along a curve defined by the data.
  23203. *
  23204. * The sample values can have any dimensionality and derived classes may
  23205. * apply special interpretations to the data.
  23206. *
  23207. * This class provides the interval seek in a Template Method, deferring
  23208. * the actual interpolation to derived classes.
  23209. *
  23210. * Time complexity is O(1) for linear access crossing at most two points
  23211. * and O(log N) for random access, where N is the number of positions.
  23212. *
  23213. * References:
  23214. *
  23215. * http://www.oodesign.com/template-method-pattern.html
  23216. *
  23217. */
  23218. class Interpolant {
  23219. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23220. this.parameterPositions = parameterPositions;
  23221. this._cachedIndex = 0;
  23222. this.resultBuffer = resultBuffer !== undefined ?
  23223. resultBuffer : new sampleValues.constructor( sampleSize );
  23224. this.sampleValues = sampleValues;
  23225. this.valueSize = sampleSize;
  23226. this.settings = null;
  23227. this.DefaultSettings_ = {};
  23228. }
  23229. evaluate( t ) {
  23230. const pp = this.parameterPositions;
  23231. let i1 = this._cachedIndex,
  23232. t1 = pp[ i1 ],
  23233. t0 = pp[ i1 - 1 ];
  23234. validate_interval: {
  23235. seek: {
  23236. let right;
  23237. linear_scan: {
  23238. //- See http://jsperf.com/comparison-to-undefined/3
  23239. //- slower code:
  23240. //-
  23241. //- if ( t >= t1 || t1 === undefined ) {
  23242. forward_scan: if ( ! ( t < t1 ) ) {
  23243. for ( let giveUpAt = i1 + 2; ; ) {
  23244. if ( t1 === undefined ) {
  23245. if ( t < t0 ) break forward_scan;
  23246. // after end
  23247. i1 = pp.length;
  23248. this._cachedIndex = i1;
  23249. return this.copySampleValue_( i1 - 1 );
  23250. }
  23251. if ( i1 === giveUpAt ) break; // this loop
  23252. t0 = t1;
  23253. t1 = pp[ ++ i1 ];
  23254. if ( t < t1 ) {
  23255. // we have arrived at the sought interval
  23256. break seek;
  23257. }
  23258. }
  23259. // prepare binary search on the right side of the index
  23260. right = pp.length;
  23261. break linear_scan;
  23262. }
  23263. //- slower code:
  23264. //- if ( t < t0 || t0 === undefined ) {
  23265. if ( ! ( t >= t0 ) ) {
  23266. // looping?
  23267. const t1global = pp[ 1 ];
  23268. if ( t < t1global ) {
  23269. i1 = 2; // + 1, using the scan for the details
  23270. t0 = t1global;
  23271. }
  23272. // linear reverse scan
  23273. for ( let giveUpAt = i1 - 2; ; ) {
  23274. if ( t0 === undefined ) {
  23275. // before start
  23276. this._cachedIndex = 0;
  23277. return this.copySampleValue_( 0 );
  23278. }
  23279. if ( i1 === giveUpAt ) break; // this loop
  23280. t1 = t0;
  23281. t0 = pp[ -- i1 - 1 ];
  23282. if ( t >= t0 ) {
  23283. // we have arrived at the sought interval
  23284. break seek;
  23285. }
  23286. }
  23287. // prepare binary search on the left side of the index
  23288. right = i1;
  23289. i1 = 0;
  23290. break linear_scan;
  23291. }
  23292. // the interval is valid
  23293. break validate_interval;
  23294. } // linear scan
  23295. // binary search
  23296. while ( i1 < right ) {
  23297. const mid = ( i1 + right ) >>> 1;
  23298. if ( t < pp[ mid ] ) {
  23299. right = mid;
  23300. } else {
  23301. i1 = mid + 1;
  23302. }
  23303. }
  23304. t1 = pp[ i1 ];
  23305. t0 = pp[ i1 - 1 ];
  23306. // check boundary cases, again
  23307. if ( t0 === undefined ) {
  23308. this._cachedIndex = 0;
  23309. return this.copySampleValue_( 0 );
  23310. }
  23311. if ( t1 === undefined ) {
  23312. i1 = pp.length;
  23313. this._cachedIndex = i1;
  23314. return this.copySampleValue_( i1 - 1 );
  23315. }
  23316. } // seek
  23317. this._cachedIndex = i1;
  23318. this.intervalChanged_( i1, t0, t1 );
  23319. } // validate_interval
  23320. return this.interpolate_( i1, t0, t, t1 );
  23321. }
  23322. getSettings_() {
  23323. return this.settings || this.DefaultSettings_;
  23324. }
  23325. copySampleValue_( index ) {
  23326. // copies a sample value to the result buffer
  23327. const result = this.resultBuffer,
  23328. values = this.sampleValues,
  23329. stride = this.valueSize,
  23330. offset = index * stride;
  23331. for ( let i = 0; i !== stride; ++ i ) {
  23332. result[ i ] = values[ offset + i ];
  23333. }
  23334. return result;
  23335. }
  23336. // Template methods for derived classes:
  23337. interpolate_( /* i1, t0, t, t1 */ ) {
  23338. throw new Error( 'call to abstract method' );
  23339. // implementations shall return this.resultBuffer
  23340. }
  23341. intervalChanged_( /* i1, t0, t1 */ ) {
  23342. // empty
  23343. }
  23344. }
  23345. /**
  23346. * Fast and simple cubic spline interpolant.
  23347. *
  23348. * It was derived from a Hermitian construction setting the first derivative
  23349. * at each sample position to the linear slope between neighboring positions
  23350. * over their parameter interval.
  23351. */
  23352. class CubicInterpolant extends Interpolant {
  23353. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23354. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23355. this._weightPrev = - 0;
  23356. this._offsetPrev = - 0;
  23357. this._weightNext = - 0;
  23358. this._offsetNext = - 0;
  23359. this.DefaultSettings_ = {
  23360. endingStart: ZeroCurvatureEnding,
  23361. endingEnd: ZeroCurvatureEnding
  23362. };
  23363. }
  23364. intervalChanged_( i1, t0, t1 ) {
  23365. const pp = this.parameterPositions;
  23366. let iPrev = i1 - 2,
  23367. iNext = i1 + 1,
  23368. tPrev = pp[ iPrev ],
  23369. tNext = pp[ iNext ];
  23370. if ( tPrev === undefined ) {
  23371. switch ( this.getSettings_().endingStart ) {
  23372. case ZeroSlopeEnding:
  23373. // f'(t0) = 0
  23374. iPrev = i1;
  23375. tPrev = 2 * t0 - t1;
  23376. break;
  23377. case WrapAroundEnding:
  23378. // use the other end of the curve
  23379. iPrev = pp.length - 2;
  23380. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  23381. break;
  23382. default: // ZeroCurvatureEnding
  23383. // f''(t0) = 0 a.k.a. Natural Spline
  23384. iPrev = i1;
  23385. tPrev = t1;
  23386. }
  23387. }
  23388. if ( tNext === undefined ) {
  23389. switch ( this.getSettings_().endingEnd ) {
  23390. case ZeroSlopeEnding:
  23391. // f'(tN) = 0
  23392. iNext = i1;
  23393. tNext = 2 * t1 - t0;
  23394. break;
  23395. case WrapAroundEnding:
  23396. // use the other end of the curve
  23397. iNext = 1;
  23398. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  23399. break;
  23400. default: // ZeroCurvatureEnding
  23401. // f''(tN) = 0, a.k.a. Natural Spline
  23402. iNext = i1 - 1;
  23403. tNext = t0;
  23404. }
  23405. }
  23406. const halfDt = ( t1 - t0 ) * 0.5,
  23407. stride = this.valueSize;
  23408. this._weightPrev = halfDt / ( t0 - tPrev );
  23409. this._weightNext = halfDt / ( tNext - t1 );
  23410. this._offsetPrev = iPrev * stride;
  23411. this._offsetNext = iNext * stride;
  23412. }
  23413. interpolate_( i1, t0, t, t1 ) {
  23414. const result = this.resultBuffer,
  23415. values = this.sampleValues,
  23416. stride = this.valueSize,
  23417. o1 = i1 * stride, o0 = o1 - stride,
  23418. oP = this._offsetPrev, oN = this._offsetNext,
  23419. wP = this._weightPrev, wN = this._weightNext,
  23420. p = ( t - t0 ) / ( t1 - t0 ),
  23421. pp = p * p,
  23422. ppp = pp * p;
  23423. // evaluate polynomials
  23424. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  23425. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  23426. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  23427. const sN = wN * ppp - wN * pp;
  23428. // combine data linearly
  23429. for ( let i = 0; i !== stride; ++ i ) {
  23430. result[ i ] =
  23431. sP * values[ oP + i ] +
  23432. s0 * values[ o0 + i ] +
  23433. s1 * values[ o1 + i ] +
  23434. sN * values[ oN + i ];
  23435. }
  23436. return result;
  23437. }
  23438. }
  23439. class LinearInterpolant extends Interpolant {
  23440. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23441. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23442. }
  23443. interpolate_( i1, t0, t, t1 ) {
  23444. const result = this.resultBuffer,
  23445. values = this.sampleValues,
  23446. stride = this.valueSize,
  23447. offset1 = i1 * stride,
  23448. offset0 = offset1 - stride,
  23449. weight1 = ( t - t0 ) / ( t1 - t0 ),
  23450. weight0 = 1 - weight1;
  23451. for ( let i = 0; i !== stride; ++ i ) {
  23452. result[ i ] =
  23453. values[ offset0 + i ] * weight0 +
  23454. values[ offset1 + i ] * weight1;
  23455. }
  23456. return result;
  23457. }
  23458. }
  23459. /**
  23460. *
  23461. * Interpolant that evaluates to the sample value at the position preceding
  23462. * the parameter.
  23463. */
  23464. class DiscreteInterpolant extends Interpolant {
  23465. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23466. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23467. }
  23468. interpolate_( i1 /*, t0, t, t1 */ ) {
  23469. return this.copySampleValue_( i1 - 1 );
  23470. }
  23471. }
  23472. class KeyframeTrack {
  23473. constructor( name, times, values, interpolation ) {
  23474. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  23475. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  23476. this.name = name;
  23477. this.times = convertArray( times, this.TimeBufferType );
  23478. this.values = convertArray( values, this.ValueBufferType );
  23479. this.setInterpolation( interpolation || this.DefaultInterpolation );
  23480. }
  23481. // Serialization (in static context, because of constructor invocation
  23482. // and automatic invocation of .toJSON):
  23483. static toJSON( track ) {
  23484. const trackType = track.constructor;
  23485. let json;
  23486. // derived classes can define a static toJSON method
  23487. if ( trackType.toJSON !== this.toJSON ) {
  23488. json = trackType.toJSON( track );
  23489. } else {
  23490. // by default, we assume the data can be serialized as-is
  23491. json = {
  23492. 'name': track.name,
  23493. 'times': convertArray( track.times, Array ),
  23494. 'values': convertArray( track.values, Array )
  23495. };
  23496. const interpolation = track.getInterpolation();
  23497. if ( interpolation !== track.DefaultInterpolation ) {
  23498. json.interpolation = interpolation;
  23499. }
  23500. }
  23501. json.type = track.ValueTypeName; // mandatory
  23502. return json;
  23503. }
  23504. InterpolantFactoryMethodDiscrete( result ) {
  23505. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  23506. }
  23507. InterpolantFactoryMethodLinear( result ) {
  23508. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23509. }
  23510. InterpolantFactoryMethodSmooth( result ) {
  23511. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  23512. }
  23513. setInterpolation( interpolation ) {
  23514. let factoryMethod;
  23515. switch ( interpolation ) {
  23516. case InterpolateDiscrete:
  23517. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  23518. break;
  23519. case InterpolateLinear:
  23520. factoryMethod = this.InterpolantFactoryMethodLinear;
  23521. break;
  23522. case InterpolateSmooth:
  23523. factoryMethod = this.InterpolantFactoryMethodSmooth;
  23524. break;
  23525. }
  23526. if ( factoryMethod === undefined ) {
  23527. const message = 'unsupported interpolation for ' +
  23528. this.ValueTypeName + ' keyframe track named ' + this.name;
  23529. if ( this.createInterpolant === undefined ) {
  23530. // fall back to default, unless the default itself is messed up
  23531. if ( interpolation !== this.DefaultInterpolation ) {
  23532. this.setInterpolation( this.DefaultInterpolation );
  23533. } else {
  23534. throw new Error( message ); // fatal, in this case
  23535. }
  23536. }
  23537. console.warn( 'THREE.KeyframeTrack:', message );
  23538. return this;
  23539. }
  23540. this.createInterpolant = factoryMethod;
  23541. return this;
  23542. }
  23543. getInterpolation() {
  23544. switch ( this.createInterpolant ) {
  23545. case this.InterpolantFactoryMethodDiscrete:
  23546. return InterpolateDiscrete;
  23547. case this.InterpolantFactoryMethodLinear:
  23548. return InterpolateLinear;
  23549. case this.InterpolantFactoryMethodSmooth:
  23550. return InterpolateSmooth;
  23551. }
  23552. }
  23553. getValueSize() {
  23554. return this.values.length / this.times.length;
  23555. }
  23556. // move all keyframes either forwards or backwards in time
  23557. shift( timeOffset ) {
  23558. if ( timeOffset !== 0.0 ) {
  23559. const times = this.times;
  23560. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23561. times[ i ] += timeOffset;
  23562. }
  23563. }
  23564. return this;
  23565. }
  23566. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  23567. scale( timeScale ) {
  23568. if ( timeScale !== 1.0 ) {
  23569. const times = this.times;
  23570. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  23571. times[ i ] *= timeScale;
  23572. }
  23573. }
  23574. return this;
  23575. }
  23576. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  23577. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  23578. trim( startTime, endTime ) {
  23579. const times = this.times,
  23580. nKeys = times.length;
  23581. let from = 0,
  23582. to = nKeys - 1;
  23583. while ( from !== nKeys && times[ from ] < startTime ) {
  23584. ++ from;
  23585. }
  23586. while ( to !== - 1 && times[ to ] > endTime ) {
  23587. -- to;
  23588. }
  23589. ++ to; // inclusive -> exclusive bound
  23590. if ( from !== 0 || to !== nKeys ) {
  23591. // empty tracks are forbidden, so keep at least one keyframe
  23592. if ( from >= to ) {
  23593. to = Math.max( to, 1 );
  23594. from = to - 1;
  23595. }
  23596. const stride = this.getValueSize();
  23597. this.times = arraySlice( times, from, to );
  23598. this.values = arraySlice( this.values, from * stride, to * stride );
  23599. }
  23600. return this;
  23601. }
  23602. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  23603. validate() {
  23604. let valid = true;
  23605. const valueSize = this.getValueSize();
  23606. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  23607. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  23608. valid = false;
  23609. }
  23610. const times = this.times,
  23611. values = this.values,
  23612. nKeys = times.length;
  23613. if ( nKeys === 0 ) {
  23614. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  23615. valid = false;
  23616. }
  23617. let prevTime = null;
  23618. for ( let i = 0; i !== nKeys; i ++ ) {
  23619. const currTime = times[ i ];
  23620. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  23621. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  23622. valid = false;
  23623. break;
  23624. }
  23625. if ( prevTime !== null && prevTime > currTime ) {
  23626. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  23627. valid = false;
  23628. break;
  23629. }
  23630. prevTime = currTime;
  23631. }
  23632. if ( values !== undefined ) {
  23633. if ( isTypedArray( values ) ) {
  23634. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  23635. const value = values[ i ];
  23636. if ( isNaN( value ) ) {
  23637. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  23638. valid = false;
  23639. break;
  23640. }
  23641. }
  23642. }
  23643. }
  23644. return valid;
  23645. }
  23646. // removes equivalent sequential keys as common in morph target sequences
  23647. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  23648. optimize() {
  23649. // times or values may be shared with other tracks, so overwriting is unsafe
  23650. const times = arraySlice( this.times ),
  23651. values = arraySlice( this.values ),
  23652. stride = this.getValueSize(),
  23653. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  23654. lastIndex = times.length - 1;
  23655. let writeIndex = 1;
  23656. for ( let i = 1; i < lastIndex; ++ i ) {
  23657. let keep = false;
  23658. const time = times[ i ];
  23659. const timeNext = times[ i + 1 ];
  23660. // remove adjacent keyframes scheduled at the same time
  23661. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  23662. if ( ! smoothInterpolation ) {
  23663. // remove unnecessary keyframes same as their neighbors
  23664. const offset = i * stride,
  23665. offsetP = offset - stride,
  23666. offsetN = offset + stride;
  23667. for ( let j = 0; j !== stride; ++ j ) {
  23668. const value = values[ offset + j ];
  23669. if ( value !== values[ offsetP + j ] ||
  23670. value !== values[ offsetN + j ] ) {
  23671. keep = true;
  23672. break;
  23673. }
  23674. }
  23675. } else {
  23676. keep = true;
  23677. }
  23678. }
  23679. // in-place compaction
  23680. if ( keep ) {
  23681. if ( i !== writeIndex ) {
  23682. times[ writeIndex ] = times[ i ];
  23683. const readOffset = i * stride,
  23684. writeOffset = writeIndex * stride;
  23685. for ( let j = 0; j !== stride; ++ j ) {
  23686. values[ writeOffset + j ] = values[ readOffset + j ];
  23687. }
  23688. }
  23689. ++ writeIndex;
  23690. }
  23691. }
  23692. // flush last keyframe (compaction looks ahead)
  23693. if ( lastIndex > 0 ) {
  23694. times[ writeIndex ] = times[ lastIndex ];
  23695. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  23696. values[ writeOffset + j ] = values[ readOffset + j ];
  23697. }
  23698. ++ writeIndex;
  23699. }
  23700. if ( writeIndex !== times.length ) {
  23701. this.times = arraySlice( times, 0, writeIndex );
  23702. this.values = arraySlice( values, 0, writeIndex * stride );
  23703. } else {
  23704. this.times = times;
  23705. this.values = values;
  23706. }
  23707. return this;
  23708. }
  23709. clone() {
  23710. const times = arraySlice( this.times, 0 );
  23711. const values = arraySlice( this.values, 0 );
  23712. const TypedKeyframeTrack = this.constructor;
  23713. const track = new TypedKeyframeTrack( this.name, times, values );
  23714. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  23715. track.createInterpolant = this.createInterpolant;
  23716. return track;
  23717. }
  23718. }
  23719. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  23720. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  23721. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23722. /**
  23723. * A Track of Boolean keyframe values.
  23724. */
  23725. class BooleanKeyframeTrack extends KeyframeTrack {}
  23726. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  23727. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  23728. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23729. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23730. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23731. /**
  23732. * A Track of keyframe values that represent color.
  23733. */
  23734. class ColorKeyframeTrack extends KeyframeTrack {}
  23735. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  23736. /**
  23737. * A Track of numeric keyframe values.
  23738. */
  23739. class NumberKeyframeTrack extends KeyframeTrack {}
  23740. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  23741. /**
  23742. * Spherical linear unit quaternion interpolant.
  23743. */
  23744. class QuaternionLinearInterpolant extends Interpolant {
  23745. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23746. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23747. }
  23748. interpolate_( i1, t0, t, t1 ) {
  23749. const result = this.resultBuffer,
  23750. values = this.sampleValues,
  23751. stride = this.valueSize,
  23752. alpha = ( t - t0 ) / ( t1 - t0 );
  23753. let offset = i1 * stride;
  23754. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  23755. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  23756. }
  23757. return result;
  23758. }
  23759. }
  23760. /**
  23761. * A Track of quaternion keyframe values.
  23762. */
  23763. class QuaternionKeyframeTrack extends KeyframeTrack {
  23764. InterpolantFactoryMethodLinear( result ) {
  23765. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23766. }
  23767. }
  23768. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  23769. // ValueBufferType is inherited
  23770. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23771. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23772. /**
  23773. * A Track that interpolates Strings
  23774. */
  23775. class StringKeyframeTrack extends KeyframeTrack {}
  23776. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  23777. StringKeyframeTrack.prototype.ValueBufferType = Array;
  23778. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23779. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23780. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23781. /**
  23782. * A Track of vectored keyframe values.
  23783. */
  23784. class VectorKeyframeTrack extends KeyframeTrack {}
  23785. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  23786. class AnimationClip {
  23787. constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  23788. this.name = name;
  23789. this.tracks = tracks;
  23790. this.duration = duration;
  23791. this.blendMode = blendMode;
  23792. this.uuid = generateUUID();
  23793. // this means it should figure out its duration by scanning the tracks
  23794. if ( this.duration < 0 ) {
  23795. this.resetDuration();
  23796. }
  23797. }
  23798. static parse( json ) {
  23799. const tracks = [],
  23800. jsonTracks = json.tracks,
  23801. frameTime = 1.0 / ( json.fps || 1.0 );
  23802. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  23803. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  23804. }
  23805. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  23806. clip.uuid = json.uuid;
  23807. return clip;
  23808. }
  23809. static toJSON( clip ) {
  23810. const tracks = [],
  23811. clipTracks = clip.tracks;
  23812. const json = {
  23813. 'name': clip.name,
  23814. 'duration': clip.duration,
  23815. 'tracks': tracks,
  23816. 'uuid': clip.uuid,
  23817. 'blendMode': clip.blendMode
  23818. };
  23819. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  23820. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  23821. }
  23822. return json;
  23823. }
  23824. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  23825. const numMorphTargets = morphTargetSequence.length;
  23826. const tracks = [];
  23827. for ( let i = 0; i < numMorphTargets; i ++ ) {
  23828. let times = [];
  23829. let values = [];
  23830. times.push(
  23831. ( i + numMorphTargets - 1 ) % numMorphTargets,
  23832. i,
  23833. ( i + 1 ) % numMorphTargets );
  23834. values.push( 0, 1, 0 );
  23835. const order = getKeyframeOrder( times );
  23836. times = sortedArray( times, 1, order );
  23837. values = sortedArray( values, 1, order );
  23838. // if there is a key at the first frame, duplicate it as the
  23839. // last frame as well for perfect loop.
  23840. if ( ! noLoop && times[ 0 ] === 0 ) {
  23841. times.push( numMorphTargets );
  23842. values.push( values[ 0 ] );
  23843. }
  23844. tracks.push(
  23845. new NumberKeyframeTrack(
  23846. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  23847. times, values
  23848. ).scale( 1.0 / fps ) );
  23849. }
  23850. return new this( name, - 1, tracks );
  23851. }
  23852. static findByName( objectOrClipArray, name ) {
  23853. let clipArray = objectOrClipArray;
  23854. if ( ! Array.isArray( objectOrClipArray ) ) {
  23855. const o = objectOrClipArray;
  23856. clipArray = o.geometry && o.geometry.animations || o.animations;
  23857. }
  23858. for ( let i = 0; i < clipArray.length; i ++ ) {
  23859. if ( clipArray[ i ].name === name ) {
  23860. return clipArray[ i ];
  23861. }
  23862. }
  23863. return null;
  23864. }
  23865. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  23866. const animationToMorphTargets = {};
  23867. // tested with https://regex101.com/ on trick sequences
  23868. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  23869. const pattern = /^([\w-]*?)([\d]+)$/;
  23870. // sort morph target names into animation groups based
  23871. // patterns like Walk_001, Walk_002, Run_001, Run_002
  23872. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  23873. const morphTarget = morphTargets[ i ];
  23874. const parts = morphTarget.name.match( pattern );
  23875. if ( parts && parts.length > 1 ) {
  23876. const name = parts[ 1 ];
  23877. let animationMorphTargets = animationToMorphTargets[ name ];
  23878. if ( ! animationMorphTargets ) {
  23879. animationToMorphTargets[ name ] = animationMorphTargets = [];
  23880. }
  23881. animationMorphTargets.push( morphTarget );
  23882. }
  23883. }
  23884. const clips = [];
  23885. for ( const name in animationToMorphTargets ) {
  23886. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  23887. }
  23888. return clips;
  23889. }
  23890. // parse the animation.hierarchy format
  23891. static parseAnimation( animation, bones ) {
  23892. if ( ! animation ) {
  23893. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  23894. return null;
  23895. }
  23896. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  23897. // only return track if there are actually keys.
  23898. if ( animationKeys.length !== 0 ) {
  23899. const times = [];
  23900. const values = [];
  23901. flattenJSON( animationKeys, times, values, propertyName );
  23902. // empty keys are filtered out, so check again
  23903. if ( times.length !== 0 ) {
  23904. destTracks.push( new trackType( trackName, times, values ) );
  23905. }
  23906. }
  23907. };
  23908. const tracks = [];
  23909. const clipName = animation.name || 'default';
  23910. const fps = animation.fps || 30;
  23911. const blendMode = animation.blendMode;
  23912. // automatic length determination in AnimationClip.
  23913. let duration = animation.length || - 1;
  23914. const hierarchyTracks = animation.hierarchy || [];
  23915. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  23916. const animationKeys = hierarchyTracks[ h ].keys;
  23917. // skip empty tracks
  23918. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  23919. // process morph targets
  23920. if ( animationKeys[ 0 ].morphTargets ) {
  23921. // figure out all morph targets used in this track
  23922. const morphTargetNames = {};
  23923. let k;
  23924. for ( k = 0; k < animationKeys.length; k ++ ) {
  23925. if ( animationKeys[ k ].morphTargets ) {
  23926. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  23927. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  23928. }
  23929. }
  23930. }
  23931. // create a track for each morph target with all zero
  23932. // morphTargetInfluences except for the keys in which
  23933. // the morphTarget is named.
  23934. for ( const morphTargetName in morphTargetNames ) {
  23935. const times = [];
  23936. const values = [];
  23937. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  23938. const animationKey = animationKeys[ k ];
  23939. times.push( animationKey.time );
  23940. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  23941. }
  23942. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  23943. }
  23944. duration = morphTargetNames.length * fps;
  23945. } else {
  23946. // ...assume skeletal animation
  23947. const boneName = '.bones[' + bones[ h ].name + ']';
  23948. addNonemptyTrack(
  23949. VectorKeyframeTrack, boneName + '.position',
  23950. animationKeys, 'pos', tracks );
  23951. addNonemptyTrack(
  23952. QuaternionKeyframeTrack, boneName + '.quaternion',
  23953. animationKeys, 'rot', tracks );
  23954. addNonemptyTrack(
  23955. VectorKeyframeTrack, boneName + '.scale',
  23956. animationKeys, 'scl', tracks );
  23957. }
  23958. }
  23959. if ( tracks.length === 0 ) {
  23960. return null;
  23961. }
  23962. const clip = new this( clipName, duration, tracks, blendMode );
  23963. return clip;
  23964. }
  23965. resetDuration() {
  23966. const tracks = this.tracks;
  23967. let duration = 0;
  23968. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  23969. const track = this.tracks[ i ];
  23970. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  23971. }
  23972. this.duration = duration;
  23973. return this;
  23974. }
  23975. trim() {
  23976. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23977. this.tracks[ i ].trim( 0, this.duration );
  23978. }
  23979. return this;
  23980. }
  23981. validate() {
  23982. let valid = true;
  23983. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23984. valid = valid && this.tracks[ i ].validate();
  23985. }
  23986. return valid;
  23987. }
  23988. optimize() {
  23989. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23990. this.tracks[ i ].optimize();
  23991. }
  23992. return this;
  23993. }
  23994. clone() {
  23995. const tracks = [];
  23996. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23997. tracks.push( this.tracks[ i ].clone() );
  23998. }
  23999. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  24000. }
  24001. toJSON() {
  24002. return this.constructor.toJSON( this );
  24003. }
  24004. }
  24005. function getTrackTypeForValueTypeName( typeName ) {
  24006. switch ( typeName.toLowerCase() ) {
  24007. case 'scalar':
  24008. case 'double':
  24009. case 'float':
  24010. case 'number':
  24011. case 'integer':
  24012. return NumberKeyframeTrack;
  24013. case 'vector':
  24014. case 'vector2':
  24015. case 'vector3':
  24016. case 'vector4':
  24017. return VectorKeyframeTrack;
  24018. case 'color':
  24019. return ColorKeyframeTrack;
  24020. case 'quaternion':
  24021. return QuaternionKeyframeTrack;
  24022. case 'bool':
  24023. case 'boolean':
  24024. return BooleanKeyframeTrack;
  24025. case 'string':
  24026. return StringKeyframeTrack;
  24027. }
  24028. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  24029. }
  24030. function parseKeyframeTrack( json ) {
  24031. if ( json.type === undefined ) {
  24032. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  24033. }
  24034. const trackType = getTrackTypeForValueTypeName( json.type );
  24035. if ( json.times === undefined ) {
  24036. const times = [], values = [];
  24037. flattenJSON( json.keys, times, values, 'value' );
  24038. json.times = times;
  24039. json.values = values;
  24040. }
  24041. // derived classes can define a static parse method
  24042. if ( trackType.parse !== undefined ) {
  24043. return trackType.parse( json );
  24044. } else {
  24045. // by default, we assume a constructor compatible with the base
  24046. return new trackType( json.name, json.times, json.values, json.interpolation );
  24047. }
  24048. }
  24049. const Cache = {
  24050. enabled: false,
  24051. files: {},
  24052. add: function ( key, file ) {
  24053. if ( this.enabled === false ) return;
  24054. // console.log( 'THREE.Cache', 'Adding key:', key );
  24055. this.files[ key ] = file;
  24056. },
  24057. get: function ( key ) {
  24058. if ( this.enabled === false ) return;
  24059. // console.log( 'THREE.Cache', 'Checking key:', key );
  24060. return this.files[ key ];
  24061. },
  24062. remove: function ( key ) {
  24063. delete this.files[ key ];
  24064. },
  24065. clear: function () {
  24066. this.files = {};
  24067. }
  24068. };
  24069. class LoadingManager {
  24070. constructor( onLoad, onProgress, onError ) {
  24071. const scope = this;
  24072. let isLoading = false;
  24073. let itemsLoaded = 0;
  24074. let itemsTotal = 0;
  24075. let urlModifier = undefined;
  24076. const handlers = [];
  24077. // Refer to #5689 for the reason why we don't set .onStart
  24078. // in the constructor
  24079. this.onStart = undefined;
  24080. this.onLoad = onLoad;
  24081. this.onProgress = onProgress;
  24082. this.onError = onError;
  24083. this.itemStart = function ( url ) {
  24084. itemsTotal ++;
  24085. if ( isLoading === false ) {
  24086. if ( scope.onStart !== undefined ) {
  24087. scope.onStart( url, itemsLoaded, itemsTotal );
  24088. }
  24089. }
  24090. isLoading = true;
  24091. };
  24092. this.itemEnd = function ( url ) {
  24093. itemsLoaded ++;
  24094. if ( scope.onProgress !== undefined ) {
  24095. scope.onProgress( url, itemsLoaded, itemsTotal );
  24096. }
  24097. if ( itemsLoaded === itemsTotal ) {
  24098. isLoading = false;
  24099. if ( scope.onLoad !== undefined ) {
  24100. scope.onLoad();
  24101. }
  24102. }
  24103. };
  24104. this.itemError = function ( url ) {
  24105. if ( scope.onError !== undefined ) {
  24106. scope.onError( url );
  24107. }
  24108. };
  24109. this.resolveURL = function ( url ) {
  24110. if ( urlModifier ) {
  24111. return urlModifier( url );
  24112. }
  24113. return url;
  24114. };
  24115. this.setURLModifier = function ( transform ) {
  24116. urlModifier = transform;
  24117. return this;
  24118. };
  24119. this.addHandler = function ( regex, loader ) {
  24120. handlers.push( regex, loader );
  24121. return this;
  24122. };
  24123. this.removeHandler = function ( regex ) {
  24124. const index = handlers.indexOf( regex );
  24125. if ( index !== - 1 ) {
  24126. handlers.splice( index, 2 );
  24127. }
  24128. return this;
  24129. };
  24130. this.getHandler = function ( file ) {
  24131. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  24132. const regex = handlers[ i ];
  24133. const loader = handlers[ i + 1 ];
  24134. if ( regex.global ) regex.lastIndex = 0; // see #17920
  24135. if ( regex.test( file ) ) {
  24136. return loader;
  24137. }
  24138. }
  24139. return null;
  24140. };
  24141. }
  24142. }
  24143. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  24144. class Loader {
  24145. constructor( manager ) {
  24146. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  24147. this.crossOrigin = 'anonymous';
  24148. this.withCredentials = false;
  24149. this.path = '';
  24150. this.resourcePath = '';
  24151. this.requestHeader = {};
  24152. }
  24153. load( /* url, onLoad, onProgress, onError */ ) {}
  24154. loadAsync( url, onProgress ) {
  24155. const scope = this;
  24156. return new Promise( function ( resolve, reject ) {
  24157. scope.load( url, resolve, onProgress, reject );
  24158. } );
  24159. }
  24160. parse( /* data */ ) {}
  24161. setCrossOrigin( crossOrigin ) {
  24162. this.crossOrigin = crossOrigin;
  24163. return this;
  24164. }
  24165. setWithCredentials( value ) {
  24166. this.withCredentials = value;
  24167. return this;
  24168. }
  24169. setPath( path ) {
  24170. this.path = path;
  24171. return this;
  24172. }
  24173. setResourcePath( resourcePath ) {
  24174. this.resourcePath = resourcePath;
  24175. return this;
  24176. }
  24177. setRequestHeader( requestHeader ) {
  24178. this.requestHeader = requestHeader;
  24179. return this;
  24180. }
  24181. }
  24182. const loading = {};
  24183. class HttpError extends Error {
  24184. constructor( message, response ) {
  24185. super( message );
  24186. this.response = response;
  24187. }
  24188. }
  24189. class FileLoader extends Loader {
  24190. constructor( manager ) {
  24191. super( manager );
  24192. }
  24193. load( url, onLoad, onProgress, onError ) {
  24194. if ( url === undefined ) url = '';
  24195. if ( this.path !== undefined ) url = this.path + url;
  24196. url = this.manager.resolveURL( url );
  24197. const cached = Cache.get( url );
  24198. if ( cached !== undefined ) {
  24199. this.manager.itemStart( url );
  24200. setTimeout( () => {
  24201. if ( onLoad ) onLoad( cached );
  24202. this.manager.itemEnd( url );
  24203. }, 0 );
  24204. return cached;
  24205. }
  24206. // Check if request is duplicate
  24207. if ( loading[ url ] !== undefined ) {
  24208. loading[ url ].push( {
  24209. onLoad: onLoad,
  24210. onProgress: onProgress,
  24211. onError: onError
  24212. } );
  24213. return;
  24214. }
  24215. // Initialise array for duplicate requests
  24216. loading[ url ] = [];
  24217. loading[ url ].push( {
  24218. onLoad: onLoad,
  24219. onProgress: onProgress,
  24220. onError: onError,
  24221. } );
  24222. // create request
  24223. const req = new Request( url, {
  24224. headers: new Headers( this.requestHeader ),
  24225. credentials: this.withCredentials ? 'include' : 'same-origin',
  24226. // An abort controller could be added within a future PR
  24227. } );
  24228. // record states ( avoid data race )
  24229. const mimeType = this.mimeType;
  24230. const responseType = this.responseType;
  24231. // start the fetch
  24232. fetch( req )
  24233. .then( response => {
  24234. if ( response.status === 200 || response.status === 0 ) {
  24235. // Some browsers return HTTP Status 0 when using non-http protocol
  24236. // e.g. 'file://' or 'data://'. Handle as success.
  24237. if ( response.status === 0 ) {
  24238. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  24239. }
  24240. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  24241. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  24242. return response;
  24243. }
  24244. const callbacks = loading[ url ];
  24245. const reader = response.body.getReader();
  24246. // Nginx needs X-File-Size check
  24247. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  24248. const contentLength = response.headers.get( 'Content-Length' ) || response.headers.get( 'X-File-Size' );
  24249. const total = contentLength ? parseInt( contentLength ) : 0;
  24250. const lengthComputable = total !== 0;
  24251. let loaded = 0;
  24252. // periodically read data into the new stream tracking while download progress
  24253. const stream = new ReadableStream( {
  24254. start( controller ) {
  24255. readData();
  24256. function readData() {
  24257. reader.read().then( ( { done, value } ) => {
  24258. if ( done ) {
  24259. controller.close();
  24260. } else {
  24261. loaded += value.byteLength;
  24262. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  24263. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24264. const callback = callbacks[ i ];
  24265. if ( callback.onProgress ) callback.onProgress( event );
  24266. }
  24267. controller.enqueue( value );
  24268. readData();
  24269. }
  24270. } );
  24271. }
  24272. }
  24273. } );
  24274. return new Response( stream );
  24275. } else {
  24276. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  24277. }
  24278. } )
  24279. .then( response => {
  24280. switch ( responseType ) {
  24281. case 'arraybuffer':
  24282. return response.arrayBuffer();
  24283. case 'blob':
  24284. return response.blob();
  24285. case 'document':
  24286. return response.text()
  24287. .then( text => {
  24288. const parser = new DOMParser();
  24289. return parser.parseFromString( text, mimeType );
  24290. } );
  24291. case 'json':
  24292. return response.json();
  24293. default:
  24294. if ( mimeType === undefined ) {
  24295. return response.text();
  24296. } else {
  24297. // sniff encoding
  24298. const re = /charset="?([^;"\s]*)"?/i;
  24299. const exec = re.exec( mimeType );
  24300. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  24301. const decoder = new TextDecoder( label );
  24302. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  24303. }
  24304. }
  24305. } )
  24306. .then( data => {
  24307. // Add to cache only on HTTP success, so that we do not cache
  24308. // error response bodies as proper responses to requests.
  24309. Cache.add( url, data );
  24310. const callbacks = loading[ url ];
  24311. delete loading[ url ];
  24312. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24313. const callback = callbacks[ i ];
  24314. if ( callback.onLoad ) callback.onLoad( data );
  24315. }
  24316. } )
  24317. .catch( err => {
  24318. // Abort errors and other errors are handled the same
  24319. const callbacks = loading[ url ];
  24320. if ( callbacks === undefined ) {
  24321. // When onLoad was called and url was deleted in `loading`
  24322. this.manager.itemError( url );
  24323. throw err;
  24324. }
  24325. delete loading[ url ];
  24326. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  24327. const callback = callbacks[ i ];
  24328. if ( callback.onError ) callback.onError( err );
  24329. }
  24330. this.manager.itemError( url );
  24331. } )
  24332. .finally( () => {
  24333. this.manager.itemEnd( url );
  24334. } );
  24335. this.manager.itemStart( url );
  24336. }
  24337. setResponseType( value ) {
  24338. this.responseType = value;
  24339. return this;
  24340. }
  24341. setMimeType( value ) {
  24342. this.mimeType = value;
  24343. return this;
  24344. }
  24345. }
  24346. class AnimationLoader extends Loader {
  24347. constructor( manager ) {
  24348. super( manager );
  24349. }
  24350. load( url, onLoad, onProgress, onError ) {
  24351. const scope = this;
  24352. const loader = new FileLoader( this.manager );
  24353. loader.setPath( this.path );
  24354. loader.setRequestHeader( this.requestHeader );
  24355. loader.setWithCredentials( this.withCredentials );
  24356. loader.load( url, function ( text ) {
  24357. try {
  24358. onLoad( scope.parse( JSON.parse( text ) ) );
  24359. } catch ( e ) {
  24360. if ( onError ) {
  24361. onError( e );
  24362. } else {
  24363. console.error( e );
  24364. }
  24365. scope.manager.itemError( url );
  24366. }
  24367. }, onProgress, onError );
  24368. }
  24369. parse( json ) {
  24370. const animations = [];
  24371. for ( let i = 0; i < json.length; i ++ ) {
  24372. const clip = AnimationClip.parse( json[ i ] );
  24373. animations.push( clip );
  24374. }
  24375. return animations;
  24376. }
  24377. }
  24378. /**
  24379. * Abstract Base class to block based textures loader (dds, pvr, ...)
  24380. *
  24381. * Sub classes have to implement the parse() method which will be used in load().
  24382. */
  24383. class CompressedTextureLoader extends Loader {
  24384. constructor( manager ) {
  24385. super( manager );
  24386. }
  24387. load( url, onLoad, onProgress, onError ) {
  24388. const scope = this;
  24389. const images = [];
  24390. const texture = new CompressedTexture();
  24391. const loader = new FileLoader( this.manager );
  24392. loader.setPath( this.path );
  24393. loader.setResponseType( 'arraybuffer' );
  24394. loader.setRequestHeader( this.requestHeader );
  24395. loader.setWithCredentials( scope.withCredentials );
  24396. let loaded = 0;
  24397. function loadTexture( i ) {
  24398. loader.load( url[ i ], function ( buffer ) {
  24399. const texDatas = scope.parse( buffer, true );
  24400. images[ i ] = {
  24401. width: texDatas.width,
  24402. height: texDatas.height,
  24403. format: texDatas.format,
  24404. mipmaps: texDatas.mipmaps
  24405. };
  24406. loaded += 1;
  24407. if ( loaded === 6 ) {
  24408. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  24409. texture.image = images;
  24410. texture.format = texDatas.format;
  24411. texture.needsUpdate = true;
  24412. if ( onLoad ) onLoad( texture );
  24413. }
  24414. }, onProgress, onError );
  24415. }
  24416. if ( Array.isArray( url ) ) {
  24417. for ( let i = 0, il = url.length; i < il; ++ i ) {
  24418. loadTexture( i );
  24419. }
  24420. } else {
  24421. // compressed cubemap texture stored in a single DDS file
  24422. loader.load( url, function ( buffer ) {
  24423. const texDatas = scope.parse( buffer, true );
  24424. if ( texDatas.isCubemap ) {
  24425. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  24426. for ( let f = 0; f < faces; f ++ ) {
  24427. images[ f ] = { mipmaps: [] };
  24428. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  24429. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  24430. images[ f ].format = texDatas.format;
  24431. images[ f ].width = texDatas.width;
  24432. images[ f ].height = texDatas.height;
  24433. }
  24434. }
  24435. texture.image = images;
  24436. } else {
  24437. texture.image.width = texDatas.width;
  24438. texture.image.height = texDatas.height;
  24439. texture.mipmaps = texDatas.mipmaps;
  24440. }
  24441. if ( texDatas.mipmapCount === 1 ) {
  24442. texture.minFilter = LinearFilter;
  24443. }
  24444. texture.format = texDatas.format;
  24445. texture.needsUpdate = true;
  24446. if ( onLoad ) onLoad( texture );
  24447. }, onProgress, onError );
  24448. }
  24449. return texture;
  24450. }
  24451. }
  24452. class ImageLoader extends Loader {
  24453. constructor( manager ) {
  24454. super( manager );
  24455. }
  24456. load( url, onLoad, onProgress, onError ) {
  24457. if ( this.path !== undefined ) url = this.path + url;
  24458. url = this.manager.resolveURL( url );
  24459. const scope = this;
  24460. const cached = Cache.get( url );
  24461. if ( cached !== undefined ) {
  24462. scope.manager.itemStart( url );
  24463. setTimeout( function () {
  24464. if ( onLoad ) onLoad( cached );
  24465. scope.manager.itemEnd( url );
  24466. }, 0 );
  24467. return cached;
  24468. }
  24469. const image = createElementNS( 'img' );
  24470. function onImageLoad() {
  24471. removeEventListeners();
  24472. Cache.add( url, this );
  24473. if ( onLoad ) onLoad( this );
  24474. scope.manager.itemEnd( url );
  24475. }
  24476. function onImageError( event ) {
  24477. removeEventListeners();
  24478. if ( onError ) onError( event );
  24479. scope.manager.itemError( url );
  24480. scope.manager.itemEnd( url );
  24481. }
  24482. function removeEventListeners() {
  24483. image.removeEventListener( 'load', onImageLoad, false );
  24484. image.removeEventListener( 'error', onImageError, false );
  24485. }
  24486. image.addEventListener( 'load', onImageLoad, false );
  24487. image.addEventListener( 'error', onImageError, false );
  24488. if ( url.slice( 0, 5 ) !== 'data:' ) {
  24489. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  24490. }
  24491. scope.manager.itemStart( url );
  24492. image.src = url;
  24493. return image;
  24494. }
  24495. }
  24496. class CubeTextureLoader extends Loader {
  24497. constructor( manager ) {
  24498. super( manager );
  24499. }
  24500. load( urls, onLoad, onProgress, onError ) {
  24501. const texture = new CubeTexture();
  24502. const loader = new ImageLoader( this.manager );
  24503. loader.setCrossOrigin( this.crossOrigin );
  24504. loader.setPath( this.path );
  24505. let loaded = 0;
  24506. function loadTexture( i ) {
  24507. loader.load( urls[ i ], function ( image ) {
  24508. texture.images[ i ] = image;
  24509. loaded ++;
  24510. if ( loaded === 6 ) {
  24511. texture.needsUpdate = true;
  24512. if ( onLoad ) onLoad( texture );
  24513. }
  24514. }, undefined, onError );
  24515. }
  24516. for ( let i = 0; i < urls.length; ++ i ) {
  24517. loadTexture( i );
  24518. }
  24519. return texture;
  24520. }
  24521. }
  24522. /**
  24523. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  24524. *
  24525. * Sub classes have to implement the parse() method which will be used in load().
  24526. */
  24527. class DataTextureLoader extends Loader {
  24528. constructor( manager ) {
  24529. super( manager );
  24530. }
  24531. load( url, onLoad, onProgress, onError ) {
  24532. const scope = this;
  24533. const texture = new DataTexture();
  24534. const loader = new FileLoader( this.manager );
  24535. loader.setResponseType( 'arraybuffer' );
  24536. loader.setRequestHeader( this.requestHeader );
  24537. loader.setPath( this.path );
  24538. loader.setWithCredentials( scope.withCredentials );
  24539. loader.load( url, function ( buffer ) {
  24540. const texData = scope.parse( buffer );
  24541. if ( ! texData ) return;
  24542. if ( texData.image !== undefined ) {
  24543. texture.image = texData.image;
  24544. } else if ( texData.data !== undefined ) {
  24545. texture.image.width = texData.width;
  24546. texture.image.height = texData.height;
  24547. texture.image.data = texData.data;
  24548. }
  24549. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  24550. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  24551. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  24552. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  24553. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  24554. if ( texData.encoding !== undefined ) {
  24555. texture.encoding = texData.encoding;
  24556. }
  24557. if ( texData.flipY !== undefined ) {
  24558. texture.flipY = texData.flipY;
  24559. }
  24560. if ( texData.format !== undefined ) {
  24561. texture.format = texData.format;
  24562. }
  24563. if ( texData.type !== undefined ) {
  24564. texture.type = texData.type;
  24565. }
  24566. if ( texData.mipmaps !== undefined ) {
  24567. texture.mipmaps = texData.mipmaps;
  24568. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  24569. }
  24570. if ( texData.mipmapCount === 1 ) {
  24571. texture.minFilter = LinearFilter;
  24572. }
  24573. if ( texData.generateMipmaps !== undefined ) {
  24574. texture.generateMipmaps = texData.generateMipmaps;
  24575. }
  24576. texture.needsUpdate = true;
  24577. if ( onLoad ) onLoad( texture, texData );
  24578. }, onProgress, onError );
  24579. return texture;
  24580. }
  24581. }
  24582. class TextureLoader extends Loader {
  24583. constructor( manager ) {
  24584. super( manager );
  24585. }
  24586. load( url, onLoad, onProgress, onError ) {
  24587. const texture = new Texture();
  24588. const loader = new ImageLoader( this.manager );
  24589. loader.setCrossOrigin( this.crossOrigin );
  24590. loader.setPath( this.path );
  24591. loader.load( url, function ( image ) {
  24592. texture.image = image;
  24593. texture.needsUpdate = true;
  24594. if ( onLoad !== undefined ) {
  24595. onLoad( texture );
  24596. }
  24597. }, onProgress, onError );
  24598. return texture;
  24599. }
  24600. }
  24601. class Light extends Object3D {
  24602. constructor( color, intensity = 1 ) {
  24603. super();
  24604. this.isLight = true;
  24605. this.type = 'Light';
  24606. this.color = new Color( color );
  24607. this.intensity = intensity;
  24608. }
  24609. dispose() {
  24610. // Empty here in base class; some subclasses override.
  24611. }
  24612. copy( source, recursive ) {
  24613. super.copy( source, recursive );
  24614. this.color.copy( source.color );
  24615. this.intensity = source.intensity;
  24616. return this;
  24617. }
  24618. toJSON( meta ) {
  24619. const data = super.toJSON( meta );
  24620. data.object.color = this.color.getHex();
  24621. data.object.intensity = this.intensity;
  24622. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  24623. if ( this.distance !== undefined ) data.object.distance = this.distance;
  24624. if ( this.angle !== undefined ) data.object.angle = this.angle;
  24625. if ( this.decay !== undefined ) data.object.decay = this.decay;
  24626. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  24627. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  24628. return data;
  24629. }
  24630. }
  24631. class HemisphereLight extends Light {
  24632. constructor( skyColor, groundColor, intensity ) {
  24633. super( skyColor, intensity );
  24634. this.isHemisphereLight = true;
  24635. this.type = 'HemisphereLight';
  24636. this.position.copy( Object3D.DEFAULT_UP );
  24637. this.updateMatrix();
  24638. this.groundColor = new Color( groundColor );
  24639. }
  24640. copy( source, recursive ) {
  24641. super.copy( source, recursive );
  24642. this.groundColor.copy( source.groundColor );
  24643. return this;
  24644. }
  24645. }
  24646. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  24647. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  24648. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  24649. class LightShadow {
  24650. constructor( camera ) {
  24651. this.camera = camera;
  24652. this.bias = 0;
  24653. this.normalBias = 0;
  24654. this.radius = 1;
  24655. this.blurSamples = 8;
  24656. this.mapSize = new Vector2( 512, 512 );
  24657. this.map = null;
  24658. this.mapPass = null;
  24659. this.matrix = new Matrix4();
  24660. this.autoUpdate = true;
  24661. this.needsUpdate = false;
  24662. this._frustum = new Frustum();
  24663. this._frameExtents = new Vector2( 1, 1 );
  24664. this._viewportCount = 1;
  24665. this._viewports = [
  24666. new Vector4( 0, 0, 1, 1 )
  24667. ];
  24668. }
  24669. getViewportCount() {
  24670. return this._viewportCount;
  24671. }
  24672. getFrustum() {
  24673. return this._frustum;
  24674. }
  24675. updateMatrices( light ) {
  24676. const shadowCamera = this.camera;
  24677. const shadowMatrix = this.matrix;
  24678. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  24679. shadowCamera.position.copy( _lightPositionWorld$1 );
  24680. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  24681. shadowCamera.lookAt( _lookTarget$1 );
  24682. shadowCamera.updateMatrixWorld();
  24683. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  24684. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  24685. shadowMatrix.set(
  24686. 0.5, 0.0, 0.0, 0.5,
  24687. 0.0, 0.5, 0.0, 0.5,
  24688. 0.0, 0.0, 0.5, 0.5,
  24689. 0.0, 0.0, 0.0, 1.0
  24690. );
  24691. shadowMatrix.multiply( _projScreenMatrix$1 );
  24692. }
  24693. getViewport( viewportIndex ) {
  24694. return this._viewports[ viewportIndex ];
  24695. }
  24696. getFrameExtents() {
  24697. return this._frameExtents;
  24698. }
  24699. dispose() {
  24700. if ( this.map ) {
  24701. this.map.dispose();
  24702. }
  24703. if ( this.mapPass ) {
  24704. this.mapPass.dispose();
  24705. }
  24706. }
  24707. copy( source ) {
  24708. this.camera = source.camera.clone();
  24709. this.bias = source.bias;
  24710. this.radius = source.radius;
  24711. this.mapSize.copy( source.mapSize );
  24712. return this;
  24713. }
  24714. clone() {
  24715. return new this.constructor().copy( this );
  24716. }
  24717. toJSON() {
  24718. const object = {};
  24719. if ( this.bias !== 0 ) object.bias = this.bias;
  24720. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  24721. if ( this.radius !== 1 ) object.radius = this.radius;
  24722. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  24723. object.camera = this.camera.toJSON( false ).object;
  24724. delete object.camera.matrix;
  24725. return object;
  24726. }
  24727. }
  24728. class SpotLightShadow extends LightShadow {
  24729. constructor() {
  24730. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  24731. this.isSpotLightShadow = true;
  24732. this.focus = 1;
  24733. }
  24734. updateMatrices( light ) {
  24735. const camera = this.camera;
  24736. const fov = RAD2DEG * 2 * light.angle * this.focus;
  24737. const aspect = this.mapSize.width / this.mapSize.height;
  24738. const far = light.distance || camera.far;
  24739. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  24740. camera.fov = fov;
  24741. camera.aspect = aspect;
  24742. camera.far = far;
  24743. camera.updateProjectionMatrix();
  24744. }
  24745. super.updateMatrices( light );
  24746. }
  24747. copy( source ) {
  24748. super.copy( source );
  24749. this.focus = source.focus;
  24750. return this;
  24751. }
  24752. }
  24753. class SpotLight extends Light {
  24754. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  24755. super( color, intensity );
  24756. this.isSpotLight = true;
  24757. this.type = 'SpotLight';
  24758. this.position.copy( Object3D.DEFAULT_UP );
  24759. this.updateMatrix();
  24760. this.target = new Object3D();
  24761. this.distance = distance;
  24762. this.angle = angle;
  24763. this.penumbra = penumbra;
  24764. this.decay = decay;
  24765. this.map = null;
  24766. this.shadow = new SpotLightShadow();
  24767. }
  24768. get power() {
  24769. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24770. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  24771. return this.intensity * Math.PI;
  24772. }
  24773. set power( power ) {
  24774. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24775. this.intensity = power / Math.PI;
  24776. }
  24777. dispose() {
  24778. this.shadow.dispose();
  24779. }
  24780. copy( source, recursive ) {
  24781. super.copy( source, recursive );
  24782. this.distance = source.distance;
  24783. this.angle = source.angle;
  24784. this.penumbra = source.penumbra;
  24785. this.decay = source.decay;
  24786. this.target = source.target.clone();
  24787. this.shadow = source.shadow.clone();
  24788. return this;
  24789. }
  24790. }
  24791. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  24792. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  24793. const _lookTarget = /*@__PURE__*/ new Vector3();
  24794. class PointLightShadow extends LightShadow {
  24795. constructor() {
  24796. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  24797. this.isPointLightShadow = true;
  24798. this._frameExtents = new Vector2( 4, 2 );
  24799. this._viewportCount = 6;
  24800. this._viewports = [
  24801. // These viewports map a cube-map onto a 2D texture with the
  24802. // following orientation:
  24803. //
  24804. // xzXZ
  24805. // y Y
  24806. //
  24807. // X - Positive x direction
  24808. // x - Negative x direction
  24809. // Y - Positive y direction
  24810. // y - Negative y direction
  24811. // Z - Positive z direction
  24812. // z - Negative z direction
  24813. // positive X
  24814. new Vector4( 2, 1, 1, 1 ),
  24815. // negative X
  24816. new Vector4( 0, 1, 1, 1 ),
  24817. // positive Z
  24818. new Vector4( 3, 1, 1, 1 ),
  24819. // negative Z
  24820. new Vector4( 1, 1, 1, 1 ),
  24821. // positive Y
  24822. new Vector4( 3, 0, 1, 1 ),
  24823. // negative Y
  24824. new Vector4( 1, 0, 1, 1 )
  24825. ];
  24826. this._cubeDirections = [
  24827. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  24828. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  24829. ];
  24830. this._cubeUps = [
  24831. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  24832. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  24833. ];
  24834. }
  24835. updateMatrices( light, viewportIndex = 0 ) {
  24836. const camera = this.camera;
  24837. const shadowMatrix = this.matrix;
  24838. const far = light.distance || camera.far;
  24839. if ( far !== camera.far ) {
  24840. camera.far = far;
  24841. camera.updateProjectionMatrix();
  24842. }
  24843. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  24844. camera.position.copy( _lightPositionWorld );
  24845. _lookTarget.copy( camera.position );
  24846. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  24847. camera.up.copy( this._cubeUps[ viewportIndex ] );
  24848. camera.lookAt( _lookTarget );
  24849. camera.updateMatrixWorld();
  24850. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  24851. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  24852. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  24853. }
  24854. }
  24855. class PointLight extends Light {
  24856. constructor( color, intensity, distance = 0, decay = 2 ) {
  24857. super( color, intensity );
  24858. this.isPointLight = true;
  24859. this.type = 'PointLight';
  24860. this.distance = distance;
  24861. this.decay = decay;
  24862. this.shadow = new PointLightShadow();
  24863. }
  24864. get power() {
  24865. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24866. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  24867. return this.intensity * 4 * Math.PI;
  24868. }
  24869. set power( power ) {
  24870. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24871. this.intensity = power / ( 4 * Math.PI );
  24872. }
  24873. dispose() {
  24874. this.shadow.dispose();
  24875. }
  24876. copy( source, recursive ) {
  24877. super.copy( source, recursive );
  24878. this.distance = source.distance;
  24879. this.decay = source.decay;
  24880. this.shadow = source.shadow.clone();
  24881. return this;
  24882. }
  24883. }
  24884. class DirectionalLightShadow extends LightShadow {
  24885. constructor() {
  24886. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  24887. this.isDirectionalLightShadow = true;
  24888. }
  24889. }
  24890. class DirectionalLight extends Light {
  24891. constructor( color, intensity ) {
  24892. super( color, intensity );
  24893. this.isDirectionalLight = true;
  24894. this.type = 'DirectionalLight';
  24895. this.position.copy( Object3D.DEFAULT_UP );
  24896. this.updateMatrix();
  24897. this.target = new Object3D();
  24898. this.shadow = new DirectionalLightShadow();
  24899. }
  24900. dispose() {
  24901. this.shadow.dispose();
  24902. }
  24903. copy( source ) {
  24904. super.copy( source );
  24905. this.target = source.target.clone();
  24906. this.shadow = source.shadow.clone();
  24907. return this;
  24908. }
  24909. }
  24910. class AmbientLight extends Light {
  24911. constructor( color, intensity ) {
  24912. super( color, intensity );
  24913. this.isAmbientLight = true;
  24914. this.type = 'AmbientLight';
  24915. }
  24916. }
  24917. class RectAreaLight extends Light {
  24918. constructor( color, intensity, width = 10, height = 10 ) {
  24919. super( color, intensity );
  24920. this.isRectAreaLight = true;
  24921. this.type = 'RectAreaLight';
  24922. this.width = width;
  24923. this.height = height;
  24924. }
  24925. get power() {
  24926. // compute the light's luminous power (in lumens) from its intensity (in nits)
  24927. return this.intensity * this.width * this.height * Math.PI;
  24928. }
  24929. set power( power ) {
  24930. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  24931. this.intensity = power / ( this.width * this.height * Math.PI );
  24932. }
  24933. copy( source ) {
  24934. super.copy( source );
  24935. this.width = source.width;
  24936. this.height = source.height;
  24937. return this;
  24938. }
  24939. toJSON( meta ) {
  24940. const data = super.toJSON( meta );
  24941. data.object.width = this.width;
  24942. data.object.height = this.height;
  24943. return data;
  24944. }
  24945. }
  24946. /**
  24947. * Primary reference:
  24948. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24949. *
  24950. * Secondary reference:
  24951. * https://www.ppsloan.org/publications/StupidSH36.pdf
  24952. */
  24953. // 3-band SH defined by 9 coefficients
  24954. class SphericalHarmonics3 {
  24955. constructor() {
  24956. this.isSphericalHarmonics3 = true;
  24957. this.coefficients = [];
  24958. for ( let i = 0; i < 9; i ++ ) {
  24959. this.coefficients.push( new Vector3() );
  24960. }
  24961. }
  24962. set( coefficients ) {
  24963. for ( let i = 0; i < 9; i ++ ) {
  24964. this.coefficients[ i ].copy( coefficients[ i ] );
  24965. }
  24966. return this;
  24967. }
  24968. zero() {
  24969. for ( let i = 0; i < 9; i ++ ) {
  24970. this.coefficients[ i ].set( 0, 0, 0 );
  24971. }
  24972. return this;
  24973. }
  24974. // get the radiance in the direction of the normal
  24975. // target is a Vector3
  24976. getAt( normal, target ) {
  24977. // normal is assumed to be unit length
  24978. const x = normal.x, y = normal.y, z = normal.z;
  24979. const coeff = this.coefficients;
  24980. // band 0
  24981. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  24982. // band 1
  24983. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  24984. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  24985. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  24986. // band 2
  24987. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  24988. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  24989. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  24990. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  24991. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  24992. return target;
  24993. }
  24994. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  24995. // target is a Vector3
  24996. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24997. getIrradianceAt( normal, target ) {
  24998. // normal is assumed to be unit length
  24999. const x = normal.x, y = normal.y, z = normal.z;
  25000. const coeff = this.coefficients;
  25001. // band 0
  25002. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  25003. // band 1
  25004. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  25005. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  25006. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  25007. // band 2
  25008. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  25009. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  25010. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  25011. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  25012. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  25013. return target;
  25014. }
  25015. add( sh ) {
  25016. for ( let i = 0; i < 9; i ++ ) {
  25017. this.coefficients[ i ].add( sh.coefficients[ i ] );
  25018. }
  25019. return this;
  25020. }
  25021. addScaledSH( sh, s ) {
  25022. for ( let i = 0; i < 9; i ++ ) {
  25023. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  25024. }
  25025. return this;
  25026. }
  25027. scale( s ) {
  25028. for ( let i = 0; i < 9; i ++ ) {
  25029. this.coefficients[ i ].multiplyScalar( s );
  25030. }
  25031. return this;
  25032. }
  25033. lerp( sh, alpha ) {
  25034. for ( let i = 0; i < 9; i ++ ) {
  25035. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  25036. }
  25037. return this;
  25038. }
  25039. equals( sh ) {
  25040. for ( let i = 0; i < 9; i ++ ) {
  25041. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  25042. return false;
  25043. }
  25044. }
  25045. return true;
  25046. }
  25047. copy( sh ) {
  25048. return this.set( sh.coefficients );
  25049. }
  25050. clone() {
  25051. return new this.constructor().copy( this );
  25052. }
  25053. fromArray( array, offset = 0 ) {
  25054. const coefficients = this.coefficients;
  25055. for ( let i = 0; i < 9; i ++ ) {
  25056. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  25057. }
  25058. return this;
  25059. }
  25060. toArray( array = [], offset = 0 ) {
  25061. const coefficients = this.coefficients;
  25062. for ( let i = 0; i < 9; i ++ ) {
  25063. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  25064. }
  25065. return array;
  25066. }
  25067. // evaluate the basis functions
  25068. // shBasis is an Array[ 9 ]
  25069. static getBasisAt( normal, shBasis ) {
  25070. // normal is assumed to be unit length
  25071. const x = normal.x, y = normal.y, z = normal.z;
  25072. // band 0
  25073. shBasis[ 0 ] = 0.282095;
  25074. // band 1
  25075. shBasis[ 1 ] = 0.488603 * y;
  25076. shBasis[ 2 ] = 0.488603 * z;
  25077. shBasis[ 3 ] = 0.488603 * x;
  25078. // band 2
  25079. shBasis[ 4 ] = 1.092548 * x * y;
  25080. shBasis[ 5 ] = 1.092548 * y * z;
  25081. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  25082. shBasis[ 7 ] = 1.092548 * x * z;
  25083. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  25084. }
  25085. }
  25086. class LightProbe extends Light {
  25087. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  25088. super( undefined, intensity );
  25089. this.isLightProbe = true;
  25090. this.sh = sh;
  25091. }
  25092. copy( source ) {
  25093. super.copy( source );
  25094. this.sh.copy( source.sh );
  25095. return this;
  25096. }
  25097. fromJSON( json ) {
  25098. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  25099. this.sh.fromArray( json.sh );
  25100. return this;
  25101. }
  25102. toJSON( meta ) {
  25103. const data = super.toJSON( meta );
  25104. data.object.sh = this.sh.toArray();
  25105. return data;
  25106. }
  25107. }
  25108. class MaterialLoader extends Loader {
  25109. constructor( manager ) {
  25110. super( manager );
  25111. this.textures = {};
  25112. }
  25113. load( url, onLoad, onProgress, onError ) {
  25114. const scope = this;
  25115. const loader = new FileLoader( scope.manager );
  25116. loader.setPath( scope.path );
  25117. loader.setRequestHeader( scope.requestHeader );
  25118. loader.setWithCredentials( scope.withCredentials );
  25119. loader.load( url, function ( text ) {
  25120. try {
  25121. onLoad( scope.parse( JSON.parse( text ) ) );
  25122. } catch ( e ) {
  25123. if ( onError ) {
  25124. onError( e );
  25125. } else {
  25126. console.error( e );
  25127. }
  25128. scope.manager.itemError( url );
  25129. }
  25130. }, onProgress, onError );
  25131. }
  25132. parse( json ) {
  25133. const textures = this.textures;
  25134. function getTexture( name ) {
  25135. if ( textures[ name ] === undefined ) {
  25136. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  25137. }
  25138. return textures[ name ];
  25139. }
  25140. const material = MaterialLoader.createMaterialFromType( json.type );
  25141. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  25142. if ( json.name !== undefined ) material.name = json.name;
  25143. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  25144. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  25145. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  25146. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  25147. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  25148. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  25149. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  25150. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  25151. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  25152. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  25153. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  25154. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  25155. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  25156. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  25157. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  25158. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  25159. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  25160. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  25161. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  25162. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  25163. if ( json.fog !== undefined ) material.fog = json.fog;
  25164. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  25165. if ( json.blending !== undefined ) material.blending = json.blending;
  25166. if ( json.combine !== undefined ) material.combine = json.combine;
  25167. if ( json.side !== undefined ) material.side = json.side;
  25168. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  25169. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  25170. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  25171. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  25172. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  25173. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  25174. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  25175. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  25176. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  25177. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  25178. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  25179. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  25180. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  25181. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  25182. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  25183. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  25184. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  25185. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  25186. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  25187. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  25188. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  25189. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  25190. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  25191. if ( json.scale !== undefined ) material.scale = json.scale;
  25192. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  25193. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  25194. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  25195. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  25196. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  25197. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  25198. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  25199. if ( json.visible !== undefined ) material.visible = json.visible;
  25200. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  25201. if ( json.userData !== undefined ) material.userData = json.userData;
  25202. if ( json.vertexColors !== undefined ) {
  25203. if ( typeof json.vertexColors === 'number' ) {
  25204. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  25205. } else {
  25206. material.vertexColors = json.vertexColors;
  25207. }
  25208. }
  25209. // Shader Material
  25210. if ( json.uniforms !== undefined ) {
  25211. for ( const name in json.uniforms ) {
  25212. const uniform = json.uniforms[ name ];
  25213. material.uniforms[ name ] = {};
  25214. switch ( uniform.type ) {
  25215. case 't':
  25216. material.uniforms[ name ].value = getTexture( uniform.value );
  25217. break;
  25218. case 'c':
  25219. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  25220. break;
  25221. case 'v2':
  25222. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  25223. break;
  25224. case 'v3':
  25225. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  25226. break;
  25227. case 'v4':
  25228. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  25229. break;
  25230. case 'm3':
  25231. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  25232. break;
  25233. case 'm4':
  25234. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  25235. break;
  25236. default:
  25237. material.uniforms[ name ].value = uniform.value;
  25238. }
  25239. }
  25240. }
  25241. if ( json.defines !== undefined ) material.defines = json.defines;
  25242. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  25243. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  25244. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  25245. if ( json.extensions !== undefined ) {
  25246. for ( const key in json.extensions ) {
  25247. material.extensions[ key ] = json.extensions[ key ];
  25248. }
  25249. }
  25250. // for PointsMaterial
  25251. if ( json.size !== undefined ) material.size = json.size;
  25252. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  25253. // maps
  25254. if ( json.map !== undefined ) material.map = getTexture( json.map );
  25255. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  25256. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  25257. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  25258. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  25259. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  25260. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  25261. if ( json.normalScale !== undefined ) {
  25262. let normalScale = json.normalScale;
  25263. if ( Array.isArray( normalScale ) === false ) {
  25264. // Blender exporter used to export a scalar. See #7459
  25265. normalScale = [ normalScale, normalScale ];
  25266. }
  25267. material.normalScale = new Vector2().fromArray( normalScale );
  25268. }
  25269. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  25270. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  25271. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  25272. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  25273. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  25274. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  25275. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  25276. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  25277. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  25278. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  25279. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  25280. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  25281. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  25282. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  25283. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  25284. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  25285. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  25286. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  25287. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  25288. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  25289. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  25290. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  25291. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  25292. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  25293. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  25294. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  25295. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  25296. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  25297. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  25298. return material;
  25299. }
  25300. setTextures( value ) {
  25301. this.textures = value;
  25302. return this;
  25303. }
  25304. static createMaterialFromType( type ) {
  25305. const materialLib = {
  25306. ShadowMaterial,
  25307. SpriteMaterial,
  25308. RawShaderMaterial,
  25309. ShaderMaterial,
  25310. PointsMaterial,
  25311. MeshPhysicalMaterial,
  25312. MeshStandardMaterial,
  25313. MeshPhongMaterial,
  25314. MeshToonMaterial,
  25315. MeshNormalMaterial,
  25316. MeshLambertMaterial,
  25317. MeshDepthMaterial,
  25318. MeshDistanceMaterial,
  25319. MeshBasicMaterial,
  25320. MeshMatcapMaterial,
  25321. LineDashedMaterial,
  25322. LineBasicMaterial,
  25323. Material
  25324. };
  25325. return new materialLib[ type ]();
  25326. }
  25327. }
  25328. class LoaderUtils {
  25329. static decodeText( array ) {
  25330. if ( typeof TextDecoder !== 'undefined' ) {
  25331. return new TextDecoder().decode( array );
  25332. }
  25333. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  25334. // throws a "maximum call stack size exceeded" error for large arrays.
  25335. let s = '';
  25336. for ( let i = 0, il = array.length; i < il; i ++ ) {
  25337. // Implicitly assumes little-endian.
  25338. s += String.fromCharCode( array[ i ] );
  25339. }
  25340. try {
  25341. // merges multi-byte utf-8 characters.
  25342. return decodeURIComponent( escape( s ) );
  25343. } catch ( e ) { // see #16358
  25344. return s;
  25345. }
  25346. }
  25347. static extractUrlBase( url ) {
  25348. const index = url.lastIndexOf( '/' );
  25349. if ( index === - 1 ) return './';
  25350. return url.slice( 0, index + 1 );
  25351. }
  25352. static resolveURL( url, path ) {
  25353. // Invalid URL
  25354. if ( typeof url !== 'string' || url === '' ) return '';
  25355. // Host Relative URL
  25356. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  25357. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  25358. }
  25359. // Absolute URL http://,https://,//
  25360. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  25361. // Data URI
  25362. if ( /^data:.*,.*$/i.test( url ) ) return url;
  25363. // Blob URL
  25364. if ( /^blob:.*$/i.test( url ) ) return url;
  25365. // Relative URL
  25366. return path + url;
  25367. }
  25368. }
  25369. class InstancedBufferGeometry extends BufferGeometry {
  25370. constructor() {
  25371. super();
  25372. this.isInstancedBufferGeometry = true;
  25373. this.type = 'InstancedBufferGeometry';
  25374. this.instanceCount = Infinity;
  25375. }
  25376. copy( source ) {
  25377. super.copy( source );
  25378. this.instanceCount = source.instanceCount;
  25379. return this;
  25380. }
  25381. toJSON() {
  25382. const data = super.toJSON();
  25383. data.instanceCount = this.instanceCount;
  25384. data.isInstancedBufferGeometry = true;
  25385. return data;
  25386. }
  25387. }
  25388. class BufferGeometryLoader extends Loader {
  25389. constructor( manager ) {
  25390. super( manager );
  25391. }
  25392. load( url, onLoad, onProgress, onError ) {
  25393. const scope = this;
  25394. const loader = new FileLoader( scope.manager );
  25395. loader.setPath( scope.path );
  25396. loader.setRequestHeader( scope.requestHeader );
  25397. loader.setWithCredentials( scope.withCredentials );
  25398. loader.load( url, function ( text ) {
  25399. try {
  25400. onLoad( scope.parse( JSON.parse( text ) ) );
  25401. } catch ( e ) {
  25402. if ( onError ) {
  25403. onError( e );
  25404. } else {
  25405. console.error( e );
  25406. }
  25407. scope.manager.itemError( url );
  25408. }
  25409. }, onProgress, onError );
  25410. }
  25411. parse( json ) {
  25412. const interleavedBufferMap = {};
  25413. const arrayBufferMap = {};
  25414. function getInterleavedBuffer( json, uuid ) {
  25415. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  25416. const interleavedBuffers = json.interleavedBuffers;
  25417. const interleavedBuffer = interleavedBuffers[ uuid ];
  25418. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  25419. const array = getTypedArray( interleavedBuffer.type, buffer );
  25420. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  25421. ib.uuid = interleavedBuffer.uuid;
  25422. interleavedBufferMap[ uuid ] = ib;
  25423. return ib;
  25424. }
  25425. function getArrayBuffer( json, uuid ) {
  25426. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  25427. const arrayBuffers = json.arrayBuffers;
  25428. const arrayBuffer = arrayBuffers[ uuid ];
  25429. const ab = new Uint32Array( arrayBuffer ).buffer;
  25430. arrayBufferMap[ uuid ] = ab;
  25431. return ab;
  25432. }
  25433. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  25434. const index = json.data.index;
  25435. if ( index !== undefined ) {
  25436. const typedArray = getTypedArray( index.type, index.array );
  25437. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  25438. }
  25439. const attributes = json.data.attributes;
  25440. for ( const key in attributes ) {
  25441. const attribute = attributes[ key ];
  25442. let bufferAttribute;
  25443. if ( attribute.isInterleavedBufferAttribute ) {
  25444. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25445. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25446. } else {
  25447. const typedArray = getTypedArray( attribute.type, attribute.array );
  25448. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  25449. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  25450. }
  25451. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25452. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  25453. if ( attribute.updateRange !== undefined ) {
  25454. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  25455. bufferAttribute.updateRange.count = attribute.updateRange.count;
  25456. }
  25457. geometry.setAttribute( key, bufferAttribute );
  25458. }
  25459. const morphAttributes = json.data.morphAttributes;
  25460. if ( morphAttributes ) {
  25461. for ( const key in morphAttributes ) {
  25462. const attributeArray = morphAttributes[ key ];
  25463. const array = [];
  25464. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  25465. const attribute = attributeArray[ i ];
  25466. let bufferAttribute;
  25467. if ( attribute.isInterleavedBufferAttribute ) {
  25468. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  25469. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  25470. } else {
  25471. const typedArray = getTypedArray( attribute.type, attribute.array );
  25472. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  25473. }
  25474. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  25475. array.push( bufferAttribute );
  25476. }
  25477. geometry.morphAttributes[ key ] = array;
  25478. }
  25479. }
  25480. const morphTargetsRelative = json.data.morphTargetsRelative;
  25481. if ( morphTargetsRelative ) {
  25482. geometry.morphTargetsRelative = true;
  25483. }
  25484. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  25485. if ( groups !== undefined ) {
  25486. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  25487. const group = groups[ i ];
  25488. geometry.addGroup( group.start, group.count, group.materialIndex );
  25489. }
  25490. }
  25491. const boundingSphere = json.data.boundingSphere;
  25492. if ( boundingSphere !== undefined ) {
  25493. const center = new Vector3();
  25494. if ( boundingSphere.center !== undefined ) {
  25495. center.fromArray( boundingSphere.center );
  25496. }
  25497. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  25498. }
  25499. if ( json.name ) geometry.name = json.name;
  25500. if ( json.userData ) geometry.userData = json.userData;
  25501. return geometry;
  25502. }
  25503. }
  25504. class ObjectLoader extends Loader {
  25505. constructor( manager ) {
  25506. super( manager );
  25507. }
  25508. load( url, onLoad, onProgress, onError ) {
  25509. const scope = this;
  25510. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  25511. this.resourcePath = this.resourcePath || path;
  25512. const loader = new FileLoader( this.manager );
  25513. loader.setPath( this.path );
  25514. loader.setRequestHeader( this.requestHeader );
  25515. loader.setWithCredentials( this.withCredentials );
  25516. loader.load( url, function ( text ) {
  25517. let json = null;
  25518. try {
  25519. json = JSON.parse( text );
  25520. } catch ( error ) {
  25521. if ( onError !== undefined ) onError( error );
  25522. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  25523. return;
  25524. }
  25525. const metadata = json.metadata;
  25526. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25527. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  25528. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  25529. return;
  25530. }
  25531. scope.parse( json, onLoad );
  25532. }, onProgress, onError );
  25533. }
  25534. async loadAsync( url, onProgress ) {
  25535. const scope = this;
  25536. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  25537. this.resourcePath = this.resourcePath || path;
  25538. const loader = new FileLoader( this.manager );
  25539. loader.setPath( this.path );
  25540. loader.setRequestHeader( this.requestHeader );
  25541. loader.setWithCredentials( this.withCredentials );
  25542. const text = await loader.loadAsync( url, onProgress );
  25543. const json = JSON.parse( text );
  25544. const metadata = json.metadata;
  25545. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  25546. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  25547. }
  25548. return await scope.parseAsync( json );
  25549. }
  25550. parse( json, onLoad ) {
  25551. const animations = this.parseAnimations( json.animations );
  25552. const shapes = this.parseShapes( json.shapes );
  25553. const geometries = this.parseGeometries( json.geometries, shapes );
  25554. const images = this.parseImages( json.images, function () {
  25555. if ( onLoad !== undefined ) onLoad( object );
  25556. } );
  25557. const textures = this.parseTextures( json.textures, images );
  25558. const materials = this.parseMaterials( json.materials, textures );
  25559. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  25560. const skeletons = this.parseSkeletons( json.skeletons, object );
  25561. this.bindSkeletons( object, skeletons );
  25562. //
  25563. if ( onLoad !== undefined ) {
  25564. let hasImages = false;
  25565. for ( const uuid in images ) {
  25566. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  25567. hasImages = true;
  25568. break;
  25569. }
  25570. }
  25571. if ( hasImages === false ) onLoad( object );
  25572. }
  25573. return object;
  25574. }
  25575. async parseAsync( json ) {
  25576. const animations = this.parseAnimations( json.animations );
  25577. const shapes = this.parseShapes( json.shapes );
  25578. const geometries = this.parseGeometries( json.geometries, shapes );
  25579. const images = await this.parseImagesAsync( json.images );
  25580. const textures = this.parseTextures( json.textures, images );
  25581. const materials = this.parseMaterials( json.materials, textures );
  25582. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  25583. const skeletons = this.parseSkeletons( json.skeletons, object );
  25584. this.bindSkeletons( object, skeletons );
  25585. return object;
  25586. }
  25587. parseShapes( json ) {
  25588. const shapes = {};
  25589. if ( json !== undefined ) {
  25590. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25591. const shape = new Shape().fromJSON( json[ i ] );
  25592. shapes[ shape.uuid ] = shape;
  25593. }
  25594. }
  25595. return shapes;
  25596. }
  25597. parseSkeletons( json, object ) {
  25598. const skeletons = {};
  25599. const bones = {};
  25600. // generate bone lookup table
  25601. object.traverse( function ( child ) {
  25602. if ( child.isBone ) bones[ child.uuid ] = child;
  25603. } );
  25604. // create skeletons
  25605. if ( json !== undefined ) {
  25606. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25607. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  25608. skeletons[ skeleton.uuid ] = skeleton;
  25609. }
  25610. }
  25611. return skeletons;
  25612. }
  25613. parseGeometries( json, shapes ) {
  25614. const geometries = {};
  25615. if ( json !== undefined ) {
  25616. const bufferGeometryLoader = new BufferGeometryLoader();
  25617. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25618. let geometry;
  25619. const data = json[ i ];
  25620. switch ( data.type ) {
  25621. case 'BufferGeometry':
  25622. case 'InstancedBufferGeometry':
  25623. geometry = bufferGeometryLoader.parse( data );
  25624. break;
  25625. default:
  25626. if ( data.type in Geometries ) {
  25627. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  25628. } else {
  25629. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  25630. }
  25631. }
  25632. geometry.uuid = data.uuid;
  25633. if ( data.name !== undefined ) geometry.name = data.name;
  25634. if ( data.userData !== undefined ) geometry.userData = data.userData;
  25635. geometries[ data.uuid ] = geometry;
  25636. }
  25637. }
  25638. return geometries;
  25639. }
  25640. parseMaterials( json, textures ) {
  25641. const cache = {}; // MultiMaterial
  25642. const materials = {};
  25643. if ( json !== undefined ) {
  25644. const loader = new MaterialLoader();
  25645. loader.setTextures( textures );
  25646. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25647. const data = json[ i ];
  25648. if ( cache[ data.uuid ] === undefined ) {
  25649. cache[ data.uuid ] = loader.parse( data );
  25650. }
  25651. materials[ data.uuid ] = cache[ data.uuid ];
  25652. }
  25653. }
  25654. return materials;
  25655. }
  25656. parseAnimations( json ) {
  25657. const animations = {};
  25658. if ( json !== undefined ) {
  25659. for ( let i = 0; i < json.length; i ++ ) {
  25660. const data = json[ i ];
  25661. const clip = AnimationClip.parse( data );
  25662. animations[ clip.uuid ] = clip;
  25663. }
  25664. }
  25665. return animations;
  25666. }
  25667. parseImages( json, onLoad ) {
  25668. const scope = this;
  25669. const images = {};
  25670. let loader;
  25671. function loadImage( url ) {
  25672. scope.manager.itemStart( url );
  25673. return loader.load( url, function () {
  25674. scope.manager.itemEnd( url );
  25675. }, undefined, function () {
  25676. scope.manager.itemError( url );
  25677. scope.manager.itemEnd( url );
  25678. } );
  25679. }
  25680. function deserializeImage( image ) {
  25681. if ( typeof image === 'string' ) {
  25682. const url = image;
  25683. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25684. return loadImage( path );
  25685. } else {
  25686. if ( image.data ) {
  25687. return {
  25688. data: getTypedArray( image.type, image.data ),
  25689. width: image.width,
  25690. height: image.height
  25691. };
  25692. } else {
  25693. return null;
  25694. }
  25695. }
  25696. }
  25697. if ( json !== undefined && json.length > 0 ) {
  25698. const manager = new LoadingManager( onLoad );
  25699. loader = new ImageLoader( manager );
  25700. loader.setCrossOrigin( this.crossOrigin );
  25701. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25702. const image = json[ i ];
  25703. const url = image.url;
  25704. if ( Array.isArray( url ) ) {
  25705. // load array of images e.g CubeTexture
  25706. const imageArray = [];
  25707. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25708. const currentUrl = url[ j ];
  25709. const deserializedImage = deserializeImage( currentUrl );
  25710. if ( deserializedImage !== null ) {
  25711. if ( deserializedImage instanceof HTMLImageElement ) {
  25712. imageArray.push( deserializedImage );
  25713. } else {
  25714. // special case: handle array of data textures for cube textures
  25715. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25716. }
  25717. }
  25718. }
  25719. images[ image.uuid ] = new Source( imageArray );
  25720. } else {
  25721. // load single image
  25722. const deserializedImage = deserializeImage( image.url );
  25723. images[ image.uuid ] = new Source( deserializedImage );
  25724. }
  25725. }
  25726. }
  25727. return images;
  25728. }
  25729. async parseImagesAsync( json ) {
  25730. const scope = this;
  25731. const images = {};
  25732. let loader;
  25733. async function deserializeImage( image ) {
  25734. if ( typeof image === 'string' ) {
  25735. const url = image;
  25736. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25737. return await loader.loadAsync( path );
  25738. } else {
  25739. if ( image.data ) {
  25740. return {
  25741. data: getTypedArray( image.type, image.data ),
  25742. width: image.width,
  25743. height: image.height
  25744. };
  25745. } else {
  25746. return null;
  25747. }
  25748. }
  25749. }
  25750. if ( json !== undefined && json.length > 0 ) {
  25751. loader = new ImageLoader( this.manager );
  25752. loader.setCrossOrigin( this.crossOrigin );
  25753. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25754. const image = json[ i ];
  25755. const url = image.url;
  25756. if ( Array.isArray( url ) ) {
  25757. // load array of images e.g CubeTexture
  25758. const imageArray = [];
  25759. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25760. const currentUrl = url[ j ];
  25761. const deserializedImage = await deserializeImage( currentUrl );
  25762. if ( deserializedImage !== null ) {
  25763. if ( deserializedImage instanceof HTMLImageElement ) {
  25764. imageArray.push( deserializedImage );
  25765. } else {
  25766. // special case: handle array of data textures for cube textures
  25767. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25768. }
  25769. }
  25770. }
  25771. images[ image.uuid ] = new Source( imageArray );
  25772. } else {
  25773. // load single image
  25774. const deserializedImage = await deserializeImage( image.url );
  25775. images[ image.uuid ] = new Source( deserializedImage );
  25776. }
  25777. }
  25778. }
  25779. return images;
  25780. }
  25781. parseTextures( json, images ) {
  25782. function parseConstant( value, type ) {
  25783. if ( typeof value === 'number' ) return value;
  25784. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  25785. return type[ value ];
  25786. }
  25787. const textures = {};
  25788. if ( json !== undefined ) {
  25789. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25790. const data = json[ i ];
  25791. if ( data.image === undefined ) {
  25792. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  25793. }
  25794. if ( images[ data.image ] === undefined ) {
  25795. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  25796. }
  25797. const source = images[ data.image ];
  25798. const image = source.data;
  25799. let texture;
  25800. if ( Array.isArray( image ) ) {
  25801. texture = new CubeTexture();
  25802. if ( image.length === 6 ) texture.needsUpdate = true;
  25803. } else {
  25804. if ( image && image.data ) {
  25805. texture = new DataTexture();
  25806. } else {
  25807. texture = new Texture();
  25808. }
  25809. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  25810. }
  25811. texture.source = source;
  25812. texture.uuid = data.uuid;
  25813. if ( data.name !== undefined ) texture.name = data.name;
  25814. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  25815. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  25816. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  25817. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  25818. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  25819. if ( data.wrap !== undefined ) {
  25820. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  25821. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  25822. }
  25823. if ( data.format !== undefined ) texture.format = data.format;
  25824. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  25825. if ( data.type !== undefined ) texture.type = data.type;
  25826. if ( data.encoding !== undefined ) texture.encoding = data.encoding;
  25827. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  25828. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  25829. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  25830. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  25831. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  25832. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  25833. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  25834. if ( data.userData !== undefined ) texture.userData = data.userData;
  25835. textures[ data.uuid ] = texture;
  25836. }
  25837. }
  25838. return textures;
  25839. }
  25840. parseObject( data, geometries, materials, textures, animations ) {
  25841. let object;
  25842. function getGeometry( name ) {
  25843. if ( geometries[ name ] === undefined ) {
  25844. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  25845. }
  25846. return geometries[ name ];
  25847. }
  25848. function getMaterial( name ) {
  25849. if ( name === undefined ) return undefined;
  25850. if ( Array.isArray( name ) ) {
  25851. const array = [];
  25852. for ( let i = 0, l = name.length; i < l; i ++ ) {
  25853. const uuid = name[ i ];
  25854. if ( materials[ uuid ] === undefined ) {
  25855. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  25856. }
  25857. array.push( materials[ uuid ] );
  25858. }
  25859. return array;
  25860. }
  25861. if ( materials[ name ] === undefined ) {
  25862. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  25863. }
  25864. return materials[ name ];
  25865. }
  25866. function getTexture( uuid ) {
  25867. if ( textures[ uuid ] === undefined ) {
  25868. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  25869. }
  25870. return textures[ uuid ];
  25871. }
  25872. let geometry, material;
  25873. switch ( data.type ) {
  25874. case 'Scene':
  25875. object = new Scene();
  25876. if ( data.background !== undefined ) {
  25877. if ( Number.isInteger( data.background ) ) {
  25878. object.background = new Color( data.background );
  25879. } else {
  25880. object.background = getTexture( data.background );
  25881. }
  25882. }
  25883. if ( data.environment !== undefined ) {
  25884. object.environment = getTexture( data.environment );
  25885. }
  25886. if ( data.fog !== undefined ) {
  25887. if ( data.fog.type === 'Fog' ) {
  25888. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  25889. } else if ( data.fog.type === 'FogExp2' ) {
  25890. object.fog = new FogExp2( data.fog.color, data.fog.density );
  25891. }
  25892. }
  25893. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  25894. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  25895. break;
  25896. case 'PerspectiveCamera':
  25897. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  25898. if ( data.focus !== undefined ) object.focus = data.focus;
  25899. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25900. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  25901. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  25902. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25903. break;
  25904. case 'OrthographicCamera':
  25905. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  25906. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25907. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25908. break;
  25909. case 'AmbientLight':
  25910. object = new AmbientLight( data.color, data.intensity );
  25911. break;
  25912. case 'DirectionalLight':
  25913. object = new DirectionalLight( data.color, data.intensity );
  25914. break;
  25915. case 'PointLight':
  25916. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  25917. break;
  25918. case 'RectAreaLight':
  25919. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  25920. break;
  25921. case 'SpotLight':
  25922. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  25923. break;
  25924. case 'HemisphereLight':
  25925. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  25926. break;
  25927. case 'LightProbe':
  25928. object = new LightProbe().fromJSON( data );
  25929. break;
  25930. case 'SkinnedMesh':
  25931. geometry = getGeometry( data.geometry );
  25932. material = getMaterial( data.material );
  25933. object = new SkinnedMesh( geometry, material );
  25934. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  25935. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  25936. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  25937. break;
  25938. case 'Mesh':
  25939. geometry = getGeometry( data.geometry );
  25940. material = getMaterial( data.material );
  25941. object = new Mesh( geometry, material );
  25942. break;
  25943. case 'InstancedMesh':
  25944. geometry = getGeometry( data.geometry );
  25945. material = getMaterial( data.material );
  25946. const count = data.count;
  25947. const instanceMatrix = data.instanceMatrix;
  25948. const instanceColor = data.instanceColor;
  25949. object = new InstancedMesh( geometry, material, count );
  25950. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  25951. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  25952. break;
  25953. case 'LOD':
  25954. object = new LOD();
  25955. break;
  25956. case 'Line':
  25957. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  25958. break;
  25959. case 'LineLoop':
  25960. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  25961. break;
  25962. case 'LineSegments':
  25963. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  25964. break;
  25965. case 'PointCloud':
  25966. case 'Points':
  25967. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  25968. break;
  25969. case 'Sprite':
  25970. object = new Sprite( getMaterial( data.material ) );
  25971. break;
  25972. case 'Group':
  25973. object = new Group();
  25974. break;
  25975. case 'Bone':
  25976. object = new Bone();
  25977. break;
  25978. default:
  25979. object = new Object3D();
  25980. }
  25981. object.uuid = data.uuid;
  25982. if ( data.name !== undefined ) object.name = data.name;
  25983. if ( data.matrix !== undefined ) {
  25984. object.matrix.fromArray( data.matrix );
  25985. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  25986. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  25987. } else {
  25988. if ( data.position !== undefined ) object.position.fromArray( data.position );
  25989. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  25990. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  25991. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  25992. }
  25993. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  25994. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  25995. if ( data.shadow ) {
  25996. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  25997. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  25998. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  25999. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  26000. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  26001. }
  26002. if ( data.visible !== undefined ) object.visible = data.visible;
  26003. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  26004. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  26005. if ( data.userData !== undefined ) object.userData = data.userData;
  26006. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  26007. if ( data.children !== undefined ) {
  26008. const children = data.children;
  26009. for ( let i = 0; i < children.length; i ++ ) {
  26010. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  26011. }
  26012. }
  26013. if ( data.animations !== undefined ) {
  26014. const objectAnimations = data.animations;
  26015. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  26016. const uuid = objectAnimations[ i ];
  26017. object.animations.push( animations[ uuid ] );
  26018. }
  26019. }
  26020. if ( data.type === 'LOD' ) {
  26021. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  26022. const levels = data.levels;
  26023. for ( let l = 0; l < levels.length; l ++ ) {
  26024. const level = levels[ l ];
  26025. const child = object.getObjectByProperty( 'uuid', level.object );
  26026. if ( child !== undefined ) {
  26027. object.addLevel( child, level.distance, level.hysteresis );
  26028. }
  26029. }
  26030. }
  26031. return object;
  26032. }
  26033. bindSkeletons( object, skeletons ) {
  26034. if ( Object.keys( skeletons ).length === 0 ) return;
  26035. object.traverse( function ( child ) {
  26036. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  26037. const skeleton = skeletons[ child.skeleton ];
  26038. if ( skeleton === undefined ) {
  26039. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  26040. } else {
  26041. child.bind( skeleton, child.bindMatrix );
  26042. }
  26043. }
  26044. } );
  26045. }
  26046. }
  26047. const TEXTURE_MAPPING = {
  26048. UVMapping: UVMapping,
  26049. CubeReflectionMapping: CubeReflectionMapping,
  26050. CubeRefractionMapping: CubeRefractionMapping,
  26051. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  26052. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  26053. CubeUVReflectionMapping: CubeUVReflectionMapping
  26054. };
  26055. const TEXTURE_WRAPPING = {
  26056. RepeatWrapping: RepeatWrapping,
  26057. ClampToEdgeWrapping: ClampToEdgeWrapping,
  26058. MirroredRepeatWrapping: MirroredRepeatWrapping
  26059. };
  26060. const TEXTURE_FILTER = {
  26061. NearestFilter: NearestFilter,
  26062. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  26063. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  26064. LinearFilter: LinearFilter,
  26065. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  26066. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  26067. };
  26068. class ImageBitmapLoader extends Loader {
  26069. constructor( manager ) {
  26070. super( manager );
  26071. this.isImageBitmapLoader = true;
  26072. if ( typeof createImageBitmap === 'undefined' ) {
  26073. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  26074. }
  26075. if ( typeof fetch === 'undefined' ) {
  26076. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  26077. }
  26078. this.options = { premultiplyAlpha: 'none' };
  26079. }
  26080. setOptions( options ) {
  26081. this.options = options;
  26082. return this;
  26083. }
  26084. load( url, onLoad, onProgress, onError ) {
  26085. if ( url === undefined ) url = '';
  26086. if ( this.path !== undefined ) url = this.path + url;
  26087. url = this.manager.resolveURL( url );
  26088. const scope = this;
  26089. const cached = Cache.get( url );
  26090. if ( cached !== undefined ) {
  26091. scope.manager.itemStart( url );
  26092. setTimeout( function () {
  26093. if ( onLoad ) onLoad( cached );
  26094. scope.manager.itemEnd( url );
  26095. }, 0 );
  26096. return cached;
  26097. }
  26098. const fetchOptions = {};
  26099. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  26100. fetchOptions.headers = this.requestHeader;
  26101. fetch( url, fetchOptions ).then( function ( res ) {
  26102. return res.blob();
  26103. } ).then( function ( blob ) {
  26104. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  26105. } ).then( function ( imageBitmap ) {
  26106. Cache.add( url, imageBitmap );
  26107. if ( onLoad ) onLoad( imageBitmap );
  26108. scope.manager.itemEnd( url );
  26109. } ).catch( function ( e ) {
  26110. if ( onError ) onError( e );
  26111. scope.manager.itemError( url );
  26112. scope.manager.itemEnd( url );
  26113. } );
  26114. scope.manager.itemStart( url );
  26115. }
  26116. }
  26117. let _context;
  26118. class AudioContext {
  26119. static getContext() {
  26120. if ( _context === undefined ) {
  26121. _context = new ( window.AudioContext || window.webkitAudioContext )();
  26122. }
  26123. return _context;
  26124. }
  26125. static setContext( value ) {
  26126. _context = value;
  26127. }
  26128. }
  26129. class AudioLoader extends Loader {
  26130. constructor( manager ) {
  26131. super( manager );
  26132. }
  26133. load( url, onLoad, onProgress, onError ) {
  26134. const scope = this;
  26135. const loader = new FileLoader( this.manager );
  26136. loader.setResponseType( 'arraybuffer' );
  26137. loader.setPath( this.path );
  26138. loader.setRequestHeader( this.requestHeader );
  26139. loader.setWithCredentials( this.withCredentials );
  26140. loader.load( url, function ( buffer ) {
  26141. try {
  26142. // Create a copy of the buffer. The `decodeAudioData` method
  26143. // detaches the buffer when complete, preventing reuse.
  26144. const bufferCopy = buffer.slice( 0 );
  26145. const context = AudioContext.getContext();
  26146. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  26147. onLoad( audioBuffer );
  26148. } );
  26149. } catch ( e ) {
  26150. if ( onError ) {
  26151. onError( e );
  26152. } else {
  26153. console.error( e );
  26154. }
  26155. scope.manager.itemError( url );
  26156. }
  26157. }, onProgress, onError );
  26158. }
  26159. }
  26160. class HemisphereLightProbe extends LightProbe {
  26161. constructor( skyColor, groundColor, intensity = 1 ) {
  26162. super( undefined, intensity );
  26163. this.isHemisphereLightProbe = true;
  26164. const color1 = new Color().set( skyColor );
  26165. const color2 = new Color().set( groundColor );
  26166. const sky = new Vector3( color1.r, color1.g, color1.b );
  26167. const ground = new Vector3( color2.r, color2.g, color2.b );
  26168. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  26169. const c0 = Math.sqrt( Math.PI );
  26170. const c1 = c0 * Math.sqrt( 0.75 );
  26171. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  26172. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  26173. }
  26174. }
  26175. class AmbientLightProbe extends LightProbe {
  26176. constructor( color, intensity = 1 ) {
  26177. super( undefined, intensity );
  26178. this.isAmbientLightProbe = true;
  26179. const color1 = new Color().set( color );
  26180. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  26181. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  26182. }
  26183. }
  26184. const _eyeRight = /*@__PURE__*/ new Matrix4();
  26185. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  26186. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  26187. class StereoCamera {
  26188. constructor() {
  26189. this.type = 'StereoCamera';
  26190. this.aspect = 1;
  26191. this.eyeSep = 0.064;
  26192. this.cameraL = new PerspectiveCamera();
  26193. this.cameraL.layers.enable( 1 );
  26194. this.cameraL.matrixAutoUpdate = false;
  26195. this.cameraR = new PerspectiveCamera();
  26196. this.cameraR.layers.enable( 2 );
  26197. this.cameraR.matrixAutoUpdate = false;
  26198. this._cache = {
  26199. focus: null,
  26200. fov: null,
  26201. aspect: null,
  26202. near: null,
  26203. far: null,
  26204. zoom: null,
  26205. eyeSep: null
  26206. };
  26207. }
  26208. update( camera ) {
  26209. const cache = this._cache;
  26210. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  26211. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  26212. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  26213. if ( needsUpdate ) {
  26214. cache.focus = camera.focus;
  26215. cache.fov = camera.fov;
  26216. cache.aspect = camera.aspect * this.aspect;
  26217. cache.near = camera.near;
  26218. cache.far = camera.far;
  26219. cache.zoom = camera.zoom;
  26220. cache.eyeSep = this.eyeSep;
  26221. // Off-axis stereoscopic effect based on
  26222. // http://paulbourke.net/stereographics/stereorender/
  26223. _projectionMatrix.copy( camera.projectionMatrix );
  26224. const eyeSepHalf = cache.eyeSep / 2;
  26225. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  26226. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  26227. let xmin, xmax;
  26228. // translate xOffset
  26229. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  26230. _eyeRight.elements[ 12 ] = eyeSepHalf;
  26231. // for left eye
  26232. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  26233. xmax = ymax * cache.aspect + eyeSepOnProjection;
  26234. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26235. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26236. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  26237. // for right eye
  26238. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  26239. xmax = ymax * cache.aspect - eyeSepOnProjection;
  26240. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  26241. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  26242. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  26243. }
  26244. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  26245. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  26246. }
  26247. }
  26248. class Clock {
  26249. constructor( autoStart = true ) {
  26250. this.autoStart = autoStart;
  26251. this.startTime = 0;
  26252. this.oldTime = 0;
  26253. this.elapsedTime = 0;
  26254. this.running = false;
  26255. }
  26256. start() {
  26257. this.startTime = now();
  26258. this.oldTime = this.startTime;
  26259. this.elapsedTime = 0;
  26260. this.running = true;
  26261. }
  26262. stop() {
  26263. this.getElapsedTime();
  26264. this.running = false;
  26265. this.autoStart = false;
  26266. }
  26267. getElapsedTime() {
  26268. this.getDelta();
  26269. return this.elapsedTime;
  26270. }
  26271. getDelta() {
  26272. let diff = 0;
  26273. if ( this.autoStart && ! this.running ) {
  26274. this.start();
  26275. return 0;
  26276. }
  26277. if ( this.running ) {
  26278. const newTime = now();
  26279. diff = ( newTime - this.oldTime ) / 1000;
  26280. this.oldTime = newTime;
  26281. this.elapsedTime += diff;
  26282. }
  26283. return diff;
  26284. }
  26285. }
  26286. function now() {
  26287. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  26288. }
  26289. const _position$1 = /*@__PURE__*/ new Vector3();
  26290. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  26291. const _scale$1 = /*@__PURE__*/ new Vector3();
  26292. const _orientation$1 = /*@__PURE__*/ new Vector3();
  26293. class AudioListener extends Object3D {
  26294. constructor() {
  26295. super();
  26296. this.type = 'AudioListener';
  26297. this.context = AudioContext.getContext();
  26298. this.gain = this.context.createGain();
  26299. this.gain.connect( this.context.destination );
  26300. this.filter = null;
  26301. this.timeDelta = 0;
  26302. // private
  26303. this._clock = new Clock();
  26304. }
  26305. getInput() {
  26306. return this.gain;
  26307. }
  26308. removeFilter() {
  26309. if ( this.filter !== null ) {
  26310. this.gain.disconnect( this.filter );
  26311. this.filter.disconnect( this.context.destination );
  26312. this.gain.connect( this.context.destination );
  26313. this.filter = null;
  26314. }
  26315. return this;
  26316. }
  26317. getFilter() {
  26318. return this.filter;
  26319. }
  26320. setFilter( value ) {
  26321. if ( this.filter !== null ) {
  26322. this.gain.disconnect( this.filter );
  26323. this.filter.disconnect( this.context.destination );
  26324. } else {
  26325. this.gain.disconnect( this.context.destination );
  26326. }
  26327. this.filter = value;
  26328. this.gain.connect( this.filter );
  26329. this.filter.connect( this.context.destination );
  26330. return this;
  26331. }
  26332. getMasterVolume() {
  26333. return this.gain.gain.value;
  26334. }
  26335. setMasterVolume( value ) {
  26336. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26337. return this;
  26338. }
  26339. updateMatrixWorld( force ) {
  26340. super.updateMatrixWorld( force );
  26341. const listener = this.context.listener;
  26342. const up = this.up;
  26343. this.timeDelta = this._clock.getDelta();
  26344. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  26345. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  26346. if ( listener.positionX ) {
  26347. // code path for Chrome (see #14393)
  26348. const endTime = this.context.currentTime + this.timeDelta;
  26349. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  26350. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  26351. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  26352. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  26353. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  26354. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  26355. listener.upX.linearRampToValueAtTime( up.x, endTime );
  26356. listener.upY.linearRampToValueAtTime( up.y, endTime );
  26357. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  26358. } else {
  26359. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  26360. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  26361. }
  26362. }
  26363. }
  26364. class Audio extends Object3D {
  26365. constructor( listener ) {
  26366. super();
  26367. this.type = 'Audio';
  26368. this.listener = listener;
  26369. this.context = listener.context;
  26370. this.gain = this.context.createGain();
  26371. this.gain.connect( listener.getInput() );
  26372. this.autoplay = false;
  26373. this.buffer = null;
  26374. this.detune = 0;
  26375. this.loop = false;
  26376. this.loopStart = 0;
  26377. this.loopEnd = 0;
  26378. this.offset = 0;
  26379. this.duration = undefined;
  26380. this.playbackRate = 1;
  26381. this.isPlaying = false;
  26382. this.hasPlaybackControl = true;
  26383. this.source = null;
  26384. this.sourceType = 'empty';
  26385. this._startedAt = 0;
  26386. this._progress = 0;
  26387. this._connected = false;
  26388. this.filters = [];
  26389. }
  26390. getOutput() {
  26391. return this.gain;
  26392. }
  26393. setNodeSource( audioNode ) {
  26394. this.hasPlaybackControl = false;
  26395. this.sourceType = 'audioNode';
  26396. this.source = audioNode;
  26397. this.connect();
  26398. return this;
  26399. }
  26400. setMediaElementSource( mediaElement ) {
  26401. this.hasPlaybackControl = false;
  26402. this.sourceType = 'mediaNode';
  26403. this.source = this.context.createMediaElementSource( mediaElement );
  26404. this.connect();
  26405. return this;
  26406. }
  26407. setMediaStreamSource( mediaStream ) {
  26408. this.hasPlaybackControl = false;
  26409. this.sourceType = 'mediaStreamNode';
  26410. this.source = this.context.createMediaStreamSource( mediaStream );
  26411. this.connect();
  26412. return this;
  26413. }
  26414. setBuffer( audioBuffer ) {
  26415. this.buffer = audioBuffer;
  26416. this.sourceType = 'buffer';
  26417. if ( this.autoplay ) this.play();
  26418. return this;
  26419. }
  26420. play( delay = 0 ) {
  26421. if ( this.isPlaying === true ) {
  26422. console.warn( 'THREE.Audio: Audio is already playing.' );
  26423. return;
  26424. }
  26425. if ( this.hasPlaybackControl === false ) {
  26426. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26427. return;
  26428. }
  26429. this._startedAt = this.context.currentTime + delay;
  26430. const source = this.context.createBufferSource();
  26431. source.buffer = this.buffer;
  26432. source.loop = this.loop;
  26433. source.loopStart = this.loopStart;
  26434. source.loopEnd = this.loopEnd;
  26435. source.onended = this.onEnded.bind( this );
  26436. source.start( this._startedAt, this._progress + this.offset, this.duration );
  26437. this.isPlaying = true;
  26438. this.source = source;
  26439. this.setDetune( this.detune );
  26440. this.setPlaybackRate( this.playbackRate );
  26441. return this.connect();
  26442. }
  26443. pause() {
  26444. if ( this.hasPlaybackControl === false ) {
  26445. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26446. return;
  26447. }
  26448. if ( this.isPlaying === true ) {
  26449. // update current progress
  26450. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  26451. if ( this.loop === true ) {
  26452. // ensure _progress does not exceed duration with looped audios
  26453. this._progress = this._progress % ( this.duration || this.buffer.duration );
  26454. }
  26455. this.source.stop();
  26456. this.source.onended = null;
  26457. this.isPlaying = false;
  26458. }
  26459. return this;
  26460. }
  26461. stop() {
  26462. if ( this.hasPlaybackControl === false ) {
  26463. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26464. return;
  26465. }
  26466. this._progress = 0;
  26467. if ( this.source !== null ) {
  26468. this.source.stop();
  26469. this.source.onended = null;
  26470. }
  26471. this.isPlaying = false;
  26472. return this;
  26473. }
  26474. connect() {
  26475. if ( this.filters.length > 0 ) {
  26476. this.source.connect( this.filters[ 0 ] );
  26477. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26478. this.filters[ i - 1 ].connect( this.filters[ i ] );
  26479. }
  26480. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  26481. } else {
  26482. this.source.connect( this.getOutput() );
  26483. }
  26484. this._connected = true;
  26485. return this;
  26486. }
  26487. disconnect() {
  26488. if ( this.filters.length > 0 ) {
  26489. this.source.disconnect( this.filters[ 0 ] );
  26490. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  26491. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  26492. }
  26493. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  26494. } else {
  26495. this.source.disconnect( this.getOutput() );
  26496. }
  26497. this._connected = false;
  26498. return this;
  26499. }
  26500. getFilters() {
  26501. return this.filters;
  26502. }
  26503. setFilters( value ) {
  26504. if ( ! value ) value = [];
  26505. if ( this._connected === true ) {
  26506. this.disconnect();
  26507. this.filters = value.slice();
  26508. this.connect();
  26509. } else {
  26510. this.filters = value.slice();
  26511. }
  26512. return this;
  26513. }
  26514. setDetune( value ) {
  26515. this.detune = value;
  26516. if ( this.source.detune === undefined ) return; // only set detune when available
  26517. if ( this.isPlaying === true ) {
  26518. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  26519. }
  26520. return this;
  26521. }
  26522. getDetune() {
  26523. return this.detune;
  26524. }
  26525. getFilter() {
  26526. return this.getFilters()[ 0 ];
  26527. }
  26528. setFilter( filter ) {
  26529. return this.setFilters( filter ? [ filter ] : [] );
  26530. }
  26531. setPlaybackRate( value ) {
  26532. if ( this.hasPlaybackControl === false ) {
  26533. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26534. return;
  26535. }
  26536. this.playbackRate = value;
  26537. if ( this.isPlaying === true ) {
  26538. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  26539. }
  26540. return this;
  26541. }
  26542. getPlaybackRate() {
  26543. return this.playbackRate;
  26544. }
  26545. onEnded() {
  26546. this.isPlaying = false;
  26547. }
  26548. getLoop() {
  26549. if ( this.hasPlaybackControl === false ) {
  26550. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26551. return false;
  26552. }
  26553. return this.loop;
  26554. }
  26555. setLoop( value ) {
  26556. if ( this.hasPlaybackControl === false ) {
  26557. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  26558. return;
  26559. }
  26560. this.loop = value;
  26561. if ( this.isPlaying === true ) {
  26562. this.source.loop = this.loop;
  26563. }
  26564. return this;
  26565. }
  26566. setLoopStart( value ) {
  26567. this.loopStart = value;
  26568. return this;
  26569. }
  26570. setLoopEnd( value ) {
  26571. this.loopEnd = value;
  26572. return this;
  26573. }
  26574. getVolume() {
  26575. return this.gain.gain.value;
  26576. }
  26577. setVolume( value ) {
  26578. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  26579. return this;
  26580. }
  26581. }
  26582. const _position = /*@__PURE__*/ new Vector3();
  26583. const _quaternion = /*@__PURE__*/ new Quaternion();
  26584. const _scale = /*@__PURE__*/ new Vector3();
  26585. const _orientation = /*@__PURE__*/ new Vector3();
  26586. class PositionalAudio extends Audio {
  26587. constructor( listener ) {
  26588. super( listener );
  26589. this.panner = this.context.createPanner();
  26590. this.panner.panningModel = 'HRTF';
  26591. this.panner.connect( this.gain );
  26592. }
  26593. disconnect() {
  26594. super.disconnect();
  26595. this.panner.disconnect( this.gain );
  26596. }
  26597. getOutput() {
  26598. return this.panner;
  26599. }
  26600. getRefDistance() {
  26601. return this.panner.refDistance;
  26602. }
  26603. setRefDistance( value ) {
  26604. this.panner.refDistance = value;
  26605. return this;
  26606. }
  26607. getRolloffFactor() {
  26608. return this.panner.rolloffFactor;
  26609. }
  26610. setRolloffFactor( value ) {
  26611. this.panner.rolloffFactor = value;
  26612. return this;
  26613. }
  26614. getDistanceModel() {
  26615. return this.panner.distanceModel;
  26616. }
  26617. setDistanceModel( value ) {
  26618. this.panner.distanceModel = value;
  26619. return this;
  26620. }
  26621. getMaxDistance() {
  26622. return this.panner.maxDistance;
  26623. }
  26624. setMaxDistance( value ) {
  26625. this.panner.maxDistance = value;
  26626. return this;
  26627. }
  26628. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  26629. this.panner.coneInnerAngle = coneInnerAngle;
  26630. this.panner.coneOuterAngle = coneOuterAngle;
  26631. this.panner.coneOuterGain = coneOuterGain;
  26632. return this;
  26633. }
  26634. updateMatrixWorld( force ) {
  26635. super.updateMatrixWorld( force );
  26636. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  26637. this.matrixWorld.decompose( _position, _quaternion, _scale );
  26638. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  26639. const panner = this.panner;
  26640. if ( panner.positionX ) {
  26641. // code path for Chrome and Firefox (see #14393)
  26642. const endTime = this.context.currentTime + this.listener.timeDelta;
  26643. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  26644. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  26645. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  26646. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  26647. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  26648. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  26649. } else {
  26650. panner.setPosition( _position.x, _position.y, _position.z );
  26651. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  26652. }
  26653. }
  26654. }
  26655. class AudioAnalyser {
  26656. constructor( audio, fftSize = 2048 ) {
  26657. this.analyser = audio.context.createAnalyser();
  26658. this.analyser.fftSize = fftSize;
  26659. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  26660. audio.getOutput().connect( this.analyser );
  26661. }
  26662. getFrequencyData() {
  26663. this.analyser.getByteFrequencyData( this.data );
  26664. return this.data;
  26665. }
  26666. getAverageFrequency() {
  26667. let value = 0;
  26668. const data = this.getFrequencyData();
  26669. for ( let i = 0; i < data.length; i ++ ) {
  26670. value += data[ i ];
  26671. }
  26672. return value / data.length;
  26673. }
  26674. }
  26675. class PropertyMixer {
  26676. constructor( binding, typeName, valueSize ) {
  26677. this.binding = binding;
  26678. this.valueSize = valueSize;
  26679. let mixFunction,
  26680. mixFunctionAdditive,
  26681. setIdentity;
  26682. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  26683. //
  26684. // interpolators can use .buffer as their .result
  26685. // the data then goes to 'incoming'
  26686. //
  26687. // 'accu0' and 'accu1' are used frame-interleaved for
  26688. // the cumulative result and are compared to detect
  26689. // changes
  26690. //
  26691. // 'orig' stores the original state of the property
  26692. //
  26693. // 'add' is used for additive cumulative results
  26694. //
  26695. // 'work' is optional and is only present for quaternion types. It is used
  26696. // to store intermediate quaternion multiplication results
  26697. switch ( typeName ) {
  26698. case 'quaternion':
  26699. mixFunction = this._slerp;
  26700. mixFunctionAdditive = this._slerpAdditive;
  26701. setIdentity = this._setAdditiveIdentityQuaternion;
  26702. this.buffer = new Float64Array( valueSize * 6 );
  26703. this._workIndex = 5;
  26704. break;
  26705. case 'string':
  26706. case 'bool':
  26707. mixFunction = this._select;
  26708. // Use the regular mix function and for additive on these types,
  26709. // additive is not relevant for non-numeric types
  26710. mixFunctionAdditive = this._select;
  26711. setIdentity = this._setAdditiveIdentityOther;
  26712. this.buffer = new Array( valueSize * 5 );
  26713. break;
  26714. default:
  26715. mixFunction = this._lerp;
  26716. mixFunctionAdditive = this._lerpAdditive;
  26717. setIdentity = this._setAdditiveIdentityNumeric;
  26718. this.buffer = new Float64Array( valueSize * 5 );
  26719. }
  26720. this._mixBufferRegion = mixFunction;
  26721. this._mixBufferRegionAdditive = mixFunctionAdditive;
  26722. this._setIdentity = setIdentity;
  26723. this._origIndex = 3;
  26724. this._addIndex = 4;
  26725. this.cumulativeWeight = 0;
  26726. this.cumulativeWeightAdditive = 0;
  26727. this.useCount = 0;
  26728. this.referenceCount = 0;
  26729. }
  26730. // accumulate data in the 'incoming' region into 'accu<i>'
  26731. accumulate( accuIndex, weight ) {
  26732. // note: happily accumulating nothing when weight = 0, the caller knows
  26733. // the weight and shouldn't have made the call in the first place
  26734. const buffer = this.buffer,
  26735. stride = this.valueSize,
  26736. offset = accuIndex * stride + stride;
  26737. let currentWeight = this.cumulativeWeight;
  26738. if ( currentWeight === 0 ) {
  26739. // accuN := incoming * weight
  26740. for ( let i = 0; i !== stride; ++ i ) {
  26741. buffer[ offset + i ] = buffer[ i ];
  26742. }
  26743. currentWeight = weight;
  26744. } else {
  26745. // accuN := accuN + incoming * weight
  26746. currentWeight += weight;
  26747. const mix = weight / currentWeight;
  26748. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  26749. }
  26750. this.cumulativeWeight = currentWeight;
  26751. }
  26752. // accumulate data in the 'incoming' region into 'add'
  26753. accumulateAdditive( weight ) {
  26754. const buffer = this.buffer,
  26755. stride = this.valueSize,
  26756. offset = stride * this._addIndex;
  26757. if ( this.cumulativeWeightAdditive === 0 ) {
  26758. // add = identity
  26759. this._setIdentity();
  26760. }
  26761. // add := add + incoming * weight
  26762. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  26763. this.cumulativeWeightAdditive += weight;
  26764. }
  26765. // apply the state of 'accu<i>' to the binding when accus differ
  26766. apply( accuIndex ) {
  26767. const stride = this.valueSize,
  26768. buffer = this.buffer,
  26769. offset = accuIndex * stride + stride,
  26770. weight = this.cumulativeWeight,
  26771. weightAdditive = this.cumulativeWeightAdditive,
  26772. binding = this.binding;
  26773. this.cumulativeWeight = 0;
  26774. this.cumulativeWeightAdditive = 0;
  26775. if ( weight < 1 ) {
  26776. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26777. const originalValueOffset = stride * this._origIndex;
  26778. this._mixBufferRegion(
  26779. buffer, offset, originalValueOffset, 1 - weight, stride );
  26780. }
  26781. if ( weightAdditive > 0 ) {
  26782. // accuN := accuN + additive accuN
  26783. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  26784. }
  26785. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  26786. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  26787. // value has changed -> update scene graph
  26788. binding.setValue( buffer, offset );
  26789. break;
  26790. }
  26791. }
  26792. }
  26793. // remember the state of the bound property and copy it to both accus
  26794. saveOriginalState() {
  26795. const binding = this.binding;
  26796. const buffer = this.buffer,
  26797. stride = this.valueSize,
  26798. originalValueOffset = stride * this._origIndex;
  26799. binding.getValue( buffer, originalValueOffset );
  26800. // accu[0..1] := orig -- initially detect changes against the original
  26801. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  26802. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  26803. }
  26804. // Add to identity for additive
  26805. this._setIdentity();
  26806. this.cumulativeWeight = 0;
  26807. this.cumulativeWeightAdditive = 0;
  26808. }
  26809. // apply the state previously taken via 'saveOriginalState' to the binding
  26810. restoreOriginalState() {
  26811. const originalValueOffset = this.valueSize * 3;
  26812. this.binding.setValue( this.buffer, originalValueOffset );
  26813. }
  26814. _setAdditiveIdentityNumeric() {
  26815. const startIndex = this._addIndex * this.valueSize;
  26816. const endIndex = startIndex + this.valueSize;
  26817. for ( let i = startIndex; i < endIndex; i ++ ) {
  26818. this.buffer[ i ] = 0;
  26819. }
  26820. }
  26821. _setAdditiveIdentityQuaternion() {
  26822. this._setAdditiveIdentityNumeric();
  26823. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  26824. }
  26825. _setAdditiveIdentityOther() {
  26826. const startIndex = this._origIndex * this.valueSize;
  26827. const targetIndex = this._addIndex * this.valueSize;
  26828. for ( let i = 0; i < this.valueSize; i ++ ) {
  26829. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  26830. }
  26831. }
  26832. // mix functions
  26833. _select( buffer, dstOffset, srcOffset, t, stride ) {
  26834. if ( t >= 0.5 ) {
  26835. for ( let i = 0; i !== stride; ++ i ) {
  26836. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  26837. }
  26838. }
  26839. }
  26840. _slerp( buffer, dstOffset, srcOffset, t ) {
  26841. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  26842. }
  26843. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  26844. const workOffset = this._workIndex * stride;
  26845. // Store result in intermediate buffer offset
  26846. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  26847. // Slerp to the intermediate result
  26848. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  26849. }
  26850. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  26851. const s = 1 - t;
  26852. for ( let i = 0; i !== stride; ++ i ) {
  26853. const j = dstOffset + i;
  26854. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  26855. }
  26856. }
  26857. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  26858. for ( let i = 0; i !== stride; ++ i ) {
  26859. const j = dstOffset + i;
  26860. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  26861. }
  26862. }
  26863. }
  26864. // Characters [].:/ are reserved for track binding syntax.
  26865. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  26866. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  26867. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  26868. // only latin characters, and the unicode \p{L} is not yet supported. So
  26869. // instead, we exclude reserved characters and match everything else.
  26870. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  26871. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  26872. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  26873. // be matched to parse the rest of the track name.
  26874. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  26875. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  26876. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  26877. // Object on target node, and accessor. May not contain reserved
  26878. // characters. Accessor may contain any character except closing bracket.
  26879. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  26880. // Property and accessor. May not contain reserved characters. Accessor may
  26881. // contain any non-bracket characters.
  26882. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  26883. const _trackRe = new RegExp( ''
  26884. + '^'
  26885. + _directoryRe
  26886. + _nodeRe
  26887. + _objectRe
  26888. + _propertyRe
  26889. + '$'
  26890. );
  26891. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  26892. class Composite {
  26893. constructor( targetGroup, path, optionalParsedPath ) {
  26894. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  26895. this._targetGroup = targetGroup;
  26896. this._bindings = targetGroup.subscribe_( path, parsedPath );
  26897. }
  26898. getValue( array, offset ) {
  26899. this.bind(); // bind all binding
  26900. const firstValidIndex = this._targetGroup.nCachedObjects_,
  26901. binding = this._bindings[ firstValidIndex ];
  26902. // and only call .getValue on the first
  26903. if ( binding !== undefined ) binding.getValue( array, offset );
  26904. }
  26905. setValue( array, offset ) {
  26906. const bindings = this._bindings;
  26907. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26908. bindings[ i ].setValue( array, offset );
  26909. }
  26910. }
  26911. bind() {
  26912. const bindings = this._bindings;
  26913. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26914. bindings[ i ].bind();
  26915. }
  26916. }
  26917. unbind() {
  26918. const bindings = this._bindings;
  26919. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26920. bindings[ i ].unbind();
  26921. }
  26922. }
  26923. }
  26924. // Note: This class uses a State pattern on a per-method basis:
  26925. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  26926. // prototype version of these methods with one that represents
  26927. // the bound state. When the property is not found, the methods
  26928. // become no-ops.
  26929. class PropertyBinding {
  26930. constructor( rootNode, path, parsedPath ) {
  26931. this.path = path;
  26932. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  26933. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  26934. this.rootNode = rootNode;
  26935. // initial state of these methods that calls 'bind'
  26936. this.getValue = this._getValue_unbound;
  26937. this.setValue = this._setValue_unbound;
  26938. }
  26939. static create( root, path, parsedPath ) {
  26940. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  26941. return new PropertyBinding( root, path, parsedPath );
  26942. } else {
  26943. return new PropertyBinding.Composite( root, path, parsedPath );
  26944. }
  26945. }
  26946. /**
  26947. * Replaces spaces with underscores and removes unsupported characters from
  26948. * node names, to ensure compatibility with parseTrackName().
  26949. *
  26950. * @param {string} name Node name to be sanitized.
  26951. * @return {string}
  26952. */
  26953. static sanitizeNodeName( name ) {
  26954. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  26955. }
  26956. static parseTrackName( trackName ) {
  26957. const matches = _trackRe.exec( trackName );
  26958. if ( matches === null ) {
  26959. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  26960. }
  26961. const results = {
  26962. // directoryName: matches[ 1 ], // (tschw) currently unused
  26963. nodeName: matches[ 2 ],
  26964. objectName: matches[ 3 ],
  26965. objectIndex: matches[ 4 ],
  26966. propertyName: matches[ 5 ], // required
  26967. propertyIndex: matches[ 6 ]
  26968. };
  26969. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  26970. if ( lastDot !== undefined && lastDot !== - 1 ) {
  26971. const objectName = results.nodeName.substring( lastDot + 1 );
  26972. // Object names must be checked against an allowlist. Otherwise, there
  26973. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26974. // 'bar' could be the objectName, or part of a nodeName (which can
  26975. // include '.' characters).
  26976. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  26977. results.nodeName = results.nodeName.substring( 0, lastDot );
  26978. results.objectName = objectName;
  26979. }
  26980. }
  26981. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  26982. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  26983. }
  26984. return results;
  26985. }
  26986. static findNode( root, nodeName ) {
  26987. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  26988. return root;
  26989. }
  26990. // search into skeleton bones.
  26991. if ( root.skeleton ) {
  26992. const bone = root.skeleton.getBoneByName( nodeName );
  26993. if ( bone !== undefined ) {
  26994. return bone;
  26995. }
  26996. }
  26997. // search into node subtree.
  26998. if ( root.children ) {
  26999. const searchNodeSubtree = function ( children ) {
  27000. for ( let i = 0; i < children.length; i ++ ) {
  27001. const childNode = children[ i ];
  27002. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  27003. return childNode;
  27004. }
  27005. const result = searchNodeSubtree( childNode.children );
  27006. if ( result ) return result;
  27007. }
  27008. return null;
  27009. };
  27010. const subTreeNode = searchNodeSubtree( root.children );
  27011. if ( subTreeNode ) {
  27012. return subTreeNode;
  27013. }
  27014. }
  27015. return null;
  27016. }
  27017. // these are used to "bind" a nonexistent property
  27018. _getValue_unavailable() {}
  27019. _setValue_unavailable() {}
  27020. // Getters
  27021. _getValue_direct( buffer, offset ) {
  27022. buffer[ offset ] = this.targetObject[ this.propertyName ];
  27023. }
  27024. _getValue_array( buffer, offset ) {
  27025. const source = this.resolvedProperty;
  27026. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  27027. buffer[ offset ++ ] = source[ i ];
  27028. }
  27029. }
  27030. _getValue_arrayElement( buffer, offset ) {
  27031. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  27032. }
  27033. _getValue_toArray( buffer, offset ) {
  27034. this.resolvedProperty.toArray( buffer, offset );
  27035. }
  27036. // Direct
  27037. _setValue_direct( buffer, offset ) {
  27038. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27039. }
  27040. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  27041. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27042. this.targetObject.needsUpdate = true;
  27043. }
  27044. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27045. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27046. this.targetObject.matrixWorldNeedsUpdate = true;
  27047. }
  27048. // EntireArray
  27049. _setValue_array( buffer, offset ) {
  27050. const dest = this.resolvedProperty;
  27051. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27052. dest[ i ] = buffer[ offset ++ ];
  27053. }
  27054. }
  27055. _setValue_array_setNeedsUpdate( buffer, offset ) {
  27056. const dest = this.resolvedProperty;
  27057. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27058. dest[ i ] = buffer[ offset ++ ];
  27059. }
  27060. this.targetObject.needsUpdate = true;
  27061. }
  27062. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27063. const dest = this.resolvedProperty;
  27064. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  27065. dest[ i ] = buffer[ offset ++ ];
  27066. }
  27067. this.targetObject.matrixWorldNeedsUpdate = true;
  27068. }
  27069. // ArrayElement
  27070. _setValue_arrayElement( buffer, offset ) {
  27071. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27072. }
  27073. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  27074. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27075. this.targetObject.needsUpdate = true;
  27076. }
  27077. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27078. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  27079. this.targetObject.matrixWorldNeedsUpdate = true;
  27080. }
  27081. // HasToFromArray
  27082. _setValue_fromArray( buffer, offset ) {
  27083. this.resolvedProperty.fromArray( buffer, offset );
  27084. }
  27085. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  27086. this.resolvedProperty.fromArray( buffer, offset );
  27087. this.targetObject.needsUpdate = true;
  27088. }
  27089. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27090. this.resolvedProperty.fromArray( buffer, offset );
  27091. this.targetObject.matrixWorldNeedsUpdate = true;
  27092. }
  27093. _getValue_unbound( targetArray, offset ) {
  27094. this.bind();
  27095. this.getValue( targetArray, offset );
  27096. }
  27097. _setValue_unbound( sourceArray, offset ) {
  27098. this.bind();
  27099. this.setValue( sourceArray, offset );
  27100. }
  27101. // create getter / setter pair for a property in the scene graph
  27102. bind() {
  27103. let targetObject = this.node;
  27104. const parsedPath = this.parsedPath;
  27105. const objectName = parsedPath.objectName;
  27106. const propertyName = parsedPath.propertyName;
  27107. let propertyIndex = parsedPath.propertyIndex;
  27108. if ( ! targetObject ) {
  27109. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  27110. this.node = targetObject;
  27111. }
  27112. // set fail state so we can just 'return' on error
  27113. this.getValue = this._getValue_unavailable;
  27114. this.setValue = this._setValue_unavailable;
  27115. // ensure there is a value node
  27116. if ( ! targetObject ) {
  27117. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  27118. return;
  27119. }
  27120. if ( objectName ) {
  27121. let objectIndex = parsedPath.objectIndex;
  27122. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  27123. switch ( objectName ) {
  27124. case 'materials':
  27125. if ( ! targetObject.material ) {
  27126. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  27127. return;
  27128. }
  27129. if ( ! targetObject.material.materials ) {
  27130. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  27131. return;
  27132. }
  27133. targetObject = targetObject.material.materials;
  27134. break;
  27135. case 'bones':
  27136. if ( ! targetObject.skeleton ) {
  27137. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  27138. return;
  27139. }
  27140. // potential future optimization: skip this if propertyIndex is already an integer
  27141. // and convert the integer string to a true integer.
  27142. targetObject = targetObject.skeleton.bones;
  27143. // support resolving morphTarget names into indices.
  27144. for ( let i = 0; i < targetObject.length; i ++ ) {
  27145. if ( targetObject[ i ].name === objectIndex ) {
  27146. objectIndex = i;
  27147. break;
  27148. }
  27149. }
  27150. break;
  27151. case 'map':
  27152. if ( 'map' in targetObject ) {
  27153. targetObject = targetObject.map;
  27154. break;
  27155. }
  27156. if ( ! targetObject.material ) {
  27157. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  27158. return;
  27159. }
  27160. if ( ! targetObject.material.map ) {
  27161. console.error( 'THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  27162. return;
  27163. }
  27164. targetObject = targetObject.material.map;
  27165. break;
  27166. default:
  27167. if ( targetObject[ objectName ] === undefined ) {
  27168. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  27169. return;
  27170. }
  27171. targetObject = targetObject[ objectName ];
  27172. }
  27173. if ( objectIndex !== undefined ) {
  27174. if ( targetObject[ objectIndex ] === undefined ) {
  27175. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  27176. return;
  27177. }
  27178. targetObject = targetObject[ objectIndex ];
  27179. }
  27180. }
  27181. // resolve property
  27182. const nodeProperty = targetObject[ propertyName ];
  27183. if ( nodeProperty === undefined ) {
  27184. const nodeName = parsedPath.nodeName;
  27185. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  27186. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  27187. return;
  27188. }
  27189. // determine versioning scheme
  27190. let versioning = this.Versioning.None;
  27191. this.targetObject = targetObject;
  27192. if ( targetObject.needsUpdate !== undefined ) { // material
  27193. versioning = this.Versioning.NeedsUpdate;
  27194. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  27195. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  27196. }
  27197. // determine how the property gets bound
  27198. let bindingType = this.BindingType.Direct;
  27199. if ( propertyIndex !== undefined ) {
  27200. // access a sub element of the property array (only primitives are supported right now)
  27201. if ( propertyName === 'morphTargetInfluences' ) {
  27202. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  27203. // support resolving morphTarget names into indices.
  27204. if ( ! targetObject.geometry ) {
  27205. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  27206. return;
  27207. }
  27208. if ( ! targetObject.geometry.morphAttributes ) {
  27209. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  27210. return;
  27211. }
  27212. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  27213. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  27214. }
  27215. }
  27216. bindingType = this.BindingType.ArrayElement;
  27217. this.resolvedProperty = nodeProperty;
  27218. this.propertyIndex = propertyIndex;
  27219. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  27220. // must use copy for Object3D.Euler/Quaternion
  27221. bindingType = this.BindingType.HasFromToArray;
  27222. this.resolvedProperty = nodeProperty;
  27223. } else if ( Array.isArray( nodeProperty ) ) {
  27224. bindingType = this.BindingType.EntireArray;
  27225. this.resolvedProperty = nodeProperty;
  27226. } else {
  27227. this.propertyName = propertyName;
  27228. }
  27229. // select getter / setter
  27230. this.getValue = this.GetterByBindingType[ bindingType ];
  27231. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  27232. }
  27233. unbind() {
  27234. this.node = null;
  27235. // back to the prototype version of getValue / setValue
  27236. // note: avoiding to mutate the shape of 'this' via 'delete'
  27237. this.getValue = this._getValue_unbound;
  27238. this.setValue = this._setValue_unbound;
  27239. }
  27240. }
  27241. PropertyBinding.Composite = Composite;
  27242. PropertyBinding.prototype.BindingType = {
  27243. Direct: 0,
  27244. EntireArray: 1,
  27245. ArrayElement: 2,
  27246. HasFromToArray: 3
  27247. };
  27248. PropertyBinding.prototype.Versioning = {
  27249. None: 0,
  27250. NeedsUpdate: 1,
  27251. MatrixWorldNeedsUpdate: 2
  27252. };
  27253. PropertyBinding.prototype.GetterByBindingType = [
  27254. PropertyBinding.prototype._getValue_direct,
  27255. PropertyBinding.prototype._getValue_array,
  27256. PropertyBinding.prototype._getValue_arrayElement,
  27257. PropertyBinding.prototype._getValue_toArray,
  27258. ];
  27259. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  27260. [
  27261. // Direct
  27262. PropertyBinding.prototype._setValue_direct,
  27263. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  27264. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  27265. ], [
  27266. // EntireArray
  27267. PropertyBinding.prototype._setValue_array,
  27268. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  27269. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  27270. ], [
  27271. // ArrayElement
  27272. PropertyBinding.prototype._setValue_arrayElement,
  27273. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  27274. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  27275. ], [
  27276. // HasToFromArray
  27277. PropertyBinding.prototype._setValue_fromArray,
  27278. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  27279. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  27280. ]
  27281. ];
  27282. /**
  27283. *
  27284. * A group of objects that receives a shared animation state.
  27285. *
  27286. * Usage:
  27287. *
  27288. * - Add objects you would otherwise pass as 'root' to the
  27289. * constructor or the .clipAction method of AnimationMixer.
  27290. *
  27291. * - Instead pass this object as 'root'.
  27292. *
  27293. * - You can also add and remove objects later when the mixer
  27294. * is running.
  27295. *
  27296. * Note:
  27297. *
  27298. * Objects of this class appear as one object to the mixer,
  27299. * so cache control of the individual objects must be done
  27300. * on the group.
  27301. *
  27302. * Limitation:
  27303. *
  27304. * - The animated properties must be compatible among the
  27305. * all objects in the group.
  27306. *
  27307. * - A single property can either be controlled through a
  27308. * target group or directly, but not both.
  27309. */
  27310. class AnimationObjectGroup {
  27311. constructor() {
  27312. this.isAnimationObjectGroup = true;
  27313. this.uuid = generateUUID();
  27314. // cached objects followed by the active ones
  27315. this._objects = Array.prototype.slice.call( arguments );
  27316. this.nCachedObjects_ = 0; // threshold
  27317. // note: read by PropertyBinding.Composite
  27318. const indices = {};
  27319. this._indicesByUUID = indices; // for bookkeeping
  27320. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27321. indices[ arguments[ i ].uuid ] = i;
  27322. }
  27323. this._paths = []; // inside: string
  27324. this._parsedPaths = []; // inside: { we don't care, here }
  27325. this._bindings = []; // inside: Array< PropertyBinding >
  27326. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  27327. const scope = this;
  27328. this.stats = {
  27329. objects: {
  27330. get total() {
  27331. return scope._objects.length;
  27332. },
  27333. get inUse() {
  27334. return this.total - scope.nCachedObjects_;
  27335. }
  27336. },
  27337. get bindingsPerObject() {
  27338. return scope._bindings.length;
  27339. }
  27340. };
  27341. }
  27342. add() {
  27343. const objects = this._objects,
  27344. indicesByUUID = this._indicesByUUID,
  27345. paths = this._paths,
  27346. parsedPaths = this._parsedPaths,
  27347. bindings = this._bindings,
  27348. nBindings = bindings.length;
  27349. let knownObject = undefined,
  27350. nObjects = objects.length,
  27351. nCachedObjects = this.nCachedObjects_;
  27352. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27353. const object = arguments[ i ],
  27354. uuid = object.uuid;
  27355. let index = indicesByUUID[ uuid ];
  27356. if ( index === undefined ) {
  27357. // unknown object -> add it to the ACTIVE region
  27358. index = nObjects ++;
  27359. indicesByUUID[ uuid ] = index;
  27360. objects.push( object );
  27361. // accounting is done, now do the same for all bindings
  27362. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27363. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  27364. }
  27365. } else if ( index < nCachedObjects ) {
  27366. knownObject = objects[ index ];
  27367. // move existing object to the ACTIVE region
  27368. const firstActiveIndex = -- nCachedObjects,
  27369. lastCachedObject = objects[ firstActiveIndex ];
  27370. indicesByUUID[ lastCachedObject.uuid ] = index;
  27371. objects[ index ] = lastCachedObject;
  27372. indicesByUUID[ uuid ] = firstActiveIndex;
  27373. objects[ firstActiveIndex ] = object;
  27374. // accounting is done, now do the same for all bindings
  27375. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27376. const bindingsForPath = bindings[ j ],
  27377. lastCached = bindingsForPath[ firstActiveIndex ];
  27378. let binding = bindingsForPath[ index ];
  27379. bindingsForPath[ index ] = lastCached;
  27380. if ( binding === undefined ) {
  27381. // since we do not bother to create new bindings
  27382. // for objects that are cached, the binding may
  27383. // or may not exist
  27384. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  27385. }
  27386. bindingsForPath[ firstActiveIndex ] = binding;
  27387. }
  27388. } else if ( objects[ index ] !== knownObject ) {
  27389. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  27390. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  27391. } // else the object is already where we want it to be
  27392. } // for arguments
  27393. this.nCachedObjects_ = nCachedObjects;
  27394. }
  27395. remove() {
  27396. const objects = this._objects,
  27397. indicesByUUID = this._indicesByUUID,
  27398. bindings = this._bindings,
  27399. nBindings = bindings.length;
  27400. let nCachedObjects = this.nCachedObjects_;
  27401. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27402. const object = arguments[ i ],
  27403. uuid = object.uuid,
  27404. index = indicesByUUID[ uuid ];
  27405. if ( index !== undefined && index >= nCachedObjects ) {
  27406. // move existing object into the CACHED region
  27407. const lastCachedIndex = nCachedObjects ++,
  27408. firstActiveObject = objects[ lastCachedIndex ];
  27409. indicesByUUID[ firstActiveObject.uuid ] = index;
  27410. objects[ index ] = firstActiveObject;
  27411. indicesByUUID[ uuid ] = lastCachedIndex;
  27412. objects[ lastCachedIndex ] = object;
  27413. // accounting is done, now do the same for all bindings
  27414. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27415. const bindingsForPath = bindings[ j ],
  27416. firstActive = bindingsForPath[ lastCachedIndex ],
  27417. binding = bindingsForPath[ index ];
  27418. bindingsForPath[ index ] = firstActive;
  27419. bindingsForPath[ lastCachedIndex ] = binding;
  27420. }
  27421. }
  27422. } // for arguments
  27423. this.nCachedObjects_ = nCachedObjects;
  27424. }
  27425. // remove & forget
  27426. uncache() {
  27427. const objects = this._objects,
  27428. indicesByUUID = this._indicesByUUID,
  27429. bindings = this._bindings,
  27430. nBindings = bindings.length;
  27431. let nCachedObjects = this.nCachedObjects_,
  27432. nObjects = objects.length;
  27433. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  27434. const object = arguments[ i ],
  27435. uuid = object.uuid,
  27436. index = indicesByUUID[ uuid ];
  27437. if ( index !== undefined ) {
  27438. delete indicesByUUID[ uuid ];
  27439. if ( index < nCachedObjects ) {
  27440. // object is cached, shrink the CACHED region
  27441. const firstActiveIndex = -- nCachedObjects,
  27442. lastCachedObject = objects[ firstActiveIndex ],
  27443. lastIndex = -- nObjects,
  27444. lastObject = objects[ lastIndex ];
  27445. // last cached object takes this object's place
  27446. indicesByUUID[ lastCachedObject.uuid ] = index;
  27447. objects[ index ] = lastCachedObject;
  27448. // last object goes to the activated slot and pop
  27449. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  27450. objects[ firstActiveIndex ] = lastObject;
  27451. objects.pop();
  27452. // accounting is done, now do the same for all bindings
  27453. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27454. const bindingsForPath = bindings[ j ],
  27455. lastCached = bindingsForPath[ firstActiveIndex ],
  27456. last = bindingsForPath[ lastIndex ];
  27457. bindingsForPath[ index ] = lastCached;
  27458. bindingsForPath[ firstActiveIndex ] = last;
  27459. bindingsForPath.pop();
  27460. }
  27461. } else {
  27462. // object is active, just swap with the last and pop
  27463. const lastIndex = -- nObjects,
  27464. lastObject = objects[ lastIndex ];
  27465. if ( lastIndex > 0 ) {
  27466. indicesByUUID[ lastObject.uuid ] = index;
  27467. }
  27468. objects[ index ] = lastObject;
  27469. objects.pop();
  27470. // accounting is done, now do the same for all bindings
  27471. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  27472. const bindingsForPath = bindings[ j ];
  27473. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  27474. bindingsForPath.pop();
  27475. }
  27476. } // cached or active
  27477. } // if object is known
  27478. } // for arguments
  27479. this.nCachedObjects_ = nCachedObjects;
  27480. }
  27481. // Internal interface used by befriended PropertyBinding.Composite:
  27482. subscribe_( path, parsedPath ) {
  27483. // returns an array of bindings for the given path that is changed
  27484. // according to the contained objects in the group
  27485. const indicesByPath = this._bindingsIndicesByPath;
  27486. let index = indicesByPath[ path ];
  27487. const bindings = this._bindings;
  27488. if ( index !== undefined ) return bindings[ index ];
  27489. const paths = this._paths,
  27490. parsedPaths = this._parsedPaths,
  27491. objects = this._objects,
  27492. nObjects = objects.length,
  27493. nCachedObjects = this.nCachedObjects_,
  27494. bindingsForPath = new Array( nObjects );
  27495. index = bindings.length;
  27496. indicesByPath[ path ] = index;
  27497. paths.push( path );
  27498. parsedPaths.push( parsedPath );
  27499. bindings.push( bindingsForPath );
  27500. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  27501. const object = objects[ i ];
  27502. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  27503. }
  27504. return bindingsForPath;
  27505. }
  27506. unsubscribe_( path ) {
  27507. // tells the group to forget about a property path and no longer
  27508. // update the array previously obtained with 'subscribe_'
  27509. const indicesByPath = this._bindingsIndicesByPath,
  27510. index = indicesByPath[ path ];
  27511. if ( index !== undefined ) {
  27512. const paths = this._paths,
  27513. parsedPaths = this._parsedPaths,
  27514. bindings = this._bindings,
  27515. lastBindingsIndex = bindings.length - 1,
  27516. lastBindings = bindings[ lastBindingsIndex ],
  27517. lastBindingsPath = path[ lastBindingsIndex ];
  27518. indicesByPath[ lastBindingsPath ] = index;
  27519. bindings[ index ] = lastBindings;
  27520. bindings.pop();
  27521. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  27522. parsedPaths.pop();
  27523. paths[ index ] = paths[ lastBindingsIndex ];
  27524. paths.pop();
  27525. }
  27526. }
  27527. }
  27528. class AnimationAction {
  27529. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  27530. this._mixer = mixer;
  27531. this._clip = clip;
  27532. this._localRoot = localRoot;
  27533. this.blendMode = blendMode;
  27534. const tracks = clip.tracks,
  27535. nTracks = tracks.length,
  27536. interpolants = new Array( nTracks );
  27537. const interpolantSettings = {
  27538. endingStart: ZeroCurvatureEnding,
  27539. endingEnd: ZeroCurvatureEnding
  27540. };
  27541. for ( let i = 0; i !== nTracks; ++ i ) {
  27542. const interpolant = tracks[ i ].createInterpolant( null );
  27543. interpolants[ i ] = interpolant;
  27544. interpolant.settings = interpolantSettings;
  27545. }
  27546. this._interpolantSettings = interpolantSettings;
  27547. this._interpolants = interpolants; // bound by the mixer
  27548. // inside: PropertyMixer (managed by the mixer)
  27549. this._propertyBindings = new Array( nTracks );
  27550. this._cacheIndex = null; // for the memory manager
  27551. this._byClipCacheIndex = null; // for the memory manager
  27552. this._timeScaleInterpolant = null;
  27553. this._weightInterpolant = null;
  27554. this.loop = LoopRepeat;
  27555. this._loopCount = - 1;
  27556. // global mixer time when the action is to be started
  27557. // it's set back to 'null' upon start of the action
  27558. this._startTime = null;
  27559. // scaled local time of the action
  27560. // gets clamped or wrapped to 0..clip.duration according to loop
  27561. this.time = 0;
  27562. this.timeScale = 1;
  27563. this._effectiveTimeScale = 1;
  27564. this.weight = 1;
  27565. this._effectiveWeight = 1;
  27566. this.repetitions = Infinity; // no. of repetitions when looping
  27567. this.paused = false; // true -> zero effective time scale
  27568. this.enabled = true; // false -> zero effective weight
  27569. this.clampWhenFinished = false;// keep feeding the last frame?
  27570. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  27571. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  27572. }
  27573. // State & Scheduling
  27574. play() {
  27575. this._mixer._activateAction( this );
  27576. return this;
  27577. }
  27578. stop() {
  27579. this._mixer._deactivateAction( this );
  27580. return this.reset();
  27581. }
  27582. reset() {
  27583. this.paused = false;
  27584. this.enabled = true;
  27585. this.time = 0; // restart clip
  27586. this._loopCount = - 1;// forget previous loops
  27587. this._startTime = null;// forget scheduling
  27588. return this.stopFading().stopWarping();
  27589. }
  27590. isRunning() {
  27591. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  27592. this._startTime === null && this._mixer._isActiveAction( this );
  27593. }
  27594. // return true when play has been called
  27595. isScheduled() {
  27596. return this._mixer._isActiveAction( this );
  27597. }
  27598. startAt( time ) {
  27599. this._startTime = time;
  27600. return this;
  27601. }
  27602. setLoop( mode, repetitions ) {
  27603. this.loop = mode;
  27604. this.repetitions = repetitions;
  27605. return this;
  27606. }
  27607. // Weight
  27608. // set the weight stopping any scheduled fading
  27609. // although .enabled = false yields an effective weight of zero, this
  27610. // method does *not* change .enabled, because it would be confusing
  27611. setEffectiveWeight( weight ) {
  27612. this.weight = weight;
  27613. // note: same logic as when updated at runtime
  27614. this._effectiveWeight = this.enabled ? weight : 0;
  27615. return this.stopFading();
  27616. }
  27617. // return the weight considering fading and .enabled
  27618. getEffectiveWeight() {
  27619. return this._effectiveWeight;
  27620. }
  27621. fadeIn( duration ) {
  27622. return this._scheduleFading( duration, 0, 1 );
  27623. }
  27624. fadeOut( duration ) {
  27625. return this._scheduleFading( duration, 1, 0 );
  27626. }
  27627. crossFadeFrom( fadeOutAction, duration, warp ) {
  27628. fadeOutAction.fadeOut( duration );
  27629. this.fadeIn( duration );
  27630. if ( warp ) {
  27631. const fadeInDuration = this._clip.duration,
  27632. fadeOutDuration = fadeOutAction._clip.duration,
  27633. startEndRatio = fadeOutDuration / fadeInDuration,
  27634. endStartRatio = fadeInDuration / fadeOutDuration;
  27635. fadeOutAction.warp( 1.0, startEndRatio, duration );
  27636. this.warp( endStartRatio, 1.0, duration );
  27637. }
  27638. return this;
  27639. }
  27640. crossFadeTo( fadeInAction, duration, warp ) {
  27641. return fadeInAction.crossFadeFrom( this, duration, warp );
  27642. }
  27643. stopFading() {
  27644. const weightInterpolant = this._weightInterpolant;
  27645. if ( weightInterpolant !== null ) {
  27646. this._weightInterpolant = null;
  27647. this._mixer._takeBackControlInterpolant( weightInterpolant );
  27648. }
  27649. return this;
  27650. }
  27651. // Time Scale Control
  27652. // set the time scale stopping any scheduled warping
  27653. // although .paused = true yields an effective time scale of zero, this
  27654. // method does *not* change .paused, because it would be confusing
  27655. setEffectiveTimeScale( timeScale ) {
  27656. this.timeScale = timeScale;
  27657. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  27658. return this.stopWarping();
  27659. }
  27660. // return the time scale considering warping and .paused
  27661. getEffectiveTimeScale() {
  27662. return this._effectiveTimeScale;
  27663. }
  27664. setDuration( duration ) {
  27665. this.timeScale = this._clip.duration / duration;
  27666. return this.stopWarping();
  27667. }
  27668. syncWith( action ) {
  27669. this.time = action.time;
  27670. this.timeScale = action.timeScale;
  27671. return this.stopWarping();
  27672. }
  27673. halt( duration ) {
  27674. return this.warp( this._effectiveTimeScale, 0, duration );
  27675. }
  27676. warp( startTimeScale, endTimeScale, duration ) {
  27677. const mixer = this._mixer,
  27678. now = mixer.time,
  27679. timeScale = this.timeScale;
  27680. let interpolant = this._timeScaleInterpolant;
  27681. if ( interpolant === null ) {
  27682. interpolant = mixer._lendControlInterpolant();
  27683. this._timeScaleInterpolant = interpolant;
  27684. }
  27685. const times = interpolant.parameterPositions,
  27686. values = interpolant.sampleValues;
  27687. times[ 0 ] = now;
  27688. times[ 1 ] = now + duration;
  27689. values[ 0 ] = startTimeScale / timeScale;
  27690. values[ 1 ] = endTimeScale / timeScale;
  27691. return this;
  27692. }
  27693. stopWarping() {
  27694. const timeScaleInterpolant = this._timeScaleInterpolant;
  27695. if ( timeScaleInterpolant !== null ) {
  27696. this._timeScaleInterpolant = null;
  27697. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  27698. }
  27699. return this;
  27700. }
  27701. // Object Accessors
  27702. getMixer() {
  27703. return this._mixer;
  27704. }
  27705. getClip() {
  27706. return this._clip;
  27707. }
  27708. getRoot() {
  27709. return this._localRoot || this._mixer._root;
  27710. }
  27711. // Interna
  27712. _update( time, deltaTime, timeDirection, accuIndex ) {
  27713. // called by the mixer
  27714. if ( ! this.enabled ) {
  27715. // call ._updateWeight() to update ._effectiveWeight
  27716. this._updateWeight( time );
  27717. return;
  27718. }
  27719. const startTime = this._startTime;
  27720. if ( startTime !== null ) {
  27721. // check for scheduled start of action
  27722. const timeRunning = ( time - startTime ) * timeDirection;
  27723. if ( timeRunning < 0 || timeDirection === 0 ) {
  27724. deltaTime = 0;
  27725. } else {
  27726. this._startTime = null; // unschedule
  27727. deltaTime = timeDirection * timeRunning;
  27728. }
  27729. }
  27730. // apply time scale and advance time
  27731. deltaTime *= this._updateTimeScale( time );
  27732. const clipTime = this._updateTime( deltaTime );
  27733. // note: _updateTime may disable the action resulting in
  27734. // an effective weight of 0
  27735. const weight = this._updateWeight( time );
  27736. if ( weight > 0 ) {
  27737. const interpolants = this._interpolants;
  27738. const propertyMixers = this._propertyBindings;
  27739. switch ( this.blendMode ) {
  27740. case AdditiveAnimationBlendMode:
  27741. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27742. interpolants[ j ].evaluate( clipTime );
  27743. propertyMixers[ j ].accumulateAdditive( weight );
  27744. }
  27745. break;
  27746. case NormalAnimationBlendMode:
  27747. default:
  27748. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27749. interpolants[ j ].evaluate( clipTime );
  27750. propertyMixers[ j ].accumulate( accuIndex, weight );
  27751. }
  27752. }
  27753. }
  27754. }
  27755. _updateWeight( time ) {
  27756. let weight = 0;
  27757. if ( this.enabled ) {
  27758. weight = this.weight;
  27759. const interpolant = this._weightInterpolant;
  27760. if ( interpolant !== null ) {
  27761. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27762. weight *= interpolantValue;
  27763. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27764. this.stopFading();
  27765. if ( interpolantValue === 0 ) {
  27766. // faded out, disable
  27767. this.enabled = false;
  27768. }
  27769. }
  27770. }
  27771. }
  27772. this._effectiveWeight = weight;
  27773. return weight;
  27774. }
  27775. _updateTimeScale( time ) {
  27776. let timeScale = 0;
  27777. if ( ! this.paused ) {
  27778. timeScale = this.timeScale;
  27779. const interpolant = this._timeScaleInterpolant;
  27780. if ( interpolant !== null ) {
  27781. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27782. timeScale *= interpolantValue;
  27783. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27784. this.stopWarping();
  27785. if ( timeScale === 0 ) {
  27786. // motion has halted, pause
  27787. this.paused = true;
  27788. } else {
  27789. // warp done - apply final time scale
  27790. this.timeScale = timeScale;
  27791. }
  27792. }
  27793. }
  27794. }
  27795. this._effectiveTimeScale = timeScale;
  27796. return timeScale;
  27797. }
  27798. _updateTime( deltaTime ) {
  27799. const duration = this._clip.duration;
  27800. const loop = this.loop;
  27801. let time = this.time + deltaTime;
  27802. let loopCount = this._loopCount;
  27803. const pingPong = ( loop === LoopPingPong );
  27804. if ( deltaTime === 0 ) {
  27805. if ( loopCount === - 1 ) return time;
  27806. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  27807. }
  27808. if ( loop === LoopOnce ) {
  27809. if ( loopCount === - 1 ) {
  27810. // just started
  27811. this._loopCount = 0;
  27812. this._setEndings( true, true, false );
  27813. }
  27814. handle_stop: {
  27815. if ( time >= duration ) {
  27816. time = duration;
  27817. } else if ( time < 0 ) {
  27818. time = 0;
  27819. } else {
  27820. this.time = time;
  27821. break handle_stop;
  27822. }
  27823. if ( this.clampWhenFinished ) this.paused = true;
  27824. else this.enabled = false;
  27825. this.time = time;
  27826. this._mixer.dispatchEvent( {
  27827. type: 'finished', action: this,
  27828. direction: deltaTime < 0 ? - 1 : 1
  27829. } );
  27830. }
  27831. } else { // repetitive Repeat or PingPong
  27832. if ( loopCount === - 1 ) {
  27833. // just started
  27834. if ( deltaTime >= 0 ) {
  27835. loopCount = 0;
  27836. this._setEndings( true, this.repetitions === 0, pingPong );
  27837. } else {
  27838. // when looping in reverse direction, the initial
  27839. // transition through zero counts as a repetition,
  27840. // so leave loopCount at -1
  27841. this._setEndings( this.repetitions === 0, true, pingPong );
  27842. }
  27843. }
  27844. if ( time >= duration || time < 0 ) {
  27845. // wrap around
  27846. const loopDelta = Math.floor( time / duration ); // signed
  27847. time -= duration * loopDelta;
  27848. loopCount += Math.abs( loopDelta );
  27849. const pending = this.repetitions - loopCount;
  27850. if ( pending <= 0 ) {
  27851. // have to stop (switch state, clamp time, fire event)
  27852. if ( this.clampWhenFinished ) this.paused = true;
  27853. else this.enabled = false;
  27854. time = deltaTime > 0 ? duration : 0;
  27855. this.time = time;
  27856. this._mixer.dispatchEvent( {
  27857. type: 'finished', action: this,
  27858. direction: deltaTime > 0 ? 1 : - 1
  27859. } );
  27860. } else {
  27861. // keep running
  27862. if ( pending === 1 ) {
  27863. // entering the last round
  27864. const atStart = deltaTime < 0;
  27865. this._setEndings( atStart, ! atStart, pingPong );
  27866. } else {
  27867. this._setEndings( false, false, pingPong );
  27868. }
  27869. this._loopCount = loopCount;
  27870. this.time = time;
  27871. this._mixer.dispatchEvent( {
  27872. type: 'loop', action: this, loopDelta: loopDelta
  27873. } );
  27874. }
  27875. } else {
  27876. this.time = time;
  27877. }
  27878. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  27879. // invert time for the "pong round"
  27880. return duration - time;
  27881. }
  27882. }
  27883. return time;
  27884. }
  27885. _setEndings( atStart, atEnd, pingPong ) {
  27886. const settings = this._interpolantSettings;
  27887. if ( pingPong ) {
  27888. settings.endingStart = ZeroSlopeEnding;
  27889. settings.endingEnd = ZeroSlopeEnding;
  27890. } else {
  27891. // assuming for LoopOnce atStart == atEnd == true
  27892. if ( atStart ) {
  27893. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27894. } else {
  27895. settings.endingStart = WrapAroundEnding;
  27896. }
  27897. if ( atEnd ) {
  27898. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27899. } else {
  27900. settings.endingEnd = WrapAroundEnding;
  27901. }
  27902. }
  27903. }
  27904. _scheduleFading( duration, weightNow, weightThen ) {
  27905. const mixer = this._mixer, now = mixer.time;
  27906. let interpolant = this._weightInterpolant;
  27907. if ( interpolant === null ) {
  27908. interpolant = mixer._lendControlInterpolant();
  27909. this._weightInterpolant = interpolant;
  27910. }
  27911. const times = interpolant.parameterPositions,
  27912. values = interpolant.sampleValues;
  27913. times[ 0 ] = now;
  27914. values[ 0 ] = weightNow;
  27915. times[ 1 ] = now + duration;
  27916. values[ 1 ] = weightThen;
  27917. return this;
  27918. }
  27919. }
  27920. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  27921. class AnimationMixer extends EventDispatcher {
  27922. constructor( root ) {
  27923. super();
  27924. this._root = root;
  27925. this._initMemoryManager();
  27926. this._accuIndex = 0;
  27927. this.time = 0;
  27928. this.timeScale = 1.0;
  27929. }
  27930. _bindAction( action, prototypeAction ) {
  27931. const root = action._localRoot || this._root,
  27932. tracks = action._clip.tracks,
  27933. nTracks = tracks.length,
  27934. bindings = action._propertyBindings,
  27935. interpolants = action._interpolants,
  27936. rootUuid = root.uuid,
  27937. bindingsByRoot = this._bindingsByRootAndName;
  27938. let bindingsByName = bindingsByRoot[ rootUuid ];
  27939. if ( bindingsByName === undefined ) {
  27940. bindingsByName = {};
  27941. bindingsByRoot[ rootUuid ] = bindingsByName;
  27942. }
  27943. for ( let i = 0; i !== nTracks; ++ i ) {
  27944. const track = tracks[ i ],
  27945. trackName = track.name;
  27946. let binding = bindingsByName[ trackName ];
  27947. if ( binding !== undefined ) {
  27948. ++ binding.referenceCount;
  27949. bindings[ i ] = binding;
  27950. } else {
  27951. binding = bindings[ i ];
  27952. if ( binding !== undefined ) {
  27953. // existing binding, make sure the cache knows
  27954. if ( binding._cacheIndex === null ) {
  27955. ++ binding.referenceCount;
  27956. this._addInactiveBinding( binding, rootUuid, trackName );
  27957. }
  27958. continue;
  27959. }
  27960. const path = prototypeAction && prototypeAction.
  27961. _propertyBindings[ i ].binding.parsedPath;
  27962. binding = new PropertyMixer(
  27963. PropertyBinding.create( root, trackName, path ),
  27964. track.ValueTypeName, track.getValueSize() );
  27965. ++ binding.referenceCount;
  27966. this._addInactiveBinding( binding, rootUuid, trackName );
  27967. bindings[ i ] = binding;
  27968. }
  27969. interpolants[ i ].resultBuffer = binding.buffer;
  27970. }
  27971. }
  27972. _activateAction( action ) {
  27973. if ( ! this._isActiveAction( action ) ) {
  27974. if ( action._cacheIndex === null ) {
  27975. // this action has been forgotten by the cache, but the user
  27976. // appears to be still using it -> rebind
  27977. const rootUuid = ( action._localRoot || this._root ).uuid,
  27978. clipUuid = action._clip.uuid,
  27979. actionsForClip = this._actionsByClip[ clipUuid ];
  27980. this._bindAction( action,
  27981. actionsForClip && actionsForClip.knownActions[ 0 ] );
  27982. this._addInactiveAction( action, clipUuid, rootUuid );
  27983. }
  27984. const bindings = action._propertyBindings;
  27985. // increment reference counts / sort out state
  27986. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27987. const binding = bindings[ i ];
  27988. if ( binding.useCount ++ === 0 ) {
  27989. this._lendBinding( binding );
  27990. binding.saveOriginalState();
  27991. }
  27992. }
  27993. this._lendAction( action );
  27994. }
  27995. }
  27996. _deactivateAction( action ) {
  27997. if ( this._isActiveAction( action ) ) {
  27998. const bindings = action._propertyBindings;
  27999. // decrement reference counts / sort out state
  28000. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28001. const binding = bindings[ i ];
  28002. if ( -- binding.useCount === 0 ) {
  28003. binding.restoreOriginalState();
  28004. this._takeBackBinding( binding );
  28005. }
  28006. }
  28007. this._takeBackAction( action );
  28008. }
  28009. }
  28010. // Memory manager
  28011. _initMemoryManager() {
  28012. this._actions = []; // 'nActiveActions' followed by inactive ones
  28013. this._nActiveActions = 0;
  28014. this._actionsByClip = {};
  28015. // inside:
  28016. // {
  28017. // knownActions: Array< AnimationAction > - used as prototypes
  28018. // actionByRoot: AnimationAction - lookup
  28019. // }
  28020. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  28021. this._nActiveBindings = 0;
  28022. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  28023. this._controlInterpolants = []; // same game as above
  28024. this._nActiveControlInterpolants = 0;
  28025. const scope = this;
  28026. this.stats = {
  28027. actions: {
  28028. get total() {
  28029. return scope._actions.length;
  28030. },
  28031. get inUse() {
  28032. return scope._nActiveActions;
  28033. }
  28034. },
  28035. bindings: {
  28036. get total() {
  28037. return scope._bindings.length;
  28038. },
  28039. get inUse() {
  28040. return scope._nActiveBindings;
  28041. }
  28042. },
  28043. controlInterpolants: {
  28044. get total() {
  28045. return scope._controlInterpolants.length;
  28046. },
  28047. get inUse() {
  28048. return scope._nActiveControlInterpolants;
  28049. }
  28050. }
  28051. };
  28052. }
  28053. // Memory management for AnimationAction objects
  28054. _isActiveAction( action ) {
  28055. const index = action._cacheIndex;
  28056. return index !== null && index < this._nActiveActions;
  28057. }
  28058. _addInactiveAction( action, clipUuid, rootUuid ) {
  28059. const actions = this._actions,
  28060. actionsByClip = this._actionsByClip;
  28061. let actionsForClip = actionsByClip[ clipUuid ];
  28062. if ( actionsForClip === undefined ) {
  28063. actionsForClip = {
  28064. knownActions: [ action ],
  28065. actionByRoot: {}
  28066. };
  28067. action._byClipCacheIndex = 0;
  28068. actionsByClip[ clipUuid ] = actionsForClip;
  28069. } else {
  28070. const knownActions = actionsForClip.knownActions;
  28071. action._byClipCacheIndex = knownActions.length;
  28072. knownActions.push( action );
  28073. }
  28074. action._cacheIndex = actions.length;
  28075. actions.push( action );
  28076. actionsForClip.actionByRoot[ rootUuid ] = action;
  28077. }
  28078. _removeInactiveAction( action ) {
  28079. const actions = this._actions,
  28080. lastInactiveAction = actions[ actions.length - 1 ],
  28081. cacheIndex = action._cacheIndex;
  28082. lastInactiveAction._cacheIndex = cacheIndex;
  28083. actions[ cacheIndex ] = lastInactiveAction;
  28084. actions.pop();
  28085. action._cacheIndex = null;
  28086. const clipUuid = action._clip.uuid,
  28087. actionsByClip = this._actionsByClip,
  28088. actionsForClip = actionsByClip[ clipUuid ],
  28089. knownActionsForClip = actionsForClip.knownActions,
  28090. lastKnownAction =
  28091. knownActionsForClip[ knownActionsForClip.length - 1 ],
  28092. byClipCacheIndex = action._byClipCacheIndex;
  28093. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  28094. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  28095. knownActionsForClip.pop();
  28096. action._byClipCacheIndex = null;
  28097. const actionByRoot = actionsForClip.actionByRoot,
  28098. rootUuid = ( action._localRoot || this._root ).uuid;
  28099. delete actionByRoot[ rootUuid ];
  28100. if ( knownActionsForClip.length === 0 ) {
  28101. delete actionsByClip[ clipUuid ];
  28102. }
  28103. this._removeInactiveBindingsForAction( action );
  28104. }
  28105. _removeInactiveBindingsForAction( action ) {
  28106. const bindings = action._propertyBindings;
  28107. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  28108. const binding = bindings[ i ];
  28109. if ( -- binding.referenceCount === 0 ) {
  28110. this._removeInactiveBinding( binding );
  28111. }
  28112. }
  28113. }
  28114. _lendAction( action ) {
  28115. // [ active actions | inactive actions ]
  28116. // [ active actions >| inactive actions ]
  28117. // s a
  28118. // <-swap->
  28119. // a s
  28120. const actions = this._actions,
  28121. prevIndex = action._cacheIndex,
  28122. lastActiveIndex = this._nActiveActions ++,
  28123. firstInactiveAction = actions[ lastActiveIndex ];
  28124. action._cacheIndex = lastActiveIndex;
  28125. actions[ lastActiveIndex ] = action;
  28126. firstInactiveAction._cacheIndex = prevIndex;
  28127. actions[ prevIndex ] = firstInactiveAction;
  28128. }
  28129. _takeBackAction( action ) {
  28130. // [ active actions | inactive actions ]
  28131. // [ active actions |< inactive actions ]
  28132. // a s
  28133. // <-swap->
  28134. // s a
  28135. const actions = this._actions,
  28136. prevIndex = action._cacheIndex,
  28137. firstInactiveIndex = -- this._nActiveActions,
  28138. lastActiveAction = actions[ firstInactiveIndex ];
  28139. action._cacheIndex = firstInactiveIndex;
  28140. actions[ firstInactiveIndex ] = action;
  28141. lastActiveAction._cacheIndex = prevIndex;
  28142. actions[ prevIndex ] = lastActiveAction;
  28143. }
  28144. // Memory management for PropertyMixer objects
  28145. _addInactiveBinding( binding, rootUuid, trackName ) {
  28146. const bindingsByRoot = this._bindingsByRootAndName,
  28147. bindings = this._bindings;
  28148. let bindingByName = bindingsByRoot[ rootUuid ];
  28149. if ( bindingByName === undefined ) {
  28150. bindingByName = {};
  28151. bindingsByRoot[ rootUuid ] = bindingByName;
  28152. }
  28153. bindingByName[ trackName ] = binding;
  28154. binding._cacheIndex = bindings.length;
  28155. bindings.push( binding );
  28156. }
  28157. _removeInactiveBinding( binding ) {
  28158. const bindings = this._bindings,
  28159. propBinding = binding.binding,
  28160. rootUuid = propBinding.rootNode.uuid,
  28161. trackName = propBinding.path,
  28162. bindingsByRoot = this._bindingsByRootAndName,
  28163. bindingByName = bindingsByRoot[ rootUuid ],
  28164. lastInactiveBinding = bindings[ bindings.length - 1 ],
  28165. cacheIndex = binding._cacheIndex;
  28166. lastInactiveBinding._cacheIndex = cacheIndex;
  28167. bindings[ cacheIndex ] = lastInactiveBinding;
  28168. bindings.pop();
  28169. delete bindingByName[ trackName ];
  28170. if ( Object.keys( bindingByName ).length === 0 ) {
  28171. delete bindingsByRoot[ rootUuid ];
  28172. }
  28173. }
  28174. _lendBinding( binding ) {
  28175. const bindings = this._bindings,
  28176. prevIndex = binding._cacheIndex,
  28177. lastActiveIndex = this._nActiveBindings ++,
  28178. firstInactiveBinding = bindings[ lastActiveIndex ];
  28179. binding._cacheIndex = lastActiveIndex;
  28180. bindings[ lastActiveIndex ] = binding;
  28181. firstInactiveBinding._cacheIndex = prevIndex;
  28182. bindings[ prevIndex ] = firstInactiveBinding;
  28183. }
  28184. _takeBackBinding( binding ) {
  28185. const bindings = this._bindings,
  28186. prevIndex = binding._cacheIndex,
  28187. firstInactiveIndex = -- this._nActiveBindings,
  28188. lastActiveBinding = bindings[ firstInactiveIndex ];
  28189. binding._cacheIndex = firstInactiveIndex;
  28190. bindings[ firstInactiveIndex ] = binding;
  28191. lastActiveBinding._cacheIndex = prevIndex;
  28192. bindings[ prevIndex ] = lastActiveBinding;
  28193. }
  28194. // Memory management of Interpolants for weight and time scale
  28195. _lendControlInterpolant() {
  28196. const interpolants = this._controlInterpolants,
  28197. lastActiveIndex = this._nActiveControlInterpolants ++;
  28198. let interpolant = interpolants[ lastActiveIndex ];
  28199. if ( interpolant === undefined ) {
  28200. interpolant = new LinearInterpolant(
  28201. new Float32Array( 2 ), new Float32Array( 2 ),
  28202. 1, _controlInterpolantsResultBuffer );
  28203. interpolant.__cacheIndex = lastActiveIndex;
  28204. interpolants[ lastActiveIndex ] = interpolant;
  28205. }
  28206. return interpolant;
  28207. }
  28208. _takeBackControlInterpolant( interpolant ) {
  28209. const interpolants = this._controlInterpolants,
  28210. prevIndex = interpolant.__cacheIndex,
  28211. firstInactiveIndex = -- this._nActiveControlInterpolants,
  28212. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  28213. interpolant.__cacheIndex = firstInactiveIndex;
  28214. interpolants[ firstInactiveIndex ] = interpolant;
  28215. lastActiveInterpolant.__cacheIndex = prevIndex;
  28216. interpolants[ prevIndex ] = lastActiveInterpolant;
  28217. }
  28218. // return an action for a clip optionally using a custom root target
  28219. // object (this method allocates a lot of dynamic memory in case a
  28220. // previously unknown clip/root combination is specified)
  28221. clipAction( clip, optionalRoot, blendMode ) {
  28222. const root = optionalRoot || this._root,
  28223. rootUuid = root.uuid;
  28224. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  28225. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  28226. const actionsForClip = this._actionsByClip[ clipUuid ];
  28227. let prototypeAction = null;
  28228. if ( blendMode === undefined ) {
  28229. if ( clipObject !== null ) {
  28230. blendMode = clipObject.blendMode;
  28231. } else {
  28232. blendMode = NormalAnimationBlendMode;
  28233. }
  28234. }
  28235. if ( actionsForClip !== undefined ) {
  28236. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  28237. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  28238. return existingAction;
  28239. }
  28240. // we know the clip, so we don't have to parse all
  28241. // the bindings again but can just copy
  28242. prototypeAction = actionsForClip.knownActions[ 0 ];
  28243. // also, take the clip from the prototype action
  28244. if ( clipObject === null )
  28245. clipObject = prototypeAction._clip;
  28246. }
  28247. // clip must be known when specified via string
  28248. if ( clipObject === null ) return null;
  28249. // allocate all resources required to run it
  28250. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  28251. this._bindAction( newAction, prototypeAction );
  28252. // and make the action known to the memory manager
  28253. this._addInactiveAction( newAction, clipUuid, rootUuid );
  28254. return newAction;
  28255. }
  28256. // get an existing action
  28257. existingAction( clip, optionalRoot ) {
  28258. const root = optionalRoot || this._root,
  28259. rootUuid = root.uuid,
  28260. clipObject = typeof clip === 'string' ?
  28261. AnimationClip.findByName( root, clip ) : clip,
  28262. clipUuid = clipObject ? clipObject.uuid : clip,
  28263. actionsForClip = this._actionsByClip[ clipUuid ];
  28264. if ( actionsForClip !== undefined ) {
  28265. return actionsForClip.actionByRoot[ rootUuid ] || null;
  28266. }
  28267. return null;
  28268. }
  28269. // deactivates all previously scheduled actions
  28270. stopAllAction() {
  28271. const actions = this._actions,
  28272. nActions = this._nActiveActions;
  28273. for ( let i = nActions - 1; i >= 0; -- i ) {
  28274. actions[ i ].stop();
  28275. }
  28276. return this;
  28277. }
  28278. // advance the time and update apply the animation
  28279. update( deltaTime ) {
  28280. deltaTime *= this.timeScale;
  28281. const actions = this._actions,
  28282. nActions = this._nActiveActions,
  28283. time = this.time += deltaTime,
  28284. timeDirection = Math.sign( deltaTime ),
  28285. accuIndex = this._accuIndex ^= 1;
  28286. // run active actions
  28287. for ( let i = 0; i !== nActions; ++ i ) {
  28288. const action = actions[ i ];
  28289. action._update( time, deltaTime, timeDirection, accuIndex );
  28290. }
  28291. // update scene graph
  28292. const bindings = this._bindings,
  28293. nBindings = this._nActiveBindings;
  28294. for ( let i = 0; i !== nBindings; ++ i ) {
  28295. bindings[ i ].apply( accuIndex );
  28296. }
  28297. return this;
  28298. }
  28299. // Allows you to seek to a specific time in an animation.
  28300. setTime( timeInSeconds ) {
  28301. this.time = 0; // Zero out time attribute for AnimationMixer object;
  28302. for ( let i = 0; i < this._actions.length; i ++ ) {
  28303. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  28304. }
  28305. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  28306. }
  28307. // return this mixer's root target object
  28308. getRoot() {
  28309. return this._root;
  28310. }
  28311. // free all resources specific to a particular clip
  28312. uncacheClip( clip ) {
  28313. const actions = this._actions,
  28314. clipUuid = clip.uuid,
  28315. actionsByClip = this._actionsByClip,
  28316. actionsForClip = actionsByClip[ clipUuid ];
  28317. if ( actionsForClip !== undefined ) {
  28318. // note: just calling _removeInactiveAction would mess up the
  28319. // iteration state and also require updating the state we can
  28320. // just throw away
  28321. const actionsToRemove = actionsForClip.knownActions;
  28322. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  28323. const action = actionsToRemove[ i ];
  28324. this._deactivateAction( action );
  28325. const cacheIndex = action._cacheIndex,
  28326. lastInactiveAction = actions[ actions.length - 1 ];
  28327. action._cacheIndex = null;
  28328. action._byClipCacheIndex = null;
  28329. lastInactiveAction._cacheIndex = cacheIndex;
  28330. actions[ cacheIndex ] = lastInactiveAction;
  28331. actions.pop();
  28332. this._removeInactiveBindingsForAction( action );
  28333. }
  28334. delete actionsByClip[ clipUuid ];
  28335. }
  28336. }
  28337. // free all resources specific to a particular root target object
  28338. uncacheRoot( root ) {
  28339. const rootUuid = root.uuid,
  28340. actionsByClip = this._actionsByClip;
  28341. for ( const clipUuid in actionsByClip ) {
  28342. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  28343. action = actionByRoot[ rootUuid ];
  28344. if ( action !== undefined ) {
  28345. this._deactivateAction( action );
  28346. this._removeInactiveAction( action );
  28347. }
  28348. }
  28349. const bindingsByRoot = this._bindingsByRootAndName,
  28350. bindingByName = bindingsByRoot[ rootUuid ];
  28351. if ( bindingByName !== undefined ) {
  28352. for ( const trackName in bindingByName ) {
  28353. const binding = bindingByName[ trackName ];
  28354. binding.restoreOriginalState();
  28355. this._removeInactiveBinding( binding );
  28356. }
  28357. }
  28358. }
  28359. // remove a targeted clip from the cache
  28360. uncacheAction( clip, optionalRoot ) {
  28361. const action = this.existingAction( clip, optionalRoot );
  28362. if ( action !== null ) {
  28363. this._deactivateAction( action );
  28364. this._removeInactiveAction( action );
  28365. }
  28366. }
  28367. }
  28368. class Uniform {
  28369. constructor( value ) {
  28370. this.value = value;
  28371. }
  28372. clone() {
  28373. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  28374. }
  28375. }
  28376. let id = 0;
  28377. class UniformsGroup extends EventDispatcher {
  28378. constructor() {
  28379. super();
  28380. this.isUniformsGroup = true;
  28381. Object.defineProperty( this, 'id', { value: id ++ } );
  28382. this.name = '';
  28383. this.usage = StaticDrawUsage;
  28384. this.uniforms = [];
  28385. }
  28386. add( uniform ) {
  28387. this.uniforms.push( uniform );
  28388. return this;
  28389. }
  28390. remove( uniform ) {
  28391. const index = this.uniforms.indexOf( uniform );
  28392. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  28393. return this;
  28394. }
  28395. setName( name ) {
  28396. this.name = name;
  28397. return this;
  28398. }
  28399. setUsage( value ) {
  28400. this.usage = value;
  28401. return this;
  28402. }
  28403. dispose() {
  28404. this.dispatchEvent( { type: 'dispose' } );
  28405. return this;
  28406. }
  28407. copy( source ) {
  28408. this.name = source.name;
  28409. this.usage = source.usage;
  28410. const uniformsSource = source.uniforms;
  28411. this.uniforms.length = 0;
  28412. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  28413. this.uniforms.push( uniformsSource[ i ].clone() );
  28414. }
  28415. return this;
  28416. }
  28417. clone() {
  28418. return new this.constructor().copy( this );
  28419. }
  28420. }
  28421. class InstancedInterleavedBuffer extends InterleavedBuffer {
  28422. constructor( array, stride, meshPerAttribute = 1 ) {
  28423. super( array, stride );
  28424. this.isInstancedInterleavedBuffer = true;
  28425. this.meshPerAttribute = meshPerAttribute;
  28426. }
  28427. copy( source ) {
  28428. super.copy( source );
  28429. this.meshPerAttribute = source.meshPerAttribute;
  28430. return this;
  28431. }
  28432. clone( data ) {
  28433. const ib = super.clone( data );
  28434. ib.meshPerAttribute = this.meshPerAttribute;
  28435. return ib;
  28436. }
  28437. toJSON( data ) {
  28438. const json = super.toJSON( data );
  28439. json.isInstancedInterleavedBuffer = true;
  28440. json.meshPerAttribute = this.meshPerAttribute;
  28441. return json;
  28442. }
  28443. }
  28444. class GLBufferAttribute {
  28445. constructor( buffer, type, itemSize, elementSize, count ) {
  28446. this.isGLBufferAttribute = true;
  28447. this.name = '';
  28448. this.buffer = buffer;
  28449. this.type = type;
  28450. this.itemSize = itemSize;
  28451. this.elementSize = elementSize;
  28452. this.count = count;
  28453. this.version = 0;
  28454. }
  28455. set needsUpdate( value ) {
  28456. if ( value === true ) this.version ++;
  28457. }
  28458. setBuffer( buffer ) {
  28459. this.buffer = buffer;
  28460. return this;
  28461. }
  28462. setType( type, elementSize ) {
  28463. this.type = type;
  28464. this.elementSize = elementSize;
  28465. return this;
  28466. }
  28467. setItemSize( itemSize ) {
  28468. this.itemSize = itemSize;
  28469. return this;
  28470. }
  28471. setCount( count ) {
  28472. this.count = count;
  28473. return this;
  28474. }
  28475. }
  28476. class Raycaster {
  28477. constructor( origin, direction, near = 0, far = Infinity ) {
  28478. this.ray = new Ray( origin, direction );
  28479. // direction is assumed to be normalized (for accurate distance calculations)
  28480. this.near = near;
  28481. this.far = far;
  28482. this.camera = null;
  28483. this.layers = new Layers();
  28484. this.params = {
  28485. Mesh: {},
  28486. Line: { threshold: 1 },
  28487. LOD: {},
  28488. Points: { threshold: 1 },
  28489. Sprite: {}
  28490. };
  28491. }
  28492. set( origin, direction ) {
  28493. // direction is assumed to be normalized (for accurate distance calculations)
  28494. this.ray.set( origin, direction );
  28495. }
  28496. setFromCamera( coords, camera ) {
  28497. if ( camera.isPerspectiveCamera ) {
  28498. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  28499. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  28500. this.camera = camera;
  28501. } else if ( camera.isOrthographicCamera ) {
  28502. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  28503. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  28504. this.camera = camera;
  28505. } else {
  28506. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  28507. }
  28508. }
  28509. intersectObject( object, recursive = true, intersects = [] ) {
  28510. intersectObject( object, this, intersects, recursive );
  28511. intersects.sort( ascSort );
  28512. return intersects;
  28513. }
  28514. intersectObjects( objects, recursive = true, intersects = [] ) {
  28515. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  28516. intersectObject( objects[ i ], this, intersects, recursive );
  28517. }
  28518. intersects.sort( ascSort );
  28519. return intersects;
  28520. }
  28521. }
  28522. function ascSort( a, b ) {
  28523. return a.distance - b.distance;
  28524. }
  28525. function intersectObject( object, raycaster, intersects, recursive ) {
  28526. if ( object.layers.test( raycaster.layers ) ) {
  28527. object.raycast( raycaster, intersects );
  28528. }
  28529. if ( recursive === true ) {
  28530. const children = object.children;
  28531. for ( let i = 0, l = children.length; i < l; i ++ ) {
  28532. intersectObject( children[ i ], raycaster, intersects, true );
  28533. }
  28534. }
  28535. }
  28536. /**
  28537. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  28538. *
  28539. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  28540. * The azimuthal angle (theta) is measured from the positive z-axis.
  28541. */
  28542. class Spherical {
  28543. constructor( radius = 1, phi = 0, theta = 0 ) {
  28544. this.radius = radius;
  28545. this.phi = phi; // polar angle
  28546. this.theta = theta; // azimuthal angle
  28547. return this;
  28548. }
  28549. set( radius, phi, theta ) {
  28550. this.radius = radius;
  28551. this.phi = phi;
  28552. this.theta = theta;
  28553. return this;
  28554. }
  28555. copy( other ) {
  28556. this.radius = other.radius;
  28557. this.phi = other.phi;
  28558. this.theta = other.theta;
  28559. return this;
  28560. }
  28561. // restrict phi to be between EPS and PI-EPS
  28562. makeSafe() {
  28563. const EPS = 0.000001;
  28564. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  28565. return this;
  28566. }
  28567. setFromVector3( v ) {
  28568. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28569. }
  28570. setFromCartesianCoords( x, y, z ) {
  28571. this.radius = Math.sqrt( x * x + y * y + z * z );
  28572. if ( this.radius === 0 ) {
  28573. this.theta = 0;
  28574. this.phi = 0;
  28575. } else {
  28576. this.theta = Math.atan2( x, z );
  28577. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  28578. }
  28579. return this;
  28580. }
  28581. clone() {
  28582. return new this.constructor().copy( this );
  28583. }
  28584. }
  28585. /**
  28586. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  28587. */
  28588. class Cylindrical {
  28589. constructor( radius = 1, theta = 0, y = 0 ) {
  28590. this.radius = radius; // distance from the origin to a point in the x-z plane
  28591. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  28592. this.y = y; // height above the x-z plane
  28593. return this;
  28594. }
  28595. set( radius, theta, y ) {
  28596. this.radius = radius;
  28597. this.theta = theta;
  28598. this.y = y;
  28599. return this;
  28600. }
  28601. copy( other ) {
  28602. this.radius = other.radius;
  28603. this.theta = other.theta;
  28604. this.y = other.y;
  28605. return this;
  28606. }
  28607. setFromVector3( v ) {
  28608. return this.setFromCartesianCoords( v.x, v.y, v.z );
  28609. }
  28610. setFromCartesianCoords( x, y, z ) {
  28611. this.radius = Math.sqrt( x * x + z * z );
  28612. this.theta = Math.atan2( x, z );
  28613. this.y = y;
  28614. return this;
  28615. }
  28616. clone() {
  28617. return new this.constructor().copy( this );
  28618. }
  28619. }
  28620. const _vector$4 = /*@__PURE__*/ new Vector2();
  28621. class Box2 {
  28622. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  28623. this.isBox2 = true;
  28624. this.min = min;
  28625. this.max = max;
  28626. }
  28627. set( min, max ) {
  28628. this.min.copy( min );
  28629. this.max.copy( max );
  28630. return this;
  28631. }
  28632. setFromPoints( points ) {
  28633. this.makeEmpty();
  28634. for ( let i = 0, il = points.length; i < il; i ++ ) {
  28635. this.expandByPoint( points[ i ] );
  28636. }
  28637. return this;
  28638. }
  28639. setFromCenterAndSize( center, size ) {
  28640. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  28641. this.min.copy( center ).sub( halfSize );
  28642. this.max.copy( center ).add( halfSize );
  28643. return this;
  28644. }
  28645. clone() {
  28646. return new this.constructor().copy( this );
  28647. }
  28648. copy( box ) {
  28649. this.min.copy( box.min );
  28650. this.max.copy( box.max );
  28651. return this;
  28652. }
  28653. makeEmpty() {
  28654. this.min.x = this.min.y = + Infinity;
  28655. this.max.x = this.max.y = - Infinity;
  28656. return this;
  28657. }
  28658. isEmpty() {
  28659. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  28660. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  28661. }
  28662. getCenter( target ) {
  28663. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  28664. }
  28665. getSize( target ) {
  28666. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  28667. }
  28668. expandByPoint( point ) {
  28669. this.min.min( point );
  28670. this.max.max( point );
  28671. return this;
  28672. }
  28673. expandByVector( vector ) {
  28674. this.min.sub( vector );
  28675. this.max.add( vector );
  28676. return this;
  28677. }
  28678. expandByScalar( scalar ) {
  28679. this.min.addScalar( - scalar );
  28680. this.max.addScalar( scalar );
  28681. return this;
  28682. }
  28683. containsPoint( point ) {
  28684. return point.x < this.min.x || point.x > this.max.x ||
  28685. point.y < this.min.y || point.y > this.max.y ? false : true;
  28686. }
  28687. containsBox( box ) {
  28688. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  28689. this.min.y <= box.min.y && box.max.y <= this.max.y;
  28690. }
  28691. getParameter( point, target ) {
  28692. // This can potentially have a divide by zero if the box
  28693. // has a size dimension of 0.
  28694. return target.set(
  28695. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  28696. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  28697. );
  28698. }
  28699. intersectsBox( box ) {
  28700. // using 4 splitting planes to rule out intersections
  28701. return box.max.x < this.min.x || box.min.x > this.max.x ||
  28702. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  28703. }
  28704. clampPoint( point, target ) {
  28705. return target.copy( point ).clamp( this.min, this.max );
  28706. }
  28707. distanceToPoint( point ) {
  28708. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  28709. }
  28710. intersect( box ) {
  28711. this.min.max( box.min );
  28712. this.max.min( box.max );
  28713. if ( this.isEmpty() ) this.makeEmpty();
  28714. return this;
  28715. }
  28716. union( box ) {
  28717. this.min.min( box.min );
  28718. this.max.max( box.max );
  28719. return this;
  28720. }
  28721. translate( offset ) {
  28722. this.min.add( offset );
  28723. this.max.add( offset );
  28724. return this;
  28725. }
  28726. equals( box ) {
  28727. return box.min.equals( this.min ) && box.max.equals( this.max );
  28728. }
  28729. }
  28730. const _startP = /*@__PURE__*/ new Vector3();
  28731. const _startEnd = /*@__PURE__*/ new Vector3();
  28732. class Line3 {
  28733. constructor( start = new Vector3(), end = new Vector3() ) {
  28734. this.start = start;
  28735. this.end = end;
  28736. }
  28737. set( start, end ) {
  28738. this.start.copy( start );
  28739. this.end.copy( end );
  28740. return this;
  28741. }
  28742. copy( line ) {
  28743. this.start.copy( line.start );
  28744. this.end.copy( line.end );
  28745. return this;
  28746. }
  28747. getCenter( target ) {
  28748. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  28749. }
  28750. delta( target ) {
  28751. return target.subVectors( this.end, this.start );
  28752. }
  28753. distanceSq() {
  28754. return this.start.distanceToSquared( this.end );
  28755. }
  28756. distance() {
  28757. return this.start.distanceTo( this.end );
  28758. }
  28759. at( t, target ) {
  28760. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28761. }
  28762. closestPointToPointParameter( point, clampToLine ) {
  28763. _startP.subVectors( point, this.start );
  28764. _startEnd.subVectors( this.end, this.start );
  28765. const startEnd2 = _startEnd.dot( _startEnd );
  28766. const startEnd_startP = _startEnd.dot( _startP );
  28767. let t = startEnd_startP / startEnd2;
  28768. if ( clampToLine ) {
  28769. t = clamp( t, 0, 1 );
  28770. }
  28771. return t;
  28772. }
  28773. closestPointToPoint( point, clampToLine, target ) {
  28774. const t = this.closestPointToPointParameter( point, clampToLine );
  28775. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28776. }
  28777. applyMatrix4( matrix ) {
  28778. this.start.applyMatrix4( matrix );
  28779. this.end.applyMatrix4( matrix );
  28780. return this;
  28781. }
  28782. equals( line ) {
  28783. return line.start.equals( this.start ) && line.end.equals( this.end );
  28784. }
  28785. clone() {
  28786. return new this.constructor().copy( this );
  28787. }
  28788. }
  28789. const _vector$3 = /*@__PURE__*/ new Vector3();
  28790. class SpotLightHelper extends Object3D {
  28791. constructor( light, color ) {
  28792. super();
  28793. this.light = light;
  28794. this.matrix = light.matrixWorld;
  28795. this.matrixAutoUpdate = false;
  28796. this.color = color;
  28797. this.type = 'SpotLightHelper';
  28798. const geometry = new BufferGeometry();
  28799. const positions = [
  28800. 0, 0, 0, 0, 0, 1,
  28801. 0, 0, 0, 1, 0, 1,
  28802. 0, 0, 0, - 1, 0, 1,
  28803. 0, 0, 0, 0, 1, 1,
  28804. 0, 0, 0, 0, - 1, 1
  28805. ];
  28806. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  28807. const p1 = ( i / l ) * Math.PI * 2;
  28808. const p2 = ( j / l ) * Math.PI * 2;
  28809. positions.push(
  28810. Math.cos( p1 ), Math.sin( p1 ), 1,
  28811. Math.cos( p2 ), Math.sin( p2 ), 1
  28812. );
  28813. }
  28814. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28815. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28816. this.cone = new LineSegments( geometry, material );
  28817. this.add( this.cone );
  28818. this.update();
  28819. }
  28820. dispose() {
  28821. this.cone.geometry.dispose();
  28822. this.cone.material.dispose();
  28823. }
  28824. update() {
  28825. this.light.updateWorldMatrix( true, false );
  28826. this.light.target.updateWorldMatrix( true, false );
  28827. const coneLength = this.light.distance ? this.light.distance : 1000;
  28828. const coneWidth = coneLength * Math.tan( this.light.angle );
  28829. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  28830. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  28831. this.cone.lookAt( _vector$3 );
  28832. if ( this.color !== undefined ) {
  28833. this.cone.material.color.set( this.color );
  28834. } else {
  28835. this.cone.material.color.copy( this.light.color );
  28836. }
  28837. }
  28838. }
  28839. const _vector$2 = /*@__PURE__*/ new Vector3();
  28840. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  28841. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  28842. class SkeletonHelper extends LineSegments {
  28843. constructor( object ) {
  28844. const bones = getBoneList( object );
  28845. const geometry = new BufferGeometry();
  28846. const vertices = [];
  28847. const colors = [];
  28848. const color1 = new Color( 0, 0, 1 );
  28849. const color2 = new Color( 0, 1, 0 );
  28850. for ( let i = 0; i < bones.length; i ++ ) {
  28851. const bone = bones[ i ];
  28852. if ( bone.parent && bone.parent.isBone ) {
  28853. vertices.push( 0, 0, 0 );
  28854. vertices.push( 0, 0, 0 );
  28855. colors.push( color1.r, color1.g, color1.b );
  28856. colors.push( color2.r, color2.g, color2.b );
  28857. }
  28858. }
  28859. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28860. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28861. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  28862. super( geometry, material );
  28863. this.isSkeletonHelper = true;
  28864. this.type = 'SkeletonHelper';
  28865. this.root = object;
  28866. this.bones = bones;
  28867. this.matrix = object.matrixWorld;
  28868. this.matrixAutoUpdate = false;
  28869. }
  28870. updateMatrixWorld( force ) {
  28871. const bones = this.bones;
  28872. const geometry = this.geometry;
  28873. const position = geometry.getAttribute( 'position' );
  28874. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  28875. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  28876. const bone = bones[ i ];
  28877. if ( bone.parent && bone.parent.isBone ) {
  28878. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  28879. _vector$2.setFromMatrixPosition( _boneMatrix );
  28880. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  28881. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  28882. _vector$2.setFromMatrixPosition( _boneMatrix );
  28883. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  28884. j += 2;
  28885. }
  28886. }
  28887. geometry.getAttribute( 'position' ).needsUpdate = true;
  28888. super.updateMatrixWorld( force );
  28889. }
  28890. dispose() {
  28891. this.geometry.dispose();
  28892. this.material.dispose();
  28893. }
  28894. }
  28895. function getBoneList( object ) {
  28896. const boneList = [];
  28897. if ( object.isBone === true ) {
  28898. boneList.push( object );
  28899. }
  28900. for ( let i = 0; i < object.children.length; i ++ ) {
  28901. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  28902. }
  28903. return boneList;
  28904. }
  28905. class PointLightHelper extends Mesh {
  28906. constructor( light, sphereSize, color ) {
  28907. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  28908. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28909. super( geometry, material );
  28910. this.light = light;
  28911. this.color = color;
  28912. this.type = 'PointLightHelper';
  28913. this.matrix = this.light.matrixWorld;
  28914. this.matrixAutoUpdate = false;
  28915. this.update();
  28916. /*
  28917. // TODO: delete this comment?
  28918. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  28919. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28920. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28921. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28922. const d = light.distance;
  28923. if ( d === 0.0 ) {
  28924. this.lightDistance.visible = false;
  28925. } else {
  28926. this.lightDistance.scale.set( d, d, d );
  28927. }
  28928. this.add( this.lightDistance );
  28929. */
  28930. }
  28931. dispose() {
  28932. this.geometry.dispose();
  28933. this.material.dispose();
  28934. }
  28935. update() {
  28936. this.light.updateWorldMatrix( true, false );
  28937. if ( this.color !== undefined ) {
  28938. this.material.color.set( this.color );
  28939. } else {
  28940. this.material.color.copy( this.light.color );
  28941. }
  28942. /*
  28943. const d = this.light.distance;
  28944. if ( d === 0.0 ) {
  28945. this.lightDistance.visible = false;
  28946. } else {
  28947. this.lightDistance.visible = true;
  28948. this.lightDistance.scale.set( d, d, d );
  28949. }
  28950. */
  28951. }
  28952. }
  28953. const _vector$1 = /*@__PURE__*/ new Vector3();
  28954. const _color1 = /*@__PURE__*/ new Color();
  28955. const _color2 = /*@__PURE__*/ new Color();
  28956. class HemisphereLightHelper extends Object3D {
  28957. constructor( light, size, color ) {
  28958. super();
  28959. this.light = light;
  28960. this.matrix = light.matrixWorld;
  28961. this.matrixAutoUpdate = false;
  28962. this.color = color;
  28963. this.type = 'HemisphereLightHelper';
  28964. const geometry = new OctahedronGeometry( size );
  28965. geometry.rotateY( Math.PI * 0.5 );
  28966. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28967. if ( this.color === undefined ) this.material.vertexColors = true;
  28968. const position = geometry.getAttribute( 'position' );
  28969. const colors = new Float32Array( position.count * 3 );
  28970. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  28971. this.add( new Mesh( geometry, this.material ) );
  28972. this.update();
  28973. }
  28974. dispose() {
  28975. this.children[ 0 ].geometry.dispose();
  28976. this.children[ 0 ].material.dispose();
  28977. }
  28978. update() {
  28979. const mesh = this.children[ 0 ];
  28980. if ( this.color !== undefined ) {
  28981. this.material.color.set( this.color );
  28982. } else {
  28983. const colors = mesh.geometry.getAttribute( 'color' );
  28984. _color1.copy( this.light.color );
  28985. _color2.copy( this.light.groundColor );
  28986. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  28987. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  28988. colors.setXYZ( i, color.r, color.g, color.b );
  28989. }
  28990. colors.needsUpdate = true;
  28991. }
  28992. this.light.updateWorldMatrix( true, false );
  28993. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  28994. }
  28995. }
  28996. class GridHelper extends LineSegments {
  28997. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  28998. color1 = new Color( color1 );
  28999. color2 = new Color( color2 );
  29000. const center = divisions / 2;
  29001. const step = size / divisions;
  29002. const halfSize = size / 2;
  29003. const vertices = [], colors = [];
  29004. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  29005. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  29006. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  29007. const color = i === center ? color1 : color2;
  29008. color.toArray( colors, j ); j += 3;
  29009. color.toArray( colors, j ); j += 3;
  29010. color.toArray( colors, j ); j += 3;
  29011. color.toArray( colors, j ); j += 3;
  29012. }
  29013. const geometry = new BufferGeometry();
  29014. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29015. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29016. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29017. super( geometry, material );
  29018. this.type = 'GridHelper';
  29019. }
  29020. dispose() {
  29021. this.geometry.dispose();
  29022. this.material.dispose();
  29023. }
  29024. }
  29025. class PolarGridHelper extends LineSegments {
  29026. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  29027. color1 = new Color( color1 );
  29028. color2 = new Color( color2 );
  29029. const vertices = [];
  29030. const colors = [];
  29031. // create the sectors
  29032. if ( sectors > 1 ) {
  29033. for ( let i = 0; i < sectors; i ++ ) {
  29034. const v = ( i / sectors ) * ( Math.PI * 2 );
  29035. const x = Math.sin( v ) * radius;
  29036. const z = Math.cos( v ) * radius;
  29037. vertices.push( 0, 0, 0 );
  29038. vertices.push( x, 0, z );
  29039. const color = ( i & 1 ) ? color1 : color2;
  29040. colors.push( color.r, color.g, color.b );
  29041. colors.push( color.r, color.g, color.b );
  29042. }
  29043. }
  29044. // create the rings
  29045. for ( let i = 0; i < rings; i ++ ) {
  29046. const color = ( i & 1 ) ? color1 : color2;
  29047. const r = radius - ( radius / rings * i );
  29048. for ( let j = 0; j < divisions; j ++ ) {
  29049. // first vertex
  29050. let v = ( j / divisions ) * ( Math.PI * 2 );
  29051. let x = Math.sin( v ) * r;
  29052. let z = Math.cos( v ) * r;
  29053. vertices.push( x, 0, z );
  29054. colors.push( color.r, color.g, color.b );
  29055. // second vertex
  29056. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  29057. x = Math.sin( v ) * r;
  29058. z = Math.cos( v ) * r;
  29059. vertices.push( x, 0, z );
  29060. colors.push( color.r, color.g, color.b );
  29061. }
  29062. }
  29063. const geometry = new BufferGeometry();
  29064. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29065. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29066. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29067. super( geometry, material );
  29068. this.type = 'PolarGridHelper';
  29069. }
  29070. dispose() {
  29071. this.geometry.dispose();
  29072. this.material.dispose();
  29073. }
  29074. }
  29075. const _v1 = /*@__PURE__*/ new Vector3();
  29076. const _v2 = /*@__PURE__*/ new Vector3();
  29077. const _v3 = /*@__PURE__*/ new Vector3();
  29078. class DirectionalLightHelper extends Object3D {
  29079. constructor( light, size, color ) {
  29080. super();
  29081. this.light = light;
  29082. this.matrix = light.matrixWorld;
  29083. this.matrixAutoUpdate = false;
  29084. this.color = color;
  29085. this.type = 'DirectionalLightHelper';
  29086. if ( size === undefined ) size = 1;
  29087. let geometry = new BufferGeometry();
  29088. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  29089. - size, size, 0,
  29090. size, size, 0,
  29091. size, - size, 0,
  29092. - size, - size, 0,
  29093. - size, size, 0
  29094. ], 3 ) );
  29095. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  29096. this.lightPlane = new Line( geometry, material );
  29097. this.add( this.lightPlane );
  29098. geometry = new BufferGeometry();
  29099. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  29100. this.targetLine = new Line( geometry, material );
  29101. this.add( this.targetLine );
  29102. this.update();
  29103. }
  29104. dispose() {
  29105. this.lightPlane.geometry.dispose();
  29106. this.lightPlane.material.dispose();
  29107. this.targetLine.geometry.dispose();
  29108. this.targetLine.material.dispose();
  29109. }
  29110. update() {
  29111. this.light.updateWorldMatrix( true, false );
  29112. this.light.target.updateWorldMatrix( true, false );
  29113. _v1.setFromMatrixPosition( this.light.matrixWorld );
  29114. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  29115. _v3.subVectors( _v2, _v1 );
  29116. this.lightPlane.lookAt( _v2 );
  29117. if ( this.color !== undefined ) {
  29118. this.lightPlane.material.color.set( this.color );
  29119. this.targetLine.material.color.set( this.color );
  29120. } else {
  29121. this.lightPlane.material.color.copy( this.light.color );
  29122. this.targetLine.material.color.copy( this.light.color );
  29123. }
  29124. this.targetLine.lookAt( _v2 );
  29125. this.targetLine.scale.z = _v3.length();
  29126. }
  29127. }
  29128. const _vector = /*@__PURE__*/ new Vector3();
  29129. const _camera = /*@__PURE__*/ new Camera();
  29130. /**
  29131. * - shows frustum, line of sight and up of the camera
  29132. * - suitable for fast updates
  29133. * - based on frustum visualization in lightgl.js shadowmap example
  29134. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  29135. */
  29136. class CameraHelper extends LineSegments {
  29137. constructor( camera ) {
  29138. const geometry = new BufferGeometry();
  29139. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  29140. const vertices = [];
  29141. const colors = [];
  29142. const pointMap = {};
  29143. // near
  29144. addLine( 'n1', 'n2' );
  29145. addLine( 'n2', 'n4' );
  29146. addLine( 'n4', 'n3' );
  29147. addLine( 'n3', 'n1' );
  29148. // far
  29149. addLine( 'f1', 'f2' );
  29150. addLine( 'f2', 'f4' );
  29151. addLine( 'f4', 'f3' );
  29152. addLine( 'f3', 'f1' );
  29153. // sides
  29154. addLine( 'n1', 'f1' );
  29155. addLine( 'n2', 'f2' );
  29156. addLine( 'n3', 'f3' );
  29157. addLine( 'n4', 'f4' );
  29158. // cone
  29159. addLine( 'p', 'n1' );
  29160. addLine( 'p', 'n2' );
  29161. addLine( 'p', 'n3' );
  29162. addLine( 'p', 'n4' );
  29163. // up
  29164. addLine( 'u1', 'u2' );
  29165. addLine( 'u2', 'u3' );
  29166. addLine( 'u3', 'u1' );
  29167. // target
  29168. addLine( 'c', 't' );
  29169. addLine( 'p', 'c' );
  29170. // cross
  29171. addLine( 'cn1', 'cn2' );
  29172. addLine( 'cn3', 'cn4' );
  29173. addLine( 'cf1', 'cf2' );
  29174. addLine( 'cf3', 'cf4' );
  29175. function addLine( a, b ) {
  29176. addPoint( a );
  29177. addPoint( b );
  29178. }
  29179. function addPoint( id ) {
  29180. vertices.push( 0, 0, 0 );
  29181. colors.push( 0, 0, 0 );
  29182. if ( pointMap[ id ] === undefined ) {
  29183. pointMap[ id ] = [];
  29184. }
  29185. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  29186. }
  29187. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29188. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29189. super( geometry, material );
  29190. this.type = 'CameraHelper';
  29191. this.camera = camera;
  29192. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  29193. this.matrix = camera.matrixWorld;
  29194. this.matrixAutoUpdate = false;
  29195. this.pointMap = pointMap;
  29196. this.update();
  29197. // colors
  29198. const colorFrustum = new Color( 0xffaa00 );
  29199. const colorCone = new Color( 0xff0000 );
  29200. const colorUp = new Color( 0x00aaff );
  29201. const colorTarget = new Color( 0xffffff );
  29202. const colorCross = new Color( 0x333333 );
  29203. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  29204. }
  29205. setColors( frustum, cone, up, target, cross ) {
  29206. const geometry = this.geometry;
  29207. const colorAttribute = geometry.getAttribute( 'color' );
  29208. // near
  29209. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  29210. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  29211. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  29212. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  29213. // far
  29214. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  29215. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  29216. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  29217. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  29218. // sides
  29219. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  29220. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  29221. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  29222. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  29223. // cone
  29224. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  29225. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  29226. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  29227. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  29228. // up
  29229. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  29230. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  29231. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  29232. // target
  29233. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  29234. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  29235. // cross
  29236. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  29237. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  29238. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  29239. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  29240. colorAttribute.needsUpdate = true;
  29241. }
  29242. update() {
  29243. const geometry = this.geometry;
  29244. const pointMap = this.pointMap;
  29245. const w = 1, h = 1;
  29246. // we need just camera projection matrix inverse
  29247. // world matrix must be identity
  29248. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  29249. // center / target
  29250. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  29251. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  29252. // near
  29253. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  29254. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  29255. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  29256. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  29257. // far
  29258. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  29259. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  29260. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  29261. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  29262. // up
  29263. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  29264. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  29265. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  29266. // cross
  29267. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  29268. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  29269. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  29270. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  29271. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  29272. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  29273. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  29274. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  29275. geometry.getAttribute( 'position' ).needsUpdate = true;
  29276. }
  29277. dispose() {
  29278. this.geometry.dispose();
  29279. this.material.dispose();
  29280. }
  29281. }
  29282. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  29283. _vector.set( x, y, z ).unproject( camera );
  29284. const points = pointMap[ point ];
  29285. if ( points !== undefined ) {
  29286. const position = geometry.getAttribute( 'position' );
  29287. for ( let i = 0, l = points.length; i < l; i ++ ) {
  29288. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  29289. }
  29290. }
  29291. }
  29292. const _box = /*@__PURE__*/ new Box3();
  29293. class BoxHelper extends LineSegments {
  29294. constructor( object, color = 0xffff00 ) {
  29295. 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 ] );
  29296. const positions = new Float32Array( 8 * 3 );
  29297. const geometry = new BufferGeometry();
  29298. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29299. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  29300. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29301. this.object = object;
  29302. this.type = 'BoxHelper';
  29303. this.matrixAutoUpdate = false;
  29304. this.update();
  29305. }
  29306. update( object ) {
  29307. if ( object !== undefined ) {
  29308. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  29309. }
  29310. if ( this.object !== undefined ) {
  29311. _box.setFromObject( this.object );
  29312. }
  29313. if ( _box.isEmpty() ) return;
  29314. const min = _box.min;
  29315. const max = _box.max;
  29316. /*
  29317. 5____4
  29318. 1/___0/|
  29319. | 6__|_7
  29320. 2/___3/
  29321. 0: max.x, max.y, max.z
  29322. 1: min.x, max.y, max.z
  29323. 2: min.x, min.y, max.z
  29324. 3: max.x, min.y, max.z
  29325. 4: max.x, max.y, min.z
  29326. 5: min.x, max.y, min.z
  29327. 6: min.x, min.y, min.z
  29328. 7: max.x, min.y, min.z
  29329. */
  29330. const position = this.geometry.attributes.position;
  29331. const array = position.array;
  29332. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  29333. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  29334. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  29335. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  29336. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  29337. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  29338. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  29339. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  29340. position.needsUpdate = true;
  29341. this.geometry.computeBoundingSphere();
  29342. }
  29343. setFromObject( object ) {
  29344. this.object = object;
  29345. this.update();
  29346. return this;
  29347. }
  29348. copy( source, recursive ) {
  29349. super.copy( source, recursive );
  29350. this.object = source.object;
  29351. return this;
  29352. }
  29353. dispose() {
  29354. this.geometry.dispose();
  29355. this.material.dispose();
  29356. }
  29357. }
  29358. class Box3Helper extends LineSegments {
  29359. constructor( box, color = 0xffff00 ) {
  29360. 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 ] );
  29361. 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 ];
  29362. const geometry = new BufferGeometry();
  29363. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  29364. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29365. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29366. this.box = box;
  29367. this.type = 'Box3Helper';
  29368. this.geometry.computeBoundingSphere();
  29369. }
  29370. updateMatrixWorld( force ) {
  29371. const box = this.box;
  29372. if ( box.isEmpty() ) return;
  29373. box.getCenter( this.position );
  29374. box.getSize( this.scale );
  29375. this.scale.multiplyScalar( 0.5 );
  29376. super.updateMatrixWorld( force );
  29377. }
  29378. dispose() {
  29379. this.geometry.dispose();
  29380. this.material.dispose();
  29381. }
  29382. }
  29383. class PlaneHelper extends Line {
  29384. constructor( plane, size = 1, hex = 0xffff00 ) {
  29385. const color = hex;
  29386. 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 ];
  29387. const geometry = new BufferGeometry();
  29388. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29389. geometry.computeBoundingSphere();
  29390. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29391. this.type = 'PlaneHelper';
  29392. this.plane = plane;
  29393. this.size = size;
  29394. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  29395. const geometry2 = new BufferGeometry();
  29396. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  29397. geometry2.computeBoundingSphere();
  29398. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  29399. }
  29400. updateMatrixWorld( force ) {
  29401. this.position.set( 0, 0, 0 );
  29402. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  29403. this.lookAt( this.plane.normal );
  29404. this.translateZ( - this.plane.constant );
  29405. super.updateMatrixWorld( force );
  29406. }
  29407. dispose() {
  29408. this.geometry.dispose();
  29409. this.material.dispose();
  29410. this.children[ 0 ].geometry.dispose();
  29411. this.children[ 0 ].material.dispose();
  29412. }
  29413. }
  29414. const _axis = /*@__PURE__*/ new Vector3();
  29415. let _lineGeometry, _coneGeometry;
  29416. class ArrowHelper extends Object3D {
  29417. // dir is assumed to be normalized
  29418. 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 ) {
  29419. super();
  29420. this.type = 'ArrowHelper';
  29421. if ( _lineGeometry === undefined ) {
  29422. _lineGeometry = new BufferGeometry();
  29423. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  29424. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  29425. _coneGeometry.translate( 0, - 0.5, 0 );
  29426. }
  29427. this.position.copy( origin );
  29428. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  29429. this.line.matrixAutoUpdate = false;
  29430. this.add( this.line );
  29431. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  29432. this.cone.matrixAutoUpdate = false;
  29433. this.add( this.cone );
  29434. this.setDirection( dir );
  29435. this.setLength( length, headLength, headWidth );
  29436. }
  29437. setDirection( dir ) {
  29438. // dir is assumed to be normalized
  29439. if ( dir.y > 0.99999 ) {
  29440. this.quaternion.set( 0, 0, 0, 1 );
  29441. } else if ( dir.y < - 0.99999 ) {
  29442. this.quaternion.set( 1, 0, 0, 0 );
  29443. } else {
  29444. _axis.set( dir.z, 0, - dir.x ).normalize();
  29445. const radians = Math.acos( dir.y );
  29446. this.quaternion.setFromAxisAngle( _axis, radians );
  29447. }
  29448. }
  29449. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  29450. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  29451. this.line.updateMatrix();
  29452. this.cone.scale.set( headWidth, headLength, headWidth );
  29453. this.cone.position.y = length;
  29454. this.cone.updateMatrix();
  29455. }
  29456. setColor( color ) {
  29457. this.line.material.color.set( color );
  29458. this.cone.material.color.set( color );
  29459. }
  29460. copy( source ) {
  29461. super.copy( source, false );
  29462. this.line.copy( source.line );
  29463. this.cone.copy( source.cone );
  29464. return this;
  29465. }
  29466. dispose() {
  29467. this.line.geometry.dispose();
  29468. this.line.material.dispose();
  29469. this.cone.geometry.dispose();
  29470. this.cone.material.dispose();
  29471. }
  29472. }
  29473. class AxesHelper extends LineSegments {
  29474. constructor( size = 1 ) {
  29475. const vertices = [
  29476. 0, 0, 0, size, 0, 0,
  29477. 0, 0, 0, 0, size, 0,
  29478. 0, 0, 0, 0, 0, size
  29479. ];
  29480. const colors = [
  29481. 1, 0, 0, 1, 0.6, 0,
  29482. 0, 1, 0, 0.6, 1, 0,
  29483. 0, 0, 1, 0, 0.6, 1
  29484. ];
  29485. const geometry = new BufferGeometry();
  29486. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29487. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29488. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  29489. super( geometry, material );
  29490. this.type = 'AxesHelper';
  29491. }
  29492. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  29493. const color = new Color();
  29494. const array = this.geometry.attributes.color.array;
  29495. color.set( xAxisColor );
  29496. color.toArray( array, 0 );
  29497. color.toArray( array, 3 );
  29498. color.set( yAxisColor );
  29499. color.toArray( array, 6 );
  29500. color.toArray( array, 9 );
  29501. color.set( zAxisColor );
  29502. color.toArray( array, 12 );
  29503. color.toArray( array, 15 );
  29504. this.geometry.attributes.color.needsUpdate = true;
  29505. return this;
  29506. }
  29507. dispose() {
  29508. this.geometry.dispose();
  29509. this.material.dispose();
  29510. }
  29511. }
  29512. class ShapePath {
  29513. constructor() {
  29514. this.type = 'ShapePath';
  29515. this.color = new Color();
  29516. this.subPaths = [];
  29517. this.currentPath = null;
  29518. }
  29519. moveTo( x, y ) {
  29520. this.currentPath = new Path();
  29521. this.subPaths.push( this.currentPath );
  29522. this.currentPath.moveTo( x, y );
  29523. return this;
  29524. }
  29525. lineTo( x, y ) {
  29526. this.currentPath.lineTo( x, y );
  29527. return this;
  29528. }
  29529. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  29530. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  29531. return this;
  29532. }
  29533. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  29534. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  29535. return this;
  29536. }
  29537. splineThru( pts ) {
  29538. this.currentPath.splineThru( pts );
  29539. return this;
  29540. }
  29541. toShapes( isCCW ) {
  29542. function toShapesNoHoles( inSubpaths ) {
  29543. const shapes = [];
  29544. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  29545. const tmpPath = inSubpaths[ i ];
  29546. const tmpShape = new Shape();
  29547. tmpShape.curves = tmpPath.curves;
  29548. shapes.push( tmpShape );
  29549. }
  29550. return shapes;
  29551. }
  29552. function isPointInsidePolygon( inPt, inPolygon ) {
  29553. const polyLen = inPolygon.length;
  29554. // inPt on polygon contour => immediate success or
  29555. // toggling of inside/outside at every single! intersection point of an edge
  29556. // with the horizontal line through inPt, left of inPt
  29557. // not counting lowerY endpoints of edges and whole edges on that line
  29558. let inside = false;
  29559. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  29560. let edgeLowPt = inPolygon[ p ];
  29561. let edgeHighPt = inPolygon[ q ];
  29562. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  29563. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  29564. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  29565. // not parallel
  29566. if ( edgeDy < 0 ) {
  29567. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  29568. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  29569. }
  29570. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  29571. if ( inPt.y === edgeLowPt.y ) {
  29572. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  29573. // continue; // no intersection or edgeLowPt => doesn't count !!!
  29574. } else {
  29575. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  29576. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  29577. if ( perpEdge < 0 ) continue;
  29578. inside = ! inside; // true intersection left of inPt
  29579. }
  29580. } else {
  29581. // parallel or collinear
  29582. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  29583. // edge lies on the same horizontal line as inPt
  29584. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  29585. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  29586. // continue;
  29587. }
  29588. }
  29589. return inside;
  29590. }
  29591. const isClockWise = ShapeUtils.isClockWise;
  29592. const subPaths = this.subPaths;
  29593. if ( subPaths.length === 0 ) return [];
  29594. let solid, tmpPath, tmpShape;
  29595. const shapes = [];
  29596. if ( subPaths.length === 1 ) {
  29597. tmpPath = subPaths[ 0 ];
  29598. tmpShape = new Shape();
  29599. tmpShape.curves = tmpPath.curves;
  29600. shapes.push( tmpShape );
  29601. return shapes;
  29602. }
  29603. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  29604. holesFirst = isCCW ? ! holesFirst : holesFirst;
  29605. // console.log("Holes first", holesFirst);
  29606. const betterShapeHoles = [];
  29607. const newShapes = [];
  29608. let newShapeHoles = [];
  29609. let mainIdx = 0;
  29610. let tmpPoints;
  29611. newShapes[ mainIdx ] = undefined;
  29612. newShapeHoles[ mainIdx ] = [];
  29613. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  29614. tmpPath = subPaths[ i ];
  29615. tmpPoints = tmpPath.getPoints();
  29616. solid = isClockWise( tmpPoints );
  29617. solid = isCCW ? ! solid : solid;
  29618. if ( solid ) {
  29619. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  29620. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  29621. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  29622. if ( holesFirst ) mainIdx ++;
  29623. newShapeHoles[ mainIdx ] = [];
  29624. //console.log('cw', i);
  29625. } else {
  29626. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  29627. //console.log('ccw', i);
  29628. }
  29629. }
  29630. // only Holes? -> probably all Shapes with wrong orientation
  29631. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  29632. if ( newShapes.length > 1 ) {
  29633. let ambiguous = false;
  29634. let toChange = 0;
  29635. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29636. betterShapeHoles[ sIdx ] = [];
  29637. }
  29638. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  29639. const sho = newShapeHoles[ sIdx ];
  29640. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  29641. const ho = sho[ hIdx ];
  29642. let hole_unassigned = true;
  29643. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  29644. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  29645. if ( sIdx !== s2Idx ) toChange ++;
  29646. if ( hole_unassigned ) {
  29647. hole_unassigned = false;
  29648. betterShapeHoles[ s2Idx ].push( ho );
  29649. } else {
  29650. ambiguous = true;
  29651. }
  29652. }
  29653. }
  29654. if ( hole_unassigned ) {
  29655. betterShapeHoles[ sIdx ].push( ho );
  29656. }
  29657. }
  29658. }
  29659. if ( toChange > 0 && ambiguous === false ) {
  29660. newShapeHoles = betterShapeHoles;
  29661. }
  29662. }
  29663. let tmpHoles;
  29664. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  29665. tmpShape = newShapes[ i ].s;
  29666. shapes.push( tmpShape );
  29667. tmpHoles = newShapeHoles[ i ];
  29668. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  29669. tmpShape.holes.push( tmpHoles[ j ].h );
  29670. }
  29671. }
  29672. //console.log("shape", shapes);
  29673. return shapes;
  29674. }
  29675. }
  29676. // r144
  29677. class BoxBufferGeometry extends BoxGeometry {
  29678. constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  29679. console.warn( 'THREE.BoxBufferGeometry has been renamed to THREE.BoxGeometry.' );
  29680. super( width, height, depth, widthSegments, heightSegments, depthSegments );
  29681. }
  29682. }
  29683. // r144
  29684. class CapsuleBufferGeometry extends CapsuleGeometry {
  29685. constructor( radius, length, capSegments, radialSegments ) {
  29686. console.warn( 'THREE.CapsuleBufferGeometry has been renamed to THREE.CapsuleGeometry.' );
  29687. super( radius, length, capSegments, radialSegments );
  29688. }
  29689. }
  29690. // r144
  29691. class CircleBufferGeometry extends CircleGeometry {
  29692. constructor( radius, segments, thetaStart, thetaLength ) {
  29693. console.warn( 'THREE.CircleBufferGeometry has been renamed to THREE.CircleGeometry.' );
  29694. super( radius, segments, thetaStart, thetaLength );
  29695. }
  29696. }
  29697. // r144
  29698. class ConeBufferGeometry extends ConeGeometry {
  29699. constructor( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  29700. console.warn( 'THREE.ConeBufferGeometry has been renamed to THREE.ConeGeometry.' );
  29701. super( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  29702. }
  29703. }
  29704. // r144
  29705. class CylinderBufferGeometry extends CylinderGeometry {
  29706. constructor( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  29707. console.warn( 'THREE.CylinderBufferGeometry has been renamed to THREE.CylinderGeometry.' );
  29708. super( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  29709. }
  29710. }
  29711. // r144
  29712. class DodecahedronBufferGeometry extends DodecahedronGeometry {
  29713. constructor( radius, detail ) {
  29714. console.warn( 'THREE.DodecahedronBufferGeometry has been renamed to THREE.DodecahedronGeometry.' );
  29715. super( radius, detail );
  29716. }
  29717. }
  29718. // r144
  29719. class ExtrudeBufferGeometry extends ExtrudeGeometry {
  29720. constructor( shapes, options ) {
  29721. console.warn( 'THREE.ExtrudeBufferGeometry has been renamed to THREE.ExtrudeGeometry.' );
  29722. super( shapes, options );
  29723. }
  29724. }
  29725. // r144
  29726. class IcosahedronBufferGeometry extends IcosahedronGeometry {
  29727. constructor( radius, detail ) {
  29728. console.warn( 'THREE.IcosahedronBufferGeometry has been renamed to THREE.IcosahedronGeometry.' );
  29729. super( radius, detail );
  29730. }
  29731. }
  29732. // r144
  29733. class LatheBufferGeometry extends LatheGeometry {
  29734. constructor( points, segments, phiStart, phiLength ) {
  29735. console.warn( 'THREE.LatheBufferGeometry has been renamed to THREE.LatheGeometry.' );
  29736. super( points, segments, phiStart, phiLength );
  29737. }
  29738. }
  29739. // r144
  29740. class OctahedronBufferGeometry extends OctahedronGeometry {
  29741. constructor( radius, detail ) {
  29742. console.warn( 'THREE.OctahedronBufferGeometry has been renamed to THREE.OctahedronGeometry.' );
  29743. super( radius, detail );
  29744. }
  29745. }
  29746. // r144
  29747. class PlaneBufferGeometry extends PlaneGeometry {
  29748. constructor( width, height, widthSegments, heightSegments ) {
  29749. console.warn( 'THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry.' );
  29750. super( width, height, widthSegments, heightSegments );
  29751. }
  29752. }
  29753. // r144
  29754. class PolyhedronBufferGeometry extends PolyhedronGeometry {
  29755. constructor( vertices, indices, radius, detail ) {
  29756. console.warn( 'THREE.PolyhedronBufferGeometry has been renamed to THREE.PolyhedronGeometry.' );
  29757. super( vertices, indices, radius, detail );
  29758. }
  29759. }
  29760. // r144
  29761. class RingBufferGeometry extends RingGeometry {
  29762. constructor( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  29763. console.warn( 'THREE.RingBufferGeometry has been renamed to THREE.RingGeometry.' );
  29764. super( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength );
  29765. }
  29766. }
  29767. // r144
  29768. class ShapeBufferGeometry extends ShapeGeometry {
  29769. constructor( shapes, curveSegments ) {
  29770. console.warn( 'THREE.ShapeBufferGeometry has been renamed to THREE.ShapeGeometry.' );
  29771. super( shapes, curveSegments );
  29772. }
  29773. }
  29774. // r144
  29775. class SphereBufferGeometry extends SphereGeometry {
  29776. constructor( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  29777. console.warn( 'THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry.' );
  29778. super( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength );
  29779. }
  29780. }
  29781. // r144
  29782. class TetrahedronBufferGeometry extends TetrahedronGeometry {
  29783. constructor( radius, detail ) {
  29784. console.warn( 'THREE.TetrahedronBufferGeometry has been renamed to THREE.TetrahedronGeometry.' );
  29785. super( radius, detail );
  29786. }
  29787. }
  29788. // r144
  29789. class TorusBufferGeometry extends TorusGeometry {
  29790. constructor( radius, tube, radialSegments, tubularSegments, arc ) {
  29791. console.warn( 'THREE.TorusBufferGeometry has been renamed to THREE.TorusGeometry.' );
  29792. super( radius, tube, radialSegments, tubularSegments, arc );
  29793. }
  29794. }
  29795. // r144
  29796. class TorusKnotBufferGeometry extends TorusKnotGeometry {
  29797. constructor( radius, tube, tubularSegments, radialSegments, p, q ) {
  29798. console.warn( 'THREE.TorusKnotBufferGeometry has been renamed to THREE.TorusKnotGeometry.' );
  29799. super( radius, tube, tubularSegments, radialSegments, p, q );
  29800. }
  29801. }
  29802. // r144
  29803. class TubeBufferGeometry extends TubeGeometry {
  29804. constructor( path, tubularSegments, radius, radialSegments, closed ) {
  29805. console.warn( 'THREE.TubeBufferGeometry has been renamed to THREE.TubeGeometry.' );
  29806. super( path, tubularSegments, radius, radialSegments, closed );
  29807. }
  29808. }
  29809. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  29810. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  29811. revision: REVISION,
  29812. } } ) );
  29813. }
  29814. if ( typeof window !== 'undefined' ) {
  29815. if ( window.__THREE__ ) {
  29816. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  29817. } else {
  29818. window.__THREE__ = REVISION;
  29819. }
  29820. }
  29821. export { ACESFilmicToneMapping, AddEquation, AddOperation, AdditiveAnimationBlendMode, AdditiveBlending, AlphaFormat, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightProbe, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrayCamera, ArrowHelper, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BackSide, BasicDepthPacking, BasicShadowMap, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxBufferGeometry, BoxGeometry, BoxHelper, BufferAttribute, BufferGeometry, BufferGeometryLoader, ByteType, Cache, Camera, CameraHelper, CanvasTexture, CapsuleBufferGeometry, CapsuleGeometry, CatmullRomCurve3, CineonToneMapping, CircleBufferGeometry, CircleGeometry, ClampToEdgeWrapping, Clock, Color, ColorKeyframeTrack, ColorManagement, CompressedArrayTexture, CompressedTexture, CompressedTextureLoader, ConeBufferGeometry, ConeGeometry, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureLoader, CubeUVReflectionMapping, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceBack, CullFaceFront, CullFaceFrontBack, CullFaceNone, Curve, CurvePath, CustomBlending, CustomToneMapping, CylinderBufferGeometry, CylinderGeometry, Cylindrical, Data3DTexture, DataArrayTexture, DataTexture, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DisplayP3ColorSpace, DodecahedronBufferGeometry, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeBufferGeometry, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Float32BufferAttribute, Float64BufferAttribute, FloatType, Fog, FogExp2, FramebufferTexture, FrontSide, Frustum, GLBufferAttribute, GLSL1, GLSL3, GreaterDepth, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightProbe, IcosahedronBufferGeometry, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, IncrementStencilOp, IncrementWrapStencilOp, InstancedBufferAttribute, InstancedBufferGeometry, InstancedInterleavedBuffer, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, IntType, InterleavedBuffer, InterleavedBufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InvertStencilOp, KeepStencilOp, KeyframeTrack, LOD, LatheBufferGeometry, LatheGeometry, Layers, LessDepth, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, Light, LightProbe, Line, Line3, LineBasicMaterial, LineCurve, LineCurve3, LineDashedMaterial, LineLoop, LineSegments, LinearEncoding, LinearFilter, LinearInterpolant, LinearMipMapLinearFilter, LinearMipMapNearestFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, Loader, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, LuminanceAlphaFormat, LuminanceFormat, MOUSE, Material, MaterialLoader, MathUtils, Matrix3, Matrix4, MaxEquation, Mesh, MeshBasicMaterial, MeshDepthMaterial, MeshDistanceMaterial, MeshLambertMaterial, MeshMatcapMaterial, MeshNormalMaterial, MeshPhongMaterial, MeshPhysicalMaterial, MeshStandardMaterial, MeshToonMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, NormalAnimationBlendMode, NormalBlending, NotEqualDepth, NotEqualStencilFunc, NumberKeyframeTrack, Object3D, ObjectLoader, ObjectSpaceNormalMap, OctahedronBufferGeometry, OctahedronGeometry, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, PCFShadowMap, PCFSoftShadowMap, PMREMGenerator, Path, PerspectiveCamera, Plane, PlaneBufferGeometry, PlaneGeometry, PlaneHelper, PointLight, PointLightHelper, Points, PointsMaterial, PolarGridHelper, PolyhedronBufferGeometry, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBADepthPacking, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RawShaderMaterial, Ray, Raycaster, RectAreaLight, RedFormat, RedIntegerFormat, ReinhardToneMapping, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RingBufferGeometry, RingGeometry, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, Scene, ShaderChunk, ShaderLib, ShaderMaterial, ShadowMaterial, Shape, ShapeBufferGeometry, ShapeGeometry, ShapePath, ShapeUtils, ShortType, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, SphereBufferGeometry, SphereGeometry, Spherical, SphericalHarmonics3, SplineCurve, SpotLight, SpotLightHelper, Sprite, SpriteMaterial, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StaticCopyUsage, StaticDrawUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, SubtractEquation, SubtractiveBlending, TOUCH, TangentSpaceNormalMap, TetrahedronBufferGeometry, TetrahedronGeometry, Texture, TextureLoader, TorusBufferGeometry, TorusGeometry, TorusKnotBufferGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeBufferGeometry, TubeGeometry, TwoPassDoubleSide, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, UniformsLib, UniformsUtils, UnsignedByteType, UnsignedInt248Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, VSMShadowMap, Vector2, Vector3, Vector4, VectorKeyframeTrack, VideoTexture, WebGL1Renderer, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLCubeRenderTarget, WebGLMultipleRenderTargets, WebGLRenderTarget, WebGLRenderer, WebGLUtils, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, _SRGBAFormat, sRGBEncoding };