three.module.js 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550
  1. /**
  2. * @license
  3. * Copyright 2010-2022 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. const REVISION = '144dev';
  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 NoBlending = 0;
  21. const NormalBlending = 1;
  22. const AdditiveBlending = 2;
  23. const SubtractiveBlending = 3;
  24. const MultiplyBlending = 4;
  25. const CustomBlending = 5;
  26. const AddEquation = 100;
  27. const SubtractEquation = 101;
  28. const ReverseSubtractEquation = 102;
  29. const MinEquation = 103;
  30. const MaxEquation = 104;
  31. const ZeroFactor = 200;
  32. const OneFactor = 201;
  33. const SrcColorFactor = 202;
  34. const OneMinusSrcColorFactor = 203;
  35. const SrcAlphaFactor = 204;
  36. const OneMinusSrcAlphaFactor = 205;
  37. const DstAlphaFactor = 206;
  38. const OneMinusDstAlphaFactor = 207;
  39. const DstColorFactor = 208;
  40. const OneMinusDstColorFactor = 209;
  41. const SrcAlphaSaturateFactor = 210;
  42. const NeverDepth = 0;
  43. const AlwaysDepth = 1;
  44. const LessDepth = 2;
  45. const LessEqualDepth = 3;
  46. const EqualDepth = 4;
  47. const GreaterEqualDepth = 5;
  48. const GreaterDepth = 6;
  49. const NotEqualDepth = 7;
  50. const MultiplyOperation = 0;
  51. const MixOperation = 1;
  52. const AddOperation = 2;
  53. const NoToneMapping = 0;
  54. const LinearToneMapping = 1;
  55. const ReinhardToneMapping = 2;
  56. const CineonToneMapping = 3;
  57. const ACESFilmicToneMapping = 4;
  58. const CustomToneMapping = 5;
  59. const UVMapping = 300;
  60. const CubeReflectionMapping = 301;
  61. const CubeRefractionMapping = 302;
  62. const EquirectangularReflectionMapping = 303;
  63. const EquirectangularRefractionMapping = 304;
  64. const CubeUVReflectionMapping = 306;
  65. const RepeatWrapping = 1000;
  66. const ClampToEdgeWrapping = 1001;
  67. const MirroredRepeatWrapping = 1002;
  68. const NearestFilter = 1003;
  69. const NearestMipmapNearestFilter = 1004;
  70. const NearestMipMapNearestFilter = 1004;
  71. const NearestMipmapLinearFilter = 1005;
  72. const NearestMipMapLinearFilter = 1005;
  73. const LinearFilter = 1006;
  74. const LinearMipmapNearestFilter = 1007;
  75. const LinearMipMapNearestFilter = 1007;
  76. const LinearMipmapLinearFilter = 1008;
  77. const LinearMipMapLinearFilter = 1008;
  78. const UnsignedByteType = 1009;
  79. const ByteType = 1010;
  80. const ShortType = 1011;
  81. const UnsignedShortType = 1012;
  82. const IntType = 1013;
  83. const UnsignedIntType = 1014;
  84. const FloatType = 1015;
  85. const HalfFloatType = 1016;
  86. const UnsignedShort4444Type = 1017;
  87. const UnsignedShort5551Type = 1018;
  88. const UnsignedInt248Type = 1020;
  89. const AlphaFormat = 1021;
  90. const RGBFormat = 1022; // @deprecated since r137
  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 LoopOnce = 2200;
  128. const LoopRepeat = 2201;
  129. const LoopPingPong = 2202;
  130. const InterpolateDiscrete = 2300;
  131. const InterpolateLinear = 2301;
  132. const InterpolateSmooth = 2302;
  133. const ZeroCurvatureEnding = 2400;
  134. const ZeroSlopeEnding = 2401;
  135. const WrapAroundEnding = 2402;
  136. const NormalAnimationBlendMode = 2500;
  137. const AdditiveAnimationBlendMode = 2501;
  138. const TrianglesDrawMode = 0;
  139. const TriangleStripDrawMode = 1;
  140. const TriangleFanDrawMode = 2;
  141. const LinearEncoding = 3000;
  142. const sRGBEncoding = 3001;
  143. const BasicDepthPacking = 3200;
  144. const RGBADepthPacking = 3201;
  145. const TangentSpaceNormalMap = 0;
  146. const ObjectSpaceNormalMap = 1;
  147. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  148. const NoColorSpace = '';
  149. const SRGBColorSpace = 'srgb';
  150. const LinearSRGBColorSpace = 'srgb-linear';
  151. const ZeroStencilOp = 0;
  152. const KeepStencilOp = 7680;
  153. const ReplaceStencilOp = 7681;
  154. const IncrementStencilOp = 7682;
  155. const DecrementStencilOp = 7683;
  156. const IncrementWrapStencilOp = 34055;
  157. const DecrementWrapStencilOp = 34056;
  158. const InvertStencilOp = 5386;
  159. const NeverStencilFunc = 512;
  160. const LessStencilFunc = 513;
  161. const EqualStencilFunc = 514;
  162. const LessEqualStencilFunc = 515;
  163. const GreaterStencilFunc = 516;
  164. const NotEqualStencilFunc = 517;
  165. const GreaterEqualStencilFunc = 518;
  166. const AlwaysStencilFunc = 519;
  167. const StaticDrawUsage = 35044;
  168. const DynamicDrawUsage = 35048;
  169. const StreamDrawUsage = 35040;
  170. const StaticReadUsage = 35045;
  171. const DynamicReadUsage = 35049;
  172. const StreamReadUsage = 35041;
  173. const StaticCopyUsage = 35046;
  174. const DynamicCopyUsage = 35050;
  175. const StreamCopyUsage = 35042;
  176. const GLSL1 = '100';
  177. const GLSL3 = '300 es';
  178. const _SRGBAFormat = 1035; // fallback for WebGL 1
  179. /**
  180. * https://github.com/mrdoob/eventdispatcher.js/
  181. */
  182. class EventDispatcher {
  183. addEventListener( type, listener ) {
  184. if ( this._listeners === undefined ) this._listeners = {};
  185. const listeners = this._listeners;
  186. if ( listeners[ type ] === undefined ) {
  187. listeners[ type ] = [];
  188. }
  189. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  190. listeners[ type ].push( listener );
  191. }
  192. }
  193. hasEventListener( type, listener ) {
  194. if ( this._listeners === undefined ) return false;
  195. const listeners = this._listeners;
  196. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  197. }
  198. removeEventListener( type, listener ) {
  199. if ( this._listeners === undefined ) return;
  200. const listeners = this._listeners;
  201. const listenerArray = listeners[ type ];
  202. if ( listenerArray !== undefined ) {
  203. const index = listenerArray.indexOf( listener );
  204. if ( index !== - 1 ) {
  205. listenerArray.splice( index, 1 );
  206. }
  207. }
  208. }
  209. dispatchEvent( event ) {
  210. if ( this._listeners === undefined ) return;
  211. const listeners = this._listeners;
  212. const listenerArray = listeners[ event.type ];
  213. if ( listenerArray !== undefined ) {
  214. event.target = this;
  215. // Make a copy, in case listeners are removed while iterating.
  216. const array = listenerArray.slice( 0 );
  217. for ( let i = 0, l = array.length; i < l; i ++ ) {
  218. array[ i ].call( this, event );
  219. }
  220. event.target = null;
  221. }
  222. }
  223. }
  224. 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' ];
  225. let _seed = 1234567;
  226. const DEG2RAD = Math.PI / 180;
  227. const RAD2DEG = 180 / Math.PI;
  228. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  229. function generateUUID() {
  230. const d0 = Math.random() * 0xffffffff | 0;
  231. const d1 = Math.random() * 0xffffffff | 0;
  232. const d2 = Math.random() * 0xffffffff | 0;
  233. const d3 = Math.random() * 0xffffffff | 0;
  234. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  235. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  236. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  237. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  238. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  239. return uuid.toLowerCase();
  240. }
  241. function clamp( value, min, max ) {
  242. return Math.max( min, Math.min( max, value ) );
  243. }
  244. // compute euclidean modulo of m % n
  245. // https://en.wikipedia.org/wiki/Modulo_operation
  246. function euclideanModulo( n, m ) {
  247. return ( ( n % m ) + m ) % m;
  248. }
  249. // Linear mapping from range <a1, a2> to range <b1, b2>
  250. function mapLinear( x, a1, a2, b1, b2 ) {
  251. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  252. }
  253. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  254. function inverseLerp( x, y, value ) {
  255. if ( x !== y ) {
  256. return ( value - x ) / ( y - x );
  257. } else {
  258. return 0;
  259. }
  260. }
  261. // https://en.wikipedia.org/wiki/Linear_interpolation
  262. function lerp( x, y, t ) {
  263. return ( 1 - t ) * x + t * y;
  264. }
  265. // http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
  266. function damp( x, y, lambda, dt ) {
  267. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  268. }
  269. // https://www.desmos.com/calculator/vcsjnyz7x4
  270. function pingpong( x, length = 1 ) {
  271. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  272. }
  273. // http://en.wikipedia.org/wiki/Smoothstep
  274. function smoothstep( x, min, max ) {
  275. if ( x <= min ) return 0;
  276. if ( x >= max ) return 1;
  277. x = ( x - min ) / ( max - min );
  278. return x * x * ( 3 - 2 * x );
  279. }
  280. function smootherstep( x, min, max ) {
  281. if ( x <= min ) return 0;
  282. if ( x >= max ) return 1;
  283. x = ( x - min ) / ( max - min );
  284. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  285. }
  286. // Random integer from <low, high> interval
  287. function randInt( low, high ) {
  288. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  289. }
  290. // Random float from <low, high> interval
  291. function randFloat( low, high ) {
  292. return low + Math.random() * ( high - low );
  293. }
  294. // Random float from <-range/2, range/2> interval
  295. function randFloatSpread( range ) {
  296. return range * ( 0.5 - Math.random() );
  297. }
  298. // Deterministic pseudo-random float in the interval [ 0, 1 ]
  299. function seededRandom( s ) {
  300. if ( s !== undefined ) _seed = s;
  301. // Mulberry32 generator
  302. let t = _seed += 0x6D2B79F5;
  303. t = Math.imul( t ^ t >>> 15, t | 1 );
  304. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  305. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  306. }
  307. function degToRad( degrees ) {
  308. return degrees * DEG2RAD;
  309. }
  310. function radToDeg( radians ) {
  311. return radians * RAD2DEG;
  312. }
  313. function isPowerOfTwo( value ) {
  314. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  315. }
  316. function ceilPowerOfTwo( value ) {
  317. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  318. }
  319. function floorPowerOfTwo( value ) {
  320. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  321. }
  322. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  323. // Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
  324. // rotations are applied to the axes in the order specified by 'order'
  325. // rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
  326. // angles are in radians
  327. const cos = Math.cos;
  328. const sin = Math.sin;
  329. const c2 = cos( b / 2 );
  330. const s2 = sin( b / 2 );
  331. const c13 = cos( ( a + c ) / 2 );
  332. const s13 = sin( ( a + c ) / 2 );
  333. const c1_3 = cos( ( a - c ) / 2 );
  334. const s1_3 = sin( ( a - c ) / 2 );
  335. const c3_1 = cos( ( c - a ) / 2 );
  336. const s3_1 = sin( ( c - a ) / 2 );
  337. switch ( order ) {
  338. case 'XYX':
  339. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  340. break;
  341. case 'YZY':
  342. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  343. break;
  344. case 'ZXZ':
  345. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  346. break;
  347. case 'XZX':
  348. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  349. break;
  350. case 'YXY':
  351. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  352. break;
  353. case 'ZYZ':
  354. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  355. break;
  356. default:
  357. console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  358. }
  359. }
  360. function denormalize$1( value, array ) {
  361. switch ( array.constructor ) {
  362. case Float32Array:
  363. return value;
  364. case Uint16Array:
  365. return value / 65535.0;
  366. case Uint8Array:
  367. return value / 255.0;
  368. case Int16Array:
  369. return Math.max( value / 32767.0, - 1.0 );
  370. case Int8Array:
  371. return Math.max( value / 127.0, - 1.0 );
  372. default:
  373. throw new Error( 'Invalid component type.' );
  374. }
  375. }
  376. function normalize( value, array ) {
  377. switch ( array.constructor ) {
  378. case Float32Array:
  379. return value;
  380. case Uint16Array:
  381. return Math.round( value * 65535.0 );
  382. case Uint8Array:
  383. return Math.round( value * 255.0 );
  384. case Int16Array:
  385. return Math.round( value * 32767.0 );
  386. case Int8Array:
  387. return Math.round( value * 127.0 );
  388. default:
  389. throw new Error( 'Invalid component type.' );
  390. }
  391. }
  392. var MathUtils = /*#__PURE__*/Object.freeze({
  393. __proto__: null,
  394. DEG2RAD: DEG2RAD,
  395. RAD2DEG: RAD2DEG,
  396. generateUUID: generateUUID,
  397. clamp: clamp,
  398. euclideanModulo: euclideanModulo,
  399. mapLinear: mapLinear,
  400. inverseLerp: inverseLerp,
  401. lerp: lerp,
  402. damp: damp,
  403. pingpong: pingpong,
  404. smoothstep: smoothstep,
  405. smootherstep: smootherstep,
  406. randInt: randInt,
  407. randFloat: randFloat,
  408. randFloatSpread: randFloatSpread,
  409. seededRandom: seededRandom,
  410. degToRad: degToRad,
  411. radToDeg: radToDeg,
  412. isPowerOfTwo: isPowerOfTwo,
  413. ceilPowerOfTwo: ceilPowerOfTwo,
  414. floorPowerOfTwo: floorPowerOfTwo,
  415. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  416. normalize: normalize,
  417. denormalize: denormalize$1
  418. });
  419. class Vector2 {
  420. constructor( x = 0, y = 0 ) {
  421. Vector2.prototype.isVector2 = true;
  422. this.x = x;
  423. this.y = y;
  424. }
  425. get width() {
  426. return this.x;
  427. }
  428. set width( value ) {
  429. this.x = value;
  430. }
  431. get height() {
  432. return this.y;
  433. }
  434. set height( value ) {
  435. this.y = value;
  436. }
  437. set( x, y ) {
  438. this.x = x;
  439. this.y = y;
  440. return this;
  441. }
  442. setScalar( scalar ) {
  443. this.x = scalar;
  444. this.y = scalar;
  445. return this;
  446. }
  447. setX( x ) {
  448. this.x = x;
  449. return this;
  450. }
  451. setY( y ) {
  452. this.y = y;
  453. return this;
  454. }
  455. setComponent( index, value ) {
  456. switch ( index ) {
  457. case 0: this.x = value; break;
  458. case 1: this.y = value; break;
  459. default: throw new Error( 'index is out of range: ' + index );
  460. }
  461. return this;
  462. }
  463. getComponent( index ) {
  464. switch ( index ) {
  465. case 0: return this.x;
  466. case 1: return this.y;
  467. default: throw new Error( 'index is out of range: ' + index );
  468. }
  469. }
  470. clone() {
  471. return new this.constructor( this.x, this.y );
  472. }
  473. copy( v ) {
  474. this.x = v.x;
  475. this.y = v.y;
  476. return this;
  477. }
  478. add( v ) {
  479. this.x += v.x;
  480. this.y += v.y;
  481. return this;
  482. }
  483. addScalar( s ) {
  484. this.x += s;
  485. this.y += s;
  486. return this;
  487. }
  488. addVectors( a, b ) {
  489. this.x = a.x + b.x;
  490. this.y = a.y + b.y;
  491. return this;
  492. }
  493. addScaledVector( v, s ) {
  494. this.x += v.x * s;
  495. this.y += v.y * s;
  496. return this;
  497. }
  498. sub( v ) {
  499. this.x -= v.x;
  500. this.y -= v.y;
  501. return this;
  502. }
  503. subScalar( s ) {
  504. this.x -= s;
  505. this.y -= s;
  506. return this;
  507. }
  508. subVectors( a, b ) {
  509. this.x = a.x - b.x;
  510. this.y = a.y - b.y;
  511. return this;
  512. }
  513. multiply( v ) {
  514. this.x *= v.x;
  515. this.y *= v.y;
  516. return this;
  517. }
  518. multiplyScalar( scalar ) {
  519. this.x *= scalar;
  520. this.y *= scalar;
  521. return this;
  522. }
  523. divide( v ) {
  524. this.x /= v.x;
  525. this.y /= v.y;
  526. return this;
  527. }
  528. divideScalar( scalar ) {
  529. return this.multiplyScalar( 1 / scalar );
  530. }
  531. applyMatrix3( m ) {
  532. const x = this.x, y = this.y;
  533. const e = m.elements;
  534. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  535. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  536. return this;
  537. }
  538. min( v ) {
  539. this.x = Math.min( this.x, v.x );
  540. this.y = Math.min( this.y, v.y );
  541. return this;
  542. }
  543. max( v ) {
  544. this.x = Math.max( this.x, v.x );
  545. this.y = Math.max( this.y, v.y );
  546. return this;
  547. }
  548. clamp( min, max ) {
  549. // assumes min < max, componentwise
  550. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  551. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  552. return this;
  553. }
  554. clampScalar( minVal, maxVal ) {
  555. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  556. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  557. return this;
  558. }
  559. clampLength( min, max ) {
  560. const length = this.length();
  561. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  562. }
  563. floor() {
  564. this.x = Math.floor( this.x );
  565. this.y = Math.floor( this.y );
  566. return this;
  567. }
  568. ceil() {
  569. this.x = Math.ceil( this.x );
  570. this.y = Math.ceil( this.y );
  571. return this;
  572. }
  573. round() {
  574. this.x = Math.round( this.x );
  575. this.y = Math.round( this.y );
  576. return this;
  577. }
  578. roundToZero() {
  579. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  580. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  581. return this;
  582. }
  583. negate() {
  584. this.x = - this.x;
  585. this.y = - this.y;
  586. return this;
  587. }
  588. dot( v ) {
  589. return this.x * v.x + this.y * v.y;
  590. }
  591. cross( v ) {
  592. return this.x * v.y - this.y * v.x;
  593. }
  594. lengthSq() {
  595. return this.x * this.x + this.y * this.y;
  596. }
  597. length() {
  598. return Math.sqrt( this.x * this.x + this.y * this.y );
  599. }
  600. manhattanLength() {
  601. return Math.abs( this.x ) + Math.abs( this.y );
  602. }
  603. normalize() {
  604. return this.divideScalar( this.length() || 1 );
  605. }
  606. angle() {
  607. // computes the angle in radians with respect to the positive x-axis
  608. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  609. return angle;
  610. }
  611. distanceTo( v ) {
  612. return Math.sqrt( this.distanceToSquared( v ) );
  613. }
  614. distanceToSquared( v ) {
  615. const dx = this.x - v.x, dy = this.y - v.y;
  616. return dx * dx + dy * dy;
  617. }
  618. manhattanDistanceTo( v ) {
  619. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  620. }
  621. setLength( length ) {
  622. return this.normalize().multiplyScalar( length );
  623. }
  624. lerp( v, alpha ) {
  625. this.x += ( v.x - this.x ) * alpha;
  626. this.y += ( v.y - this.y ) * alpha;
  627. return this;
  628. }
  629. lerpVectors( v1, v2, alpha ) {
  630. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  631. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  632. return this;
  633. }
  634. equals( v ) {
  635. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  636. }
  637. fromArray( array, offset = 0 ) {
  638. this.x = array[ offset ];
  639. this.y = array[ offset + 1 ];
  640. return this;
  641. }
  642. toArray( array = [], offset = 0 ) {
  643. array[ offset ] = this.x;
  644. array[ offset + 1 ] = this.y;
  645. return array;
  646. }
  647. fromBufferAttribute( attribute, index ) {
  648. this.x = attribute.getX( index );
  649. this.y = attribute.getY( index );
  650. return this;
  651. }
  652. rotateAround( center, angle ) {
  653. const c = Math.cos( angle ), s = Math.sin( angle );
  654. const x = this.x - center.x;
  655. const y = this.y - center.y;
  656. this.x = x * c - y * s + center.x;
  657. this.y = x * s + y * c + center.y;
  658. return this;
  659. }
  660. random() {
  661. this.x = Math.random();
  662. this.y = Math.random();
  663. return this;
  664. }
  665. *[ Symbol.iterator ]() {
  666. yield this.x;
  667. yield this.y;
  668. }
  669. }
  670. class Matrix3 {
  671. constructor() {
  672. Matrix3.prototype.isMatrix3 = true;
  673. this.elements = [
  674. 1, 0, 0,
  675. 0, 1, 0,
  676. 0, 0, 1
  677. ];
  678. }
  679. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  680. const te = this.elements;
  681. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  682. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  683. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  684. return this;
  685. }
  686. identity() {
  687. this.set(
  688. 1, 0, 0,
  689. 0, 1, 0,
  690. 0, 0, 1
  691. );
  692. return this;
  693. }
  694. copy( m ) {
  695. const te = this.elements;
  696. const me = m.elements;
  697. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  698. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  699. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  700. return this;
  701. }
  702. extractBasis( xAxis, yAxis, zAxis ) {
  703. xAxis.setFromMatrix3Column( this, 0 );
  704. yAxis.setFromMatrix3Column( this, 1 );
  705. zAxis.setFromMatrix3Column( this, 2 );
  706. return this;
  707. }
  708. setFromMatrix4( m ) {
  709. const me = m.elements;
  710. this.set(
  711. me[ 0 ], me[ 4 ], me[ 8 ],
  712. me[ 1 ], me[ 5 ], me[ 9 ],
  713. me[ 2 ], me[ 6 ], me[ 10 ]
  714. );
  715. return this;
  716. }
  717. multiply( m ) {
  718. return this.multiplyMatrices( this, m );
  719. }
  720. premultiply( m ) {
  721. return this.multiplyMatrices( m, this );
  722. }
  723. multiplyMatrices( a, b ) {
  724. const ae = a.elements;
  725. const be = b.elements;
  726. const te = this.elements;
  727. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  728. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  729. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  730. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  731. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  732. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  733. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  734. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  735. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  736. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  737. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  738. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  739. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  740. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  741. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  742. return this;
  743. }
  744. multiplyScalar( s ) {
  745. const te = this.elements;
  746. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  747. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  748. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  749. return this;
  750. }
  751. determinant() {
  752. const te = this.elements;
  753. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  754. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  755. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  756. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  757. }
  758. invert() {
  759. const te = this.elements,
  760. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  761. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  762. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  763. t11 = n33 * n22 - n32 * n23,
  764. t12 = n32 * n13 - n33 * n12,
  765. t13 = n23 * n12 - n22 * n13,
  766. det = n11 * t11 + n21 * t12 + n31 * t13;
  767. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  768. const detInv = 1 / det;
  769. te[ 0 ] = t11 * detInv;
  770. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  771. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  772. te[ 3 ] = t12 * detInv;
  773. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  774. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  775. te[ 6 ] = t13 * detInv;
  776. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  777. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  778. return this;
  779. }
  780. transpose() {
  781. let tmp;
  782. const m = this.elements;
  783. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  784. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  785. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  786. return this;
  787. }
  788. getNormalMatrix( matrix4 ) {
  789. return this.setFromMatrix4( matrix4 ).invert().transpose();
  790. }
  791. transposeIntoArray( r ) {
  792. const m = this.elements;
  793. r[ 0 ] = m[ 0 ];
  794. r[ 1 ] = m[ 3 ];
  795. r[ 2 ] = m[ 6 ];
  796. r[ 3 ] = m[ 1 ];
  797. r[ 4 ] = m[ 4 ];
  798. r[ 5 ] = m[ 7 ];
  799. r[ 6 ] = m[ 2 ];
  800. r[ 7 ] = m[ 5 ];
  801. r[ 8 ] = m[ 8 ];
  802. return this;
  803. }
  804. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  805. const c = Math.cos( rotation );
  806. const s = Math.sin( rotation );
  807. this.set(
  808. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  809. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  810. 0, 0, 1
  811. );
  812. return this;
  813. }
  814. scale( sx, sy ) {
  815. const te = this.elements;
  816. te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
  817. te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;
  818. return this;
  819. }
  820. rotate( theta ) {
  821. const c = Math.cos( theta );
  822. const s = Math.sin( theta );
  823. const te = this.elements;
  824. const a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
  825. const a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];
  826. te[ 0 ] = c * a11 + s * a21;
  827. te[ 3 ] = c * a12 + s * a22;
  828. te[ 6 ] = c * a13 + s * a23;
  829. te[ 1 ] = - s * a11 + c * a21;
  830. te[ 4 ] = - s * a12 + c * a22;
  831. te[ 7 ] = - s * a13 + c * a23;
  832. return this;
  833. }
  834. translate( tx, ty ) {
  835. const te = this.elements;
  836. te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
  837. te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];
  838. return this;
  839. }
  840. equals( matrix ) {
  841. const te = this.elements;
  842. const me = matrix.elements;
  843. for ( let i = 0; i < 9; i ++ ) {
  844. if ( te[ i ] !== me[ i ] ) return false;
  845. }
  846. return true;
  847. }
  848. fromArray( array, offset = 0 ) {
  849. for ( let i = 0; i < 9; i ++ ) {
  850. this.elements[ i ] = array[ i + offset ];
  851. }
  852. return this;
  853. }
  854. toArray( array = [], offset = 0 ) {
  855. const te = this.elements;
  856. array[ offset ] = te[ 0 ];
  857. array[ offset + 1 ] = te[ 1 ];
  858. array[ offset + 2 ] = te[ 2 ];
  859. array[ offset + 3 ] = te[ 3 ];
  860. array[ offset + 4 ] = te[ 4 ];
  861. array[ offset + 5 ] = te[ 5 ];
  862. array[ offset + 6 ] = te[ 6 ];
  863. array[ offset + 7 ] = te[ 7 ];
  864. array[ offset + 8 ] = te[ 8 ];
  865. return array;
  866. }
  867. clone() {
  868. return new this.constructor().fromArray( this.elements );
  869. }
  870. }
  871. function arrayNeedsUint32( array ) {
  872. // assumes larger values usually on last
  873. for ( let i = array.length - 1; i >= 0; -- i ) {
  874. if ( array[ i ] > 65535 ) return true;
  875. }
  876. return false;
  877. }
  878. const TYPED_ARRAYS = {
  879. Int8Array: Int8Array,
  880. Uint8Array: Uint8Array,
  881. Uint8ClampedArray: Uint8ClampedArray,
  882. Int16Array: Int16Array,
  883. Uint16Array: Uint16Array,
  884. Int32Array: Int32Array,
  885. Uint32Array: Uint32Array,
  886. Float32Array: Float32Array,
  887. Float64Array: Float64Array
  888. };
  889. function getTypedArray( type, buffer ) {
  890. return new TYPED_ARRAYS[ type ]( buffer );
  891. }
  892. function createElementNS( name ) {
  893. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  894. }
  895. function SRGBToLinear( c ) {
  896. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  897. }
  898. function LinearToSRGB( c ) {
  899. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  900. }
  901. // JavaScript RGB-to-RGB transforms, defined as
  902. // FN[InputColorSpace][OutputColorSpace] callback functions.
  903. const FN = {
  904. [ SRGBColorSpace ]: { [ LinearSRGBColorSpace ]: SRGBToLinear },
  905. [ LinearSRGBColorSpace ]: { [ SRGBColorSpace ]: LinearToSRGB },
  906. };
  907. const ColorManagement = {
  908. legacyMode: true,
  909. get workingColorSpace() {
  910. return LinearSRGBColorSpace;
  911. },
  912. set workingColorSpace( colorSpace ) {
  913. console.warn( 'THREE.ColorManagement: .workingColorSpace is readonly.' );
  914. },
  915. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  916. if ( this.legacyMode || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  917. return color;
  918. }
  919. if ( FN[ sourceColorSpace ] && FN[ sourceColorSpace ][ targetColorSpace ] !== undefined ) {
  920. const fn = FN[ sourceColorSpace ][ targetColorSpace ];
  921. color.r = fn( color.r );
  922. color.g = fn( color.g );
  923. color.b = fn( color.b );
  924. return color;
  925. }
  926. throw new Error( 'Unsupported color space conversion.' );
  927. },
  928. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  929. return this.convert( color, this.workingColorSpace, targetColorSpace );
  930. },
  931. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  932. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  933. },
  934. };
  935. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  936. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  937. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  938. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  939. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  940. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  941. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  942. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  943. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  944. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  945. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  946. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  947. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  948. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  949. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  950. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  951. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  952. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  953. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  954. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  955. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  956. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  957. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  958. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  959. const _rgb = { r: 0, g: 0, b: 0 };
  960. const _hslA = { h: 0, s: 0, l: 0 };
  961. const _hslB = { h: 0, s: 0, l: 0 };
  962. function hue2rgb( p, q, t ) {
  963. if ( t < 0 ) t += 1;
  964. if ( t > 1 ) t -= 1;
  965. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  966. if ( t < 1 / 2 ) return q;
  967. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  968. return p;
  969. }
  970. function toComponents( source, target ) {
  971. target.r = source.r;
  972. target.g = source.g;
  973. target.b = source.b;
  974. return target;
  975. }
  976. class Color {
  977. constructor( r, g, b ) {
  978. this.isColor = true;
  979. this.r = 1;
  980. this.g = 1;
  981. this.b = 1;
  982. if ( g === undefined && b === undefined ) {
  983. // r is THREE.Color, hex or string
  984. return this.set( r );
  985. }
  986. return this.setRGB( r, g, b );
  987. }
  988. set( value ) {
  989. if ( value && value.isColor ) {
  990. this.copy( value );
  991. } else if ( typeof value === 'number' ) {
  992. this.setHex( value );
  993. } else if ( typeof value === 'string' ) {
  994. this.setStyle( value );
  995. }
  996. return this;
  997. }
  998. setScalar( scalar ) {
  999. this.r = scalar;
  1000. this.g = scalar;
  1001. this.b = scalar;
  1002. return this;
  1003. }
  1004. setHex( hex, colorSpace = SRGBColorSpace ) {
  1005. hex = Math.floor( hex );
  1006. this.r = ( hex >> 16 & 255 ) / 255;
  1007. this.g = ( hex >> 8 & 255 ) / 255;
  1008. this.b = ( hex & 255 ) / 255;
  1009. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1010. return this;
  1011. }
  1012. setRGB( r, g, b, colorSpace = LinearSRGBColorSpace ) {
  1013. this.r = r;
  1014. this.g = g;
  1015. this.b = b;
  1016. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1017. return this;
  1018. }
  1019. setHSL( h, s, l, colorSpace = LinearSRGBColorSpace ) {
  1020. // h,s,l ranges are in 0.0 - 1.0
  1021. h = euclideanModulo( h, 1 );
  1022. s = clamp( s, 0, 1 );
  1023. l = clamp( l, 0, 1 );
  1024. if ( s === 0 ) {
  1025. this.r = this.g = this.b = l;
  1026. } else {
  1027. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  1028. const q = ( 2 * l ) - p;
  1029. this.r = hue2rgb( q, p, h + 1 / 3 );
  1030. this.g = hue2rgb( q, p, h );
  1031. this.b = hue2rgb( q, p, h - 1 / 3 );
  1032. }
  1033. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1034. return this;
  1035. }
  1036. setStyle( style, colorSpace = SRGBColorSpace ) {
  1037. function handleAlpha( string ) {
  1038. if ( string === undefined ) return;
  1039. if ( parseFloat( string ) < 1 ) {
  1040. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  1041. }
  1042. }
  1043. let m;
  1044. if ( m = /^((?:rgb|hsl)a?)\(([^\)]*)\)/.exec( style ) ) {
  1045. // rgb / hsl
  1046. let color;
  1047. const name = m[ 1 ];
  1048. const components = m[ 2 ];
  1049. switch ( name ) {
  1050. case 'rgb':
  1051. case 'rgba':
  1052. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  1053. // rgb(255,0,0) rgba(255,0,0,0.5)
  1054. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  1055. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  1056. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  1057. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1058. handleAlpha( color[ 4 ] );
  1059. return this;
  1060. }
  1061. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  1062. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  1063. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  1064. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  1065. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  1066. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1067. handleAlpha( color[ 4 ] );
  1068. return this;
  1069. }
  1070. break;
  1071. case 'hsl':
  1072. case 'hsla':
  1073. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  1074. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  1075. const h = parseFloat( color[ 1 ] ) / 360;
  1076. const s = parseFloat( color[ 2 ] ) / 100;
  1077. const l = parseFloat( color[ 3 ] ) / 100;
  1078. handleAlpha( color[ 4 ] );
  1079. return this.setHSL( h, s, l, colorSpace );
  1080. }
  1081. break;
  1082. }
  1083. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  1084. // hex color
  1085. const hex = m[ 1 ];
  1086. const size = hex.length;
  1087. if ( size === 3 ) {
  1088. // #ff0
  1089. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  1090. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  1091. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  1092. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1093. return this;
  1094. } else if ( size === 6 ) {
  1095. // #ff0000
  1096. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  1097. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  1098. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  1099. ColorManagement.toWorkingColorSpace( this, colorSpace );
  1100. return this;
  1101. }
  1102. }
  1103. if ( style && style.length > 0 ) {
  1104. return this.setColorName( style, colorSpace );
  1105. }
  1106. return this;
  1107. }
  1108. setColorName( style, colorSpace = SRGBColorSpace ) {
  1109. // color keywords
  1110. const hex = _colorKeywords[ style.toLowerCase() ];
  1111. if ( hex !== undefined ) {
  1112. // red
  1113. this.setHex( hex, colorSpace );
  1114. } else {
  1115. // unknown color
  1116. console.warn( 'THREE.Color: Unknown color ' + style );
  1117. }
  1118. return this;
  1119. }
  1120. clone() {
  1121. return new this.constructor( this.r, this.g, this.b );
  1122. }
  1123. copy( color ) {
  1124. this.r = color.r;
  1125. this.g = color.g;
  1126. this.b = color.b;
  1127. return this;
  1128. }
  1129. copySRGBToLinear( color ) {
  1130. this.r = SRGBToLinear( color.r );
  1131. this.g = SRGBToLinear( color.g );
  1132. this.b = SRGBToLinear( color.b );
  1133. return this;
  1134. }
  1135. copyLinearToSRGB( color ) {
  1136. this.r = LinearToSRGB( color.r );
  1137. this.g = LinearToSRGB( color.g );
  1138. this.b = LinearToSRGB( color.b );
  1139. return this;
  1140. }
  1141. convertSRGBToLinear() {
  1142. this.copySRGBToLinear( this );
  1143. return this;
  1144. }
  1145. convertLinearToSRGB() {
  1146. this.copyLinearToSRGB( this );
  1147. return this;
  1148. }
  1149. getHex( colorSpace = SRGBColorSpace ) {
  1150. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb ), colorSpace );
  1151. return clamp( _rgb.r * 255, 0, 255 ) << 16 ^ clamp( _rgb.g * 255, 0, 255 ) << 8 ^ clamp( _rgb.b * 255, 0, 255 ) << 0;
  1152. }
  1153. getHexString( colorSpace = SRGBColorSpace ) {
  1154. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( - 6 );
  1155. }
  1156. getHSL( target, colorSpace = LinearSRGBColorSpace ) {
  1157. // h,s,l ranges are in 0.0 - 1.0
  1158. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb ), colorSpace );
  1159. const r = _rgb.r, g = _rgb.g, b = _rgb.b;
  1160. const max = Math.max( r, g, b );
  1161. const min = Math.min( r, g, b );
  1162. let hue, saturation;
  1163. const lightness = ( min + max ) / 2.0;
  1164. if ( min === max ) {
  1165. hue = 0;
  1166. saturation = 0;
  1167. } else {
  1168. const delta = max - min;
  1169. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  1170. switch ( max ) {
  1171. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  1172. case g: hue = ( b - r ) / delta + 2; break;
  1173. case b: hue = ( r - g ) / delta + 4; break;
  1174. }
  1175. hue /= 6;
  1176. }
  1177. target.h = hue;
  1178. target.s = saturation;
  1179. target.l = lightness;
  1180. return target;
  1181. }
  1182. getRGB( target, colorSpace = LinearSRGBColorSpace ) {
  1183. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb ), colorSpace );
  1184. target.r = _rgb.r;
  1185. target.g = _rgb.g;
  1186. target.b = _rgb.b;
  1187. return target;
  1188. }
  1189. getStyle( colorSpace = SRGBColorSpace ) {
  1190. ColorManagement.fromWorkingColorSpace( toComponents( this, _rgb ), colorSpace );
  1191. if ( colorSpace !== SRGBColorSpace ) {
  1192. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  1193. return `color(${ colorSpace } ${ _rgb.r } ${ _rgb.g } ${ _rgb.b })`;
  1194. }
  1195. return `rgb(${( _rgb.r * 255 ) | 0},${( _rgb.g * 255 ) | 0},${( _rgb.b * 255 ) | 0})`;
  1196. }
  1197. offsetHSL( h, s, l ) {
  1198. this.getHSL( _hslA );
  1199. _hslA.h += h; _hslA.s += s; _hslA.l += l;
  1200. this.setHSL( _hslA.h, _hslA.s, _hslA.l );
  1201. return this;
  1202. }
  1203. add( color ) {
  1204. this.r += color.r;
  1205. this.g += color.g;
  1206. this.b += color.b;
  1207. return this;
  1208. }
  1209. addColors( color1, color2 ) {
  1210. this.r = color1.r + color2.r;
  1211. this.g = color1.g + color2.g;
  1212. this.b = color1.b + color2.b;
  1213. return this;
  1214. }
  1215. addScalar( s ) {
  1216. this.r += s;
  1217. this.g += s;
  1218. this.b += s;
  1219. return this;
  1220. }
  1221. sub( color ) {
  1222. this.r = Math.max( 0, this.r - color.r );
  1223. this.g = Math.max( 0, this.g - color.g );
  1224. this.b = Math.max( 0, this.b - color.b );
  1225. return this;
  1226. }
  1227. multiply( color ) {
  1228. this.r *= color.r;
  1229. this.g *= color.g;
  1230. this.b *= color.b;
  1231. return this;
  1232. }
  1233. multiplyScalar( s ) {
  1234. this.r *= s;
  1235. this.g *= s;
  1236. this.b *= s;
  1237. return this;
  1238. }
  1239. lerp( color, alpha ) {
  1240. this.r += ( color.r - this.r ) * alpha;
  1241. this.g += ( color.g - this.g ) * alpha;
  1242. this.b += ( color.b - this.b ) * alpha;
  1243. return this;
  1244. }
  1245. lerpColors( color1, color2, alpha ) {
  1246. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  1247. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  1248. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  1249. return this;
  1250. }
  1251. lerpHSL( color, alpha ) {
  1252. this.getHSL( _hslA );
  1253. color.getHSL( _hslB );
  1254. const h = lerp( _hslA.h, _hslB.h, alpha );
  1255. const s = lerp( _hslA.s, _hslB.s, alpha );
  1256. const l = lerp( _hslA.l, _hslB.l, alpha );
  1257. this.setHSL( h, s, l );
  1258. return this;
  1259. }
  1260. equals( c ) {
  1261. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  1262. }
  1263. fromArray( array, offset = 0 ) {
  1264. this.r = array[ offset ];
  1265. this.g = array[ offset + 1 ];
  1266. this.b = array[ offset + 2 ];
  1267. return this;
  1268. }
  1269. toArray( array = [], offset = 0 ) {
  1270. array[ offset ] = this.r;
  1271. array[ offset + 1 ] = this.g;
  1272. array[ offset + 2 ] = this.b;
  1273. return array;
  1274. }
  1275. fromBufferAttribute( attribute, index ) {
  1276. this.r = attribute.getX( index );
  1277. this.g = attribute.getY( index );
  1278. this.b = attribute.getZ( index );
  1279. if ( attribute.normalized === true ) {
  1280. // assuming Uint8Array
  1281. this.r /= 255;
  1282. this.g /= 255;
  1283. this.b /= 255;
  1284. }
  1285. return this;
  1286. }
  1287. toJSON() {
  1288. return this.getHex();
  1289. }
  1290. *[ Symbol.iterator ]() {
  1291. yield this.r;
  1292. yield this.g;
  1293. yield this.b;
  1294. }
  1295. }
  1296. Color.NAMES = _colorKeywords;
  1297. let _canvas;
  1298. class ImageUtils {
  1299. static getDataURL( image ) {
  1300. if ( /^data:/i.test( image.src ) ) {
  1301. return image.src;
  1302. }
  1303. if ( typeof HTMLCanvasElement == 'undefined' ) {
  1304. return image.src;
  1305. }
  1306. let canvas;
  1307. if ( image instanceof HTMLCanvasElement ) {
  1308. canvas = image;
  1309. } else {
  1310. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  1311. _canvas.width = image.width;
  1312. _canvas.height = image.height;
  1313. const context = _canvas.getContext( '2d' );
  1314. if ( image instanceof ImageData ) {
  1315. context.putImageData( image, 0, 0 );
  1316. } else {
  1317. context.drawImage( image, 0, 0, image.width, image.height );
  1318. }
  1319. canvas = _canvas;
  1320. }
  1321. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  1322. console.warn( 'THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons', image );
  1323. return canvas.toDataURL( 'image/jpeg', 0.6 );
  1324. } else {
  1325. return canvas.toDataURL( 'image/png' );
  1326. }
  1327. }
  1328. static sRGBToLinear( image ) {
  1329. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1330. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1331. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1332. const canvas = createElementNS( 'canvas' );
  1333. canvas.width = image.width;
  1334. canvas.height = image.height;
  1335. const context = canvas.getContext( '2d' );
  1336. context.drawImage( image, 0, 0, image.width, image.height );
  1337. const imageData = context.getImageData( 0, 0, image.width, image.height );
  1338. const data = imageData.data;
  1339. for ( let i = 0; i < data.length; i ++ ) {
  1340. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  1341. }
  1342. context.putImageData( imageData, 0, 0 );
  1343. return canvas;
  1344. } else if ( image.data ) {
  1345. const data = image.data.slice( 0 );
  1346. for ( let i = 0; i < data.length; i ++ ) {
  1347. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  1348. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  1349. } else {
  1350. // assuming float
  1351. data[ i ] = SRGBToLinear( data[ i ] );
  1352. }
  1353. }
  1354. return {
  1355. data: data,
  1356. width: image.width,
  1357. height: image.height
  1358. };
  1359. } else {
  1360. console.warn( 'THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  1361. return image;
  1362. }
  1363. }
  1364. }
  1365. class Source {
  1366. constructor( data = null ) {
  1367. this.isSource = true;
  1368. this.uuid = generateUUID();
  1369. this.data = data;
  1370. this.version = 0;
  1371. }
  1372. set needsUpdate( value ) {
  1373. if ( value === true ) this.version ++;
  1374. }
  1375. toJSON( meta ) {
  1376. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1377. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  1378. return meta.images[ this.uuid ];
  1379. }
  1380. const output = {
  1381. uuid: this.uuid,
  1382. url: ''
  1383. };
  1384. const data = this.data;
  1385. if ( data !== null ) {
  1386. let url;
  1387. if ( Array.isArray( data ) ) {
  1388. // cube texture
  1389. url = [];
  1390. for ( let i = 0, l = data.length; i < l; i ++ ) {
  1391. if ( data[ i ].isDataTexture ) {
  1392. url.push( serializeImage( data[ i ].image ) );
  1393. } else {
  1394. url.push( serializeImage( data[ i ] ) );
  1395. }
  1396. }
  1397. } else {
  1398. // texture
  1399. url = serializeImage( data );
  1400. }
  1401. output.url = url;
  1402. }
  1403. if ( ! isRootObject ) {
  1404. meta.images[ this.uuid ] = output;
  1405. }
  1406. return output;
  1407. }
  1408. }
  1409. function serializeImage( image ) {
  1410. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  1411. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  1412. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  1413. // default images
  1414. return ImageUtils.getDataURL( image );
  1415. } else {
  1416. if ( image.data ) {
  1417. // images of DataTexture
  1418. return {
  1419. data: Array.from( image.data ),
  1420. width: image.width,
  1421. height: image.height,
  1422. type: image.data.constructor.name
  1423. };
  1424. } else {
  1425. console.warn( 'THREE.Texture: Unable to serialize Texture.' );
  1426. return {};
  1427. }
  1428. }
  1429. }
  1430. let textureId = 0;
  1431. class Texture extends EventDispatcher {
  1432. constructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = 1, encoding = LinearEncoding ) {
  1433. super();
  1434. this.isTexture = true;
  1435. Object.defineProperty( this, 'id', { value: textureId ++ } );
  1436. this.uuid = generateUUID();
  1437. this.name = '';
  1438. this.source = new Source( image );
  1439. this.mipmaps = [];
  1440. this.mapping = mapping;
  1441. this.wrapS = wrapS;
  1442. this.wrapT = wrapT;
  1443. this.magFilter = magFilter;
  1444. this.minFilter = minFilter;
  1445. this.anisotropy = anisotropy;
  1446. this.format = format;
  1447. this.internalFormat = null;
  1448. this.type = type;
  1449. this.offset = new Vector2( 0, 0 );
  1450. this.repeat = new Vector2( 1, 1 );
  1451. this.center = new Vector2( 0, 0 );
  1452. this.rotation = 0;
  1453. this.matrixAutoUpdate = true;
  1454. this.matrix = new Matrix3();
  1455. this.generateMipmaps = true;
  1456. this.premultiplyAlpha = false;
  1457. this.flipY = true;
  1458. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  1459. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  1460. //
  1461. // Also changing the encoding after already used by a Material will not automatically make the Material
  1462. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  1463. this.encoding = encoding;
  1464. this.userData = {};
  1465. this.version = 0;
  1466. this.onUpdate = null;
  1467. this.isRenderTargetTexture = false; // indicates whether a texture belongs to a render target or not
  1468. this.needsPMREMUpdate = false; // indicates whether this texture should be processed by PMREMGenerator or not (only relevant for render target textures)
  1469. }
  1470. get image() {
  1471. return this.source.data;
  1472. }
  1473. set image( value ) {
  1474. this.source.data = value;
  1475. }
  1476. updateMatrix() {
  1477. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  1478. }
  1479. clone() {
  1480. return new this.constructor().copy( this );
  1481. }
  1482. copy( source ) {
  1483. this.name = source.name;
  1484. this.source = source.source;
  1485. this.mipmaps = source.mipmaps.slice( 0 );
  1486. this.mapping = source.mapping;
  1487. this.wrapS = source.wrapS;
  1488. this.wrapT = source.wrapT;
  1489. this.magFilter = source.magFilter;
  1490. this.minFilter = source.minFilter;
  1491. this.anisotropy = source.anisotropy;
  1492. this.format = source.format;
  1493. this.internalFormat = source.internalFormat;
  1494. this.type = source.type;
  1495. this.offset.copy( source.offset );
  1496. this.repeat.copy( source.repeat );
  1497. this.center.copy( source.center );
  1498. this.rotation = source.rotation;
  1499. this.matrixAutoUpdate = source.matrixAutoUpdate;
  1500. this.matrix.copy( source.matrix );
  1501. this.generateMipmaps = source.generateMipmaps;
  1502. this.premultiplyAlpha = source.premultiplyAlpha;
  1503. this.flipY = source.flipY;
  1504. this.unpackAlignment = source.unpackAlignment;
  1505. this.encoding = source.encoding;
  1506. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  1507. this.needsUpdate = true;
  1508. return this;
  1509. }
  1510. toJSON( meta ) {
  1511. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  1512. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  1513. return meta.textures[ this.uuid ];
  1514. }
  1515. const output = {
  1516. metadata: {
  1517. version: 4.5,
  1518. type: 'Texture',
  1519. generator: 'Texture.toJSON'
  1520. },
  1521. uuid: this.uuid,
  1522. name: this.name,
  1523. image: this.source.toJSON( meta ).uuid,
  1524. mapping: this.mapping,
  1525. repeat: [ this.repeat.x, this.repeat.y ],
  1526. offset: [ this.offset.x, this.offset.y ],
  1527. center: [ this.center.x, this.center.y ],
  1528. rotation: this.rotation,
  1529. wrap: [ this.wrapS, this.wrapT ],
  1530. format: this.format,
  1531. type: this.type,
  1532. encoding: this.encoding,
  1533. minFilter: this.minFilter,
  1534. magFilter: this.magFilter,
  1535. anisotropy: this.anisotropy,
  1536. flipY: this.flipY,
  1537. premultiplyAlpha: this.premultiplyAlpha,
  1538. unpackAlignment: this.unpackAlignment
  1539. };
  1540. if ( JSON.stringify( this.userData ) !== '{}' ) output.userData = this.userData;
  1541. if ( ! isRootObject ) {
  1542. meta.textures[ this.uuid ] = output;
  1543. }
  1544. return output;
  1545. }
  1546. dispose() {
  1547. this.dispatchEvent( { type: 'dispose' } );
  1548. }
  1549. transformUv( uv ) {
  1550. if ( this.mapping !== UVMapping ) return uv;
  1551. uv.applyMatrix3( this.matrix );
  1552. if ( uv.x < 0 || uv.x > 1 ) {
  1553. switch ( this.wrapS ) {
  1554. case RepeatWrapping:
  1555. uv.x = uv.x - Math.floor( uv.x );
  1556. break;
  1557. case ClampToEdgeWrapping:
  1558. uv.x = uv.x < 0 ? 0 : 1;
  1559. break;
  1560. case MirroredRepeatWrapping:
  1561. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  1562. uv.x = Math.ceil( uv.x ) - uv.x;
  1563. } else {
  1564. uv.x = uv.x - Math.floor( uv.x );
  1565. }
  1566. break;
  1567. }
  1568. }
  1569. if ( uv.y < 0 || uv.y > 1 ) {
  1570. switch ( this.wrapT ) {
  1571. case RepeatWrapping:
  1572. uv.y = uv.y - Math.floor( uv.y );
  1573. break;
  1574. case ClampToEdgeWrapping:
  1575. uv.y = uv.y < 0 ? 0 : 1;
  1576. break;
  1577. case MirroredRepeatWrapping:
  1578. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  1579. uv.y = Math.ceil( uv.y ) - uv.y;
  1580. } else {
  1581. uv.y = uv.y - Math.floor( uv.y );
  1582. }
  1583. break;
  1584. }
  1585. }
  1586. if ( this.flipY ) {
  1587. uv.y = 1 - uv.y;
  1588. }
  1589. return uv;
  1590. }
  1591. set needsUpdate( value ) {
  1592. if ( value === true ) {
  1593. this.version ++;
  1594. this.source.needsUpdate = true;
  1595. }
  1596. }
  1597. }
  1598. Texture.DEFAULT_IMAGE = null;
  1599. Texture.DEFAULT_MAPPING = UVMapping;
  1600. class Vector4 {
  1601. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  1602. Vector4.prototype.isVector4 = true;
  1603. this.x = x;
  1604. this.y = y;
  1605. this.z = z;
  1606. this.w = w;
  1607. }
  1608. get width() {
  1609. return this.z;
  1610. }
  1611. set width( value ) {
  1612. this.z = value;
  1613. }
  1614. get height() {
  1615. return this.w;
  1616. }
  1617. set height( value ) {
  1618. this.w = value;
  1619. }
  1620. set( x, y, z, w ) {
  1621. this.x = x;
  1622. this.y = y;
  1623. this.z = z;
  1624. this.w = w;
  1625. return this;
  1626. }
  1627. setScalar( scalar ) {
  1628. this.x = scalar;
  1629. this.y = scalar;
  1630. this.z = scalar;
  1631. this.w = scalar;
  1632. return this;
  1633. }
  1634. setX( x ) {
  1635. this.x = x;
  1636. return this;
  1637. }
  1638. setY( y ) {
  1639. this.y = y;
  1640. return this;
  1641. }
  1642. setZ( z ) {
  1643. this.z = z;
  1644. return this;
  1645. }
  1646. setW( w ) {
  1647. this.w = w;
  1648. return this;
  1649. }
  1650. setComponent( index, value ) {
  1651. switch ( index ) {
  1652. case 0: this.x = value; break;
  1653. case 1: this.y = value; break;
  1654. case 2: this.z = value; break;
  1655. case 3: this.w = value; break;
  1656. default: throw new Error( 'index is out of range: ' + index );
  1657. }
  1658. return this;
  1659. }
  1660. getComponent( index ) {
  1661. switch ( index ) {
  1662. case 0: return this.x;
  1663. case 1: return this.y;
  1664. case 2: return this.z;
  1665. case 3: return this.w;
  1666. default: throw new Error( 'index is out of range: ' + index );
  1667. }
  1668. }
  1669. clone() {
  1670. return new this.constructor( this.x, this.y, this.z, this.w );
  1671. }
  1672. copy( v ) {
  1673. this.x = v.x;
  1674. this.y = v.y;
  1675. this.z = v.z;
  1676. this.w = ( v.w !== undefined ) ? v.w : 1;
  1677. return this;
  1678. }
  1679. add( v ) {
  1680. this.x += v.x;
  1681. this.y += v.y;
  1682. this.z += v.z;
  1683. this.w += v.w;
  1684. return this;
  1685. }
  1686. addScalar( s ) {
  1687. this.x += s;
  1688. this.y += s;
  1689. this.z += s;
  1690. this.w += s;
  1691. return this;
  1692. }
  1693. addVectors( a, b ) {
  1694. this.x = a.x + b.x;
  1695. this.y = a.y + b.y;
  1696. this.z = a.z + b.z;
  1697. this.w = a.w + b.w;
  1698. return this;
  1699. }
  1700. addScaledVector( v, s ) {
  1701. this.x += v.x * s;
  1702. this.y += v.y * s;
  1703. this.z += v.z * s;
  1704. this.w += v.w * s;
  1705. return this;
  1706. }
  1707. sub( v ) {
  1708. this.x -= v.x;
  1709. this.y -= v.y;
  1710. this.z -= v.z;
  1711. this.w -= v.w;
  1712. return this;
  1713. }
  1714. subScalar( s ) {
  1715. this.x -= s;
  1716. this.y -= s;
  1717. this.z -= s;
  1718. this.w -= s;
  1719. return this;
  1720. }
  1721. subVectors( a, b ) {
  1722. this.x = a.x - b.x;
  1723. this.y = a.y - b.y;
  1724. this.z = a.z - b.z;
  1725. this.w = a.w - b.w;
  1726. return this;
  1727. }
  1728. multiply( v ) {
  1729. this.x *= v.x;
  1730. this.y *= v.y;
  1731. this.z *= v.z;
  1732. this.w *= v.w;
  1733. return this;
  1734. }
  1735. multiplyScalar( scalar ) {
  1736. this.x *= scalar;
  1737. this.y *= scalar;
  1738. this.z *= scalar;
  1739. this.w *= scalar;
  1740. return this;
  1741. }
  1742. applyMatrix4( m ) {
  1743. const x = this.x, y = this.y, z = this.z, w = this.w;
  1744. const e = m.elements;
  1745. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1746. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1747. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1748. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1749. return this;
  1750. }
  1751. divideScalar( scalar ) {
  1752. return this.multiplyScalar( 1 / scalar );
  1753. }
  1754. setAxisAngleFromQuaternion( q ) {
  1755. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1756. // q is assumed to be normalized
  1757. this.w = 2 * Math.acos( q.w );
  1758. const s = Math.sqrt( 1 - q.w * q.w );
  1759. if ( s < 0.0001 ) {
  1760. this.x = 1;
  1761. this.y = 0;
  1762. this.z = 0;
  1763. } else {
  1764. this.x = q.x / s;
  1765. this.y = q.y / s;
  1766. this.z = q.z / s;
  1767. }
  1768. return this;
  1769. }
  1770. setAxisAngleFromRotationMatrix( m ) {
  1771. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1772. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1773. let angle, x, y, z; // variables for result
  1774. const epsilon = 0.01, // margin to allow for rounding errors
  1775. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1776. te = m.elements,
  1777. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1778. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1779. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1780. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1781. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1782. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1783. // singularity found
  1784. // first check for identity matrix which must have +1 for all terms
  1785. // in leading diagonal and zero in other terms
  1786. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1787. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1788. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1789. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1790. // this singularity is identity matrix so angle = 0
  1791. this.set( 1, 0, 0, 0 );
  1792. return this; // zero angle, arbitrary axis
  1793. }
  1794. // otherwise this singularity is angle = 180
  1795. angle = Math.PI;
  1796. const xx = ( m11 + 1 ) / 2;
  1797. const yy = ( m22 + 1 ) / 2;
  1798. const zz = ( m33 + 1 ) / 2;
  1799. const xy = ( m12 + m21 ) / 4;
  1800. const xz = ( m13 + m31 ) / 4;
  1801. const yz = ( m23 + m32 ) / 4;
  1802. if ( ( xx > yy ) && ( xx > zz ) ) {
  1803. // m11 is the largest diagonal term
  1804. if ( xx < epsilon ) {
  1805. x = 0;
  1806. y = 0.707106781;
  1807. z = 0.707106781;
  1808. } else {
  1809. x = Math.sqrt( xx );
  1810. y = xy / x;
  1811. z = xz / x;
  1812. }
  1813. } else if ( yy > zz ) {
  1814. // m22 is the largest diagonal term
  1815. if ( yy < epsilon ) {
  1816. x = 0.707106781;
  1817. y = 0;
  1818. z = 0.707106781;
  1819. } else {
  1820. y = Math.sqrt( yy );
  1821. x = xy / y;
  1822. z = yz / y;
  1823. }
  1824. } else {
  1825. // m33 is the largest diagonal term so base result on this
  1826. if ( zz < epsilon ) {
  1827. x = 0.707106781;
  1828. y = 0.707106781;
  1829. z = 0;
  1830. } else {
  1831. z = Math.sqrt( zz );
  1832. x = xz / z;
  1833. y = yz / z;
  1834. }
  1835. }
  1836. this.set( x, y, z, angle );
  1837. return this; // return 180 deg rotation
  1838. }
  1839. // as we have reached here there are no singularities so we can handle normally
  1840. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1841. ( m13 - m31 ) * ( m13 - m31 ) +
  1842. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1843. if ( Math.abs( s ) < 0.001 ) s = 1;
  1844. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1845. // caught by singularity test above, but I've left it in just in case
  1846. this.x = ( m32 - m23 ) / s;
  1847. this.y = ( m13 - m31 ) / s;
  1848. this.z = ( m21 - m12 ) / s;
  1849. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1850. return this;
  1851. }
  1852. min( v ) {
  1853. this.x = Math.min( this.x, v.x );
  1854. this.y = Math.min( this.y, v.y );
  1855. this.z = Math.min( this.z, v.z );
  1856. this.w = Math.min( this.w, v.w );
  1857. return this;
  1858. }
  1859. max( v ) {
  1860. this.x = Math.max( this.x, v.x );
  1861. this.y = Math.max( this.y, v.y );
  1862. this.z = Math.max( this.z, v.z );
  1863. this.w = Math.max( this.w, v.w );
  1864. return this;
  1865. }
  1866. clamp( min, max ) {
  1867. // assumes min < max, componentwise
  1868. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1869. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1870. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1871. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1872. return this;
  1873. }
  1874. clampScalar( minVal, maxVal ) {
  1875. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  1876. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  1877. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  1878. this.w = Math.max( minVal, Math.min( maxVal, this.w ) );
  1879. return this;
  1880. }
  1881. clampLength( min, max ) {
  1882. const length = this.length();
  1883. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  1884. }
  1885. floor() {
  1886. this.x = Math.floor( this.x );
  1887. this.y = Math.floor( this.y );
  1888. this.z = Math.floor( this.z );
  1889. this.w = Math.floor( this.w );
  1890. return this;
  1891. }
  1892. ceil() {
  1893. this.x = Math.ceil( this.x );
  1894. this.y = Math.ceil( this.y );
  1895. this.z = Math.ceil( this.z );
  1896. this.w = Math.ceil( this.w );
  1897. return this;
  1898. }
  1899. round() {
  1900. this.x = Math.round( this.x );
  1901. this.y = Math.round( this.y );
  1902. this.z = Math.round( this.z );
  1903. this.w = Math.round( this.w );
  1904. return this;
  1905. }
  1906. roundToZero() {
  1907. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1908. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1909. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1910. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1911. return this;
  1912. }
  1913. negate() {
  1914. this.x = - this.x;
  1915. this.y = - this.y;
  1916. this.z = - this.z;
  1917. this.w = - this.w;
  1918. return this;
  1919. }
  1920. dot( v ) {
  1921. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1922. }
  1923. lengthSq() {
  1924. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1925. }
  1926. length() {
  1927. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1928. }
  1929. manhattanLength() {
  1930. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1931. }
  1932. normalize() {
  1933. return this.divideScalar( this.length() || 1 );
  1934. }
  1935. setLength( length ) {
  1936. return this.normalize().multiplyScalar( length );
  1937. }
  1938. lerp( v, alpha ) {
  1939. this.x += ( v.x - this.x ) * alpha;
  1940. this.y += ( v.y - this.y ) * alpha;
  1941. this.z += ( v.z - this.z ) * alpha;
  1942. this.w += ( v.w - this.w ) * alpha;
  1943. return this;
  1944. }
  1945. lerpVectors( v1, v2, alpha ) {
  1946. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  1947. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  1948. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  1949. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  1950. return this;
  1951. }
  1952. equals( v ) {
  1953. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1954. }
  1955. fromArray( array, offset = 0 ) {
  1956. this.x = array[ offset ];
  1957. this.y = array[ offset + 1 ];
  1958. this.z = array[ offset + 2 ];
  1959. this.w = array[ offset + 3 ];
  1960. return this;
  1961. }
  1962. toArray( array = [], offset = 0 ) {
  1963. array[ offset ] = this.x;
  1964. array[ offset + 1 ] = this.y;
  1965. array[ offset + 2 ] = this.z;
  1966. array[ offset + 3 ] = this.w;
  1967. return array;
  1968. }
  1969. fromBufferAttribute( attribute, index ) {
  1970. this.x = attribute.getX( index );
  1971. this.y = attribute.getY( index );
  1972. this.z = attribute.getZ( index );
  1973. this.w = attribute.getW( index );
  1974. return this;
  1975. }
  1976. random() {
  1977. this.x = Math.random();
  1978. this.y = Math.random();
  1979. this.z = Math.random();
  1980. this.w = Math.random();
  1981. return this;
  1982. }
  1983. *[ Symbol.iterator ]() {
  1984. yield this.x;
  1985. yield this.y;
  1986. yield this.z;
  1987. yield this.w;
  1988. }
  1989. }
  1990. /*
  1991. In options, we can specify:
  1992. * Texture parameters for an auto-generated target texture
  1993. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  1994. */
  1995. class WebGLRenderTarget extends EventDispatcher {
  1996. constructor( width, height, options = {} ) {
  1997. super();
  1998. this.isWebGLRenderTarget = true;
  1999. this.width = width;
  2000. this.height = height;
  2001. this.depth = 1;
  2002. this.scissor = new Vector4( 0, 0, width, height );
  2003. this.scissorTest = false;
  2004. this.viewport = new Vector4( 0, 0, width, height );
  2005. const image = { width: width, height: height, depth: 1 };
  2006. this.texture = new Texture( image, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  2007. this.texture.isRenderTargetTexture = true;
  2008. this.texture.flipY = false;
  2009. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  2010. this.texture.internalFormat = options.internalFormat !== undefined ? options.internalFormat : null;
  2011. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  2012. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  2013. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
  2014. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  2015. this.samples = options.samples !== undefined ? options.samples : 0;
  2016. }
  2017. setSize( width, height, depth = 1 ) {
  2018. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  2019. this.width = width;
  2020. this.height = height;
  2021. this.depth = depth;
  2022. this.texture.image.width = width;
  2023. this.texture.image.height = height;
  2024. this.texture.image.depth = depth;
  2025. this.dispose();
  2026. }
  2027. this.viewport.set( 0, 0, width, height );
  2028. this.scissor.set( 0, 0, width, height );
  2029. }
  2030. clone() {
  2031. return new this.constructor().copy( this );
  2032. }
  2033. copy( source ) {
  2034. this.width = source.width;
  2035. this.height = source.height;
  2036. this.depth = source.depth;
  2037. this.viewport.copy( source.viewport );
  2038. this.texture = source.texture.clone();
  2039. this.texture.isRenderTargetTexture = true;
  2040. // ensure image object is not shared, see #20328
  2041. const image = Object.assign( {}, source.texture.image );
  2042. this.texture.source = new Source( image );
  2043. this.depthBuffer = source.depthBuffer;
  2044. this.stencilBuffer = source.stencilBuffer;
  2045. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  2046. this.samples = source.samples;
  2047. return this;
  2048. }
  2049. dispose() {
  2050. this.dispatchEvent( { type: 'dispose' } );
  2051. }
  2052. }
  2053. class DataArrayTexture extends Texture {
  2054. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  2055. super( null );
  2056. this.isDataArrayTexture = true;
  2057. this.image = { data, width, height, depth };
  2058. this.magFilter = NearestFilter;
  2059. this.minFilter = NearestFilter;
  2060. this.wrapR = ClampToEdgeWrapping;
  2061. this.generateMipmaps = false;
  2062. this.flipY = false;
  2063. this.unpackAlignment = 1;
  2064. }
  2065. }
  2066. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  2067. constructor( width, height, depth ) {
  2068. super( width, height );
  2069. this.isWebGLArrayRenderTarget = true;
  2070. this.depth = depth;
  2071. this.texture = new DataArrayTexture( null, width, height, depth );
  2072. this.texture.isRenderTargetTexture = true;
  2073. }
  2074. }
  2075. class Data3DTexture extends Texture {
  2076. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  2077. // We're going to add .setXXX() methods for setting properties later.
  2078. // Users can still set in DataTexture3D directly.
  2079. //
  2080. // const texture = new THREE.DataTexture3D( data, width, height, depth );
  2081. // texture.anisotropy = 16;
  2082. //
  2083. // See #14839
  2084. super( null );
  2085. this.isData3DTexture = true;
  2086. this.image = { data, width, height, depth };
  2087. this.magFilter = NearestFilter;
  2088. this.minFilter = NearestFilter;
  2089. this.wrapR = ClampToEdgeWrapping;
  2090. this.generateMipmaps = false;
  2091. this.flipY = false;
  2092. this.unpackAlignment = 1;
  2093. }
  2094. }
  2095. class WebGL3DRenderTarget extends WebGLRenderTarget {
  2096. constructor( width, height, depth ) {
  2097. super( width, height );
  2098. this.isWebGL3DRenderTarget = true;
  2099. this.depth = depth;
  2100. this.texture = new Data3DTexture( null, width, height, depth );
  2101. this.texture.isRenderTargetTexture = true;
  2102. }
  2103. }
  2104. class WebGLMultipleRenderTargets extends WebGLRenderTarget {
  2105. constructor( width, height, count, options = {} ) {
  2106. super( width, height, options );
  2107. this.isWebGLMultipleRenderTargets = true;
  2108. const texture = this.texture;
  2109. this.texture = [];
  2110. for ( let i = 0; i < count; i ++ ) {
  2111. this.texture[ i ] = texture.clone();
  2112. this.texture[ i ].isRenderTargetTexture = true;
  2113. }
  2114. }
  2115. setSize( width, height, depth = 1 ) {
  2116. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  2117. this.width = width;
  2118. this.height = height;
  2119. this.depth = depth;
  2120. for ( let i = 0, il = this.texture.length; i < il; i ++ ) {
  2121. this.texture[ i ].image.width = width;
  2122. this.texture[ i ].image.height = height;
  2123. this.texture[ i ].image.depth = depth;
  2124. }
  2125. this.dispose();
  2126. }
  2127. this.viewport.set( 0, 0, width, height );
  2128. this.scissor.set( 0, 0, width, height );
  2129. return this;
  2130. }
  2131. copy( source ) {
  2132. this.dispose();
  2133. this.width = source.width;
  2134. this.height = source.height;
  2135. this.depth = source.depth;
  2136. this.viewport.set( 0, 0, this.width, this.height );
  2137. this.scissor.set( 0, 0, this.width, this.height );
  2138. this.depthBuffer = source.depthBuffer;
  2139. this.stencilBuffer = source.stencilBuffer;
  2140. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  2141. this.texture.length = 0;
  2142. for ( let i = 0, il = source.texture.length; i < il; i ++ ) {
  2143. this.texture[ i ] = source.texture[ i ].clone();
  2144. this.texture[ i ].isRenderTargetTexture = true;
  2145. }
  2146. return this;
  2147. }
  2148. }
  2149. class Quaternion {
  2150. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2151. this.isQuaternion = true;
  2152. this._x = x;
  2153. this._y = y;
  2154. this._z = z;
  2155. this._w = w;
  2156. }
  2157. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  2158. // fuzz-free, array-based Quaternion SLERP operation
  2159. let x0 = src0[ srcOffset0 + 0 ],
  2160. y0 = src0[ srcOffset0 + 1 ],
  2161. z0 = src0[ srcOffset0 + 2 ],
  2162. w0 = src0[ srcOffset0 + 3 ];
  2163. const x1 = src1[ srcOffset1 + 0 ],
  2164. y1 = src1[ srcOffset1 + 1 ],
  2165. z1 = src1[ srcOffset1 + 2 ],
  2166. w1 = src1[ srcOffset1 + 3 ];
  2167. if ( t === 0 ) {
  2168. dst[ dstOffset + 0 ] = x0;
  2169. dst[ dstOffset + 1 ] = y0;
  2170. dst[ dstOffset + 2 ] = z0;
  2171. dst[ dstOffset + 3 ] = w0;
  2172. return;
  2173. }
  2174. if ( t === 1 ) {
  2175. dst[ dstOffset + 0 ] = x1;
  2176. dst[ dstOffset + 1 ] = y1;
  2177. dst[ dstOffset + 2 ] = z1;
  2178. dst[ dstOffset + 3 ] = w1;
  2179. return;
  2180. }
  2181. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  2182. let s = 1 - t;
  2183. const cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  2184. dir = ( cos >= 0 ? 1 : - 1 ),
  2185. sqrSin = 1 - cos * cos;
  2186. // Skip the Slerp for tiny steps to avoid numeric problems:
  2187. if ( sqrSin > Number.EPSILON ) {
  2188. const sin = Math.sqrt( sqrSin ),
  2189. len = Math.atan2( sin, cos * dir );
  2190. s = Math.sin( s * len ) / sin;
  2191. t = Math.sin( t * len ) / sin;
  2192. }
  2193. const tDir = t * dir;
  2194. x0 = x0 * s + x1 * tDir;
  2195. y0 = y0 * s + y1 * tDir;
  2196. z0 = z0 * s + z1 * tDir;
  2197. w0 = w0 * s + w1 * tDir;
  2198. // Normalize in case we just did a lerp:
  2199. if ( s === 1 - t ) {
  2200. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  2201. x0 *= f;
  2202. y0 *= f;
  2203. z0 *= f;
  2204. w0 *= f;
  2205. }
  2206. }
  2207. dst[ dstOffset ] = x0;
  2208. dst[ dstOffset + 1 ] = y0;
  2209. dst[ dstOffset + 2 ] = z0;
  2210. dst[ dstOffset + 3 ] = w0;
  2211. }
  2212. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  2213. const x0 = src0[ srcOffset0 ];
  2214. const y0 = src0[ srcOffset0 + 1 ];
  2215. const z0 = src0[ srcOffset0 + 2 ];
  2216. const w0 = src0[ srcOffset0 + 3 ];
  2217. const x1 = src1[ srcOffset1 ];
  2218. const y1 = src1[ srcOffset1 + 1 ];
  2219. const z1 = src1[ srcOffset1 + 2 ];
  2220. const w1 = src1[ srcOffset1 + 3 ];
  2221. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  2222. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  2223. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  2224. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  2225. return dst;
  2226. }
  2227. get x() {
  2228. return this._x;
  2229. }
  2230. set x( value ) {
  2231. this._x = value;
  2232. this._onChangeCallback();
  2233. }
  2234. get y() {
  2235. return this._y;
  2236. }
  2237. set y( value ) {
  2238. this._y = value;
  2239. this._onChangeCallback();
  2240. }
  2241. get z() {
  2242. return this._z;
  2243. }
  2244. set z( value ) {
  2245. this._z = value;
  2246. this._onChangeCallback();
  2247. }
  2248. get w() {
  2249. return this._w;
  2250. }
  2251. set w( value ) {
  2252. this._w = value;
  2253. this._onChangeCallback();
  2254. }
  2255. set( x, y, z, w ) {
  2256. this._x = x;
  2257. this._y = y;
  2258. this._z = z;
  2259. this._w = w;
  2260. this._onChangeCallback();
  2261. return this;
  2262. }
  2263. clone() {
  2264. return new this.constructor( this._x, this._y, this._z, this._w );
  2265. }
  2266. copy( quaternion ) {
  2267. this._x = quaternion.x;
  2268. this._y = quaternion.y;
  2269. this._z = quaternion.z;
  2270. this._w = quaternion.w;
  2271. this._onChangeCallback();
  2272. return this;
  2273. }
  2274. setFromEuler( euler, update ) {
  2275. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  2276. // http://www.mathworks.com/matlabcentral/fileexchange/
  2277. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2278. // content/SpinCalc.m
  2279. const cos = Math.cos;
  2280. const sin = Math.sin;
  2281. const c1 = cos( x / 2 );
  2282. const c2 = cos( y / 2 );
  2283. const c3 = cos( z / 2 );
  2284. const s1 = sin( x / 2 );
  2285. const s2 = sin( y / 2 );
  2286. const s3 = sin( z / 2 );
  2287. switch ( order ) {
  2288. case 'XYZ':
  2289. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2290. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2291. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2292. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2293. break;
  2294. case 'YXZ':
  2295. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2296. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2297. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2298. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2299. break;
  2300. case 'ZXY':
  2301. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2302. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2303. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2304. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2305. break;
  2306. case 'ZYX':
  2307. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2308. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2309. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2310. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2311. break;
  2312. case 'YZX':
  2313. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  2314. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  2315. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  2316. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  2317. break;
  2318. case 'XZY':
  2319. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  2320. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  2321. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  2322. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  2323. break;
  2324. default:
  2325. console.warn( 'THREE.Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  2326. }
  2327. if ( update !== false ) this._onChangeCallback();
  2328. return this;
  2329. }
  2330. setFromAxisAngle( axis, angle ) {
  2331. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2332. // assumes axis is normalized
  2333. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  2334. this._x = axis.x * s;
  2335. this._y = axis.y * s;
  2336. this._z = axis.z * s;
  2337. this._w = Math.cos( halfAngle );
  2338. this._onChangeCallback();
  2339. return this;
  2340. }
  2341. setFromRotationMatrix( m ) {
  2342. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2343. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2344. const te = m.elements,
  2345. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  2346. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  2347. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  2348. trace = m11 + m22 + m33;
  2349. if ( trace > 0 ) {
  2350. const s = 0.5 / Math.sqrt( trace + 1.0 );
  2351. this._w = 0.25 / s;
  2352. this._x = ( m32 - m23 ) * s;
  2353. this._y = ( m13 - m31 ) * s;
  2354. this._z = ( m21 - m12 ) * s;
  2355. } else if ( m11 > m22 && m11 > m33 ) {
  2356. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2357. this._w = ( m32 - m23 ) / s;
  2358. this._x = 0.25 * s;
  2359. this._y = ( m12 + m21 ) / s;
  2360. this._z = ( m13 + m31 ) / s;
  2361. } else if ( m22 > m33 ) {
  2362. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2363. this._w = ( m13 - m31 ) / s;
  2364. this._x = ( m12 + m21 ) / s;
  2365. this._y = 0.25 * s;
  2366. this._z = ( m23 + m32 ) / s;
  2367. } else {
  2368. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2369. this._w = ( m21 - m12 ) / s;
  2370. this._x = ( m13 + m31 ) / s;
  2371. this._y = ( m23 + m32 ) / s;
  2372. this._z = 0.25 * s;
  2373. }
  2374. this._onChangeCallback();
  2375. return this;
  2376. }
  2377. setFromUnitVectors( vFrom, vTo ) {
  2378. // assumes direction vectors vFrom and vTo are normalized
  2379. let r = vFrom.dot( vTo ) + 1;
  2380. if ( r < Number.EPSILON ) {
  2381. // vFrom and vTo point in opposite directions
  2382. r = 0;
  2383. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  2384. this._x = - vFrom.y;
  2385. this._y = vFrom.x;
  2386. this._z = 0;
  2387. this._w = r;
  2388. } else {
  2389. this._x = 0;
  2390. this._y = - vFrom.z;
  2391. this._z = vFrom.y;
  2392. this._w = r;
  2393. }
  2394. } else {
  2395. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  2396. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  2397. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  2398. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  2399. this._w = r;
  2400. }
  2401. return this.normalize();
  2402. }
  2403. angleTo( q ) {
  2404. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), - 1, 1 ) ) );
  2405. }
  2406. rotateTowards( q, step ) {
  2407. const angle = this.angleTo( q );
  2408. if ( angle === 0 ) return this;
  2409. const t = Math.min( 1, step / angle );
  2410. this.slerp( q, t );
  2411. return this;
  2412. }
  2413. identity() {
  2414. return this.set( 0, 0, 0, 1 );
  2415. }
  2416. invert() {
  2417. // quaternion is assumed to have unit length
  2418. return this.conjugate();
  2419. }
  2420. conjugate() {
  2421. this._x *= - 1;
  2422. this._y *= - 1;
  2423. this._z *= - 1;
  2424. this._onChangeCallback();
  2425. return this;
  2426. }
  2427. dot( v ) {
  2428. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  2429. }
  2430. lengthSq() {
  2431. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  2432. }
  2433. length() {
  2434. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  2435. }
  2436. normalize() {
  2437. let l = this.length();
  2438. if ( l === 0 ) {
  2439. this._x = 0;
  2440. this._y = 0;
  2441. this._z = 0;
  2442. this._w = 1;
  2443. } else {
  2444. l = 1 / l;
  2445. this._x = this._x * l;
  2446. this._y = this._y * l;
  2447. this._z = this._z * l;
  2448. this._w = this._w * l;
  2449. }
  2450. this._onChangeCallback();
  2451. return this;
  2452. }
  2453. multiply( q ) {
  2454. return this.multiplyQuaternions( this, q );
  2455. }
  2456. premultiply( q ) {
  2457. return this.multiplyQuaternions( q, this );
  2458. }
  2459. multiplyQuaternions( a, b ) {
  2460. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2461. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  2462. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  2463. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2464. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2465. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2466. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2467. this._onChangeCallback();
  2468. return this;
  2469. }
  2470. slerp( qb, t ) {
  2471. if ( t === 0 ) return this;
  2472. if ( t === 1 ) return this.copy( qb );
  2473. const x = this._x, y = this._y, z = this._z, w = this._w;
  2474. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2475. let cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  2476. if ( cosHalfTheta < 0 ) {
  2477. this._w = - qb._w;
  2478. this._x = - qb._x;
  2479. this._y = - qb._y;
  2480. this._z = - qb._z;
  2481. cosHalfTheta = - cosHalfTheta;
  2482. } else {
  2483. this.copy( qb );
  2484. }
  2485. if ( cosHalfTheta >= 1.0 ) {
  2486. this._w = w;
  2487. this._x = x;
  2488. this._y = y;
  2489. this._z = z;
  2490. return this;
  2491. }
  2492. const sqrSinHalfTheta = 1.0 - cosHalfTheta * cosHalfTheta;
  2493. if ( sqrSinHalfTheta <= Number.EPSILON ) {
  2494. const s = 1 - t;
  2495. this._w = s * w + t * this._w;
  2496. this._x = s * x + t * this._x;
  2497. this._y = s * y + t * this._y;
  2498. this._z = s * z + t * this._z;
  2499. this.normalize();
  2500. this._onChangeCallback();
  2501. return this;
  2502. }
  2503. const sinHalfTheta = Math.sqrt( sqrSinHalfTheta );
  2504. const halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  2505. const ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2506. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2507. this._w = ( w * ratioA + this._w * ratioB );
  2508. this._x = ( x * ratioA + this._x * ratioB );
  2509. this._y = ( y * ratioA + this._y * ratioB );
  2510. this._z = ( z * ratioA + this._z * ratioB );
  2511. this._onChangeCallback();
  2512. return this;
  2513. }
  2514. slerpQuaternions( qa, qb, t ) {
  2515. return this.copy( qa ).slerp( qb, t );
  2516. }
  2517. random() {
  2518. // Derived from http://planning.cs.uiuc.edu/node198.html
  2519. // Note, this source uses w, x, y, z ordering,
  2520. // so we swap the order below.
  2521. const u1 = Math.random();
  2522. const sqrt1u1 = Math.sqrt( 1 - u1 );
  2523. const sqrtu1 = Math.sqrt( u1 );
  2524. const u2 = 2 * Math.PI * Math.random();
  2525. const u3 = 2 * Math.PI * Math.random();
  2526. return this.set(
  2527. sqrt1u1 * Math.cos( u2 ),
  2528. sqrtu1 * Math.sin( u3 ),
  2529. sqrtu1 * Math.cos( u3 ),
  2530. sqrt1u1 * Math.sin( u2 ),
  2531. );
  2532. }
  2533. equals( quaternion ) {
  2534. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  2535. }
  2536. fromArray( array, offset = 0 ) {
  2537. this._x = array[ offset ];
  2538. this._y = array[ offset + 1 ];
  2539. this._z = array[ offset + 2 ];
  2540. this._w = array[ offset + 3 ];
  2541. this._onChangeCallback();
  2542. return this;
  2543. }
  2544. toArray( array = [], offset = 0 ) {
  2545. array[ offset ] = this._x;
  2546. array[ offset + 1 ] = this._y;
  2547. array[ offset + 2 ] = this._z;
  2548. array[ offset + 3 ] = this._w;
  2549. return array;
  2550. }
  2551. fromBufferAttribute( attribute, index ) {
  2552. this._x = attribute.getX( index );
  2553. this._y = attribute.getY( index );
  2554. this._z = attribute.getZ( index );
  2555. this._w = attribute.getW( index );
  2556. return this;
  2557. }
  2558. _onChange( callback ) {
  2559. this._onChangeCallback = callback;
  2560. return this;
  2561. }
  2562. _onChangeCallback() {}
  2563. *[ Symbol.iterator ]() {
  2564. yield this._x;
  2565. yield this._y;
  2566. yield this._z;
  2567. yield this._w;
  2568. }
  2569. }
  2570. class Vector3 {
  2571. constructor( x = 0, y = 0, z = 0 ) {
  2572. Vector3.prototype.isVector3 = true;
  2573. this.x = x;
  2574. this.y = y;
  2575. this.z = z;
  2576. }
  2577. set( x, y, z ) {
  2578. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  2579. this.x = x;
  2580. this.y = y;
  2581. this.z = z;
  2582. return this;
  2583. }
  2584. setScalar( scalar ) {
  2585. this.x = scalar;
  2586. this.y = scalar;
  2587. this.z = scalar;
  2588. return this;
  2589. }
  2590. setX( x ) {
  2591. this.x = x;
  2592. return this;
  2593. }
  2594. setY( y ) {
  2595. this.y = y;
  2596. return this;
  2597. }
  2598. setZ( z ) {
  2599. this.z = z;
  2600. return this;
  2601. }
  2602. setComponent( index, value ) {
  2603. switch ( index ) {
  2604. case 0: this.x = value; break;
  2605. case 1: this.y = value; break;
  2606. case 2: this.z = value; break;
  2607. default: throw new Error( 'index is out of range: ' + index );
  2608. }
  2609. return this;
  2610. }
  2611. getComponent( index ) {
  2612. switch ( index ) {
  2613. case 0: return this.x;
  2614. case 1: return this.y;
  2615. case 2: return this.z;
  2616. default: throw new Error( 'index is out of range: ' + index );
  2617. }
  2618. }
  2619. clone() {
  2620. return new this.constructor( this.x, this.y, this.z );
  2621. }
  2622. copy( v ) {
  2623. this.x = v.x;
  2624. this.y = v.y;
  2625. this.z = v.z;
  2626. return this;
  2627. }
  2628. add( v ) {
  2629. this.x += v.x;
  2630. this.y += v.y;
  2631. this.z += v.z;
  2632. return this;
  2633. }
  2634. addScalar( s ) {
  2635. this.x += s;
  2636. this.y += s;
  2637. this.z += s;
  2638. return this;
  2639. }
  2640. addVectors( a, b ) {
  2641. this.x = a.x + b.x;
  2642. this.y = a.y + b.y;
  2643. this.z = a.z + b.z;
  2644. return this;
  2645. }
  2646. addScaledVector( v, s ) {
  2647. this.x += v.x * s;
  2648. this.y += v.y * s;
  2649. this.z += v.z * s;
  2650. return this;
  2651. }
  2652. sub( v ) {
  2653. this.x -= v.x;
  2654. this.y -= v.y;
  2655. this.z -= v.z;
  2656. return this;
  2657. }
  2658. subScalar( s ) {
  2659. this.x -= s;
  2660. this.y -= s;
  2661. this.z -= s;
  2662. return this;
  2663. }
  2664. subVectors( a, b ) {
  2665. this.x = a.x - b.x;
  2666. this.y = a.y - b.y;
  2667. this.z = a.z - b.z;
  2668. return this;
  2669. }
  2670. multiply( v ) {
  2671. this.x *= v.x;
  2672. this.y *= v.y;
  2673. this.z *= v.z;
  2674. return this;
  2675. }
  2676. multiplyScalar( scalar ) {
  2677. this.x *= scalar;
  2678. this.y *= scalar;
  2679. this.z *= scalar;
  2680. return this;
  2681. }
  2682. multiplyVectors( a, b ) {
  2683. this.x = a.x * b.x;
  2684. this.y = a.y * b.y;
  2685. this.z = a.z * b.z;
  2686. return this;
  2687. }
  2688. applyEuler( euler ) {
  2689. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  2690. }
  2691. applyAxisAngle( axis, angle ) {
  2692. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  2693. }
  2694. applyMatrix3( m ) {
  2695. const x = this.x, y = this.y, z = this.z;
  2696. const e = m.elements;
  2697. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  2698. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  2699. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  2700. return this;
  2701. }
  2702. applyNormalMatrix( m ) {
  2703. return this.applyMatrix3( m ).normalize();
  2704. }
  2705. applyMatrix4( m ) {
  2706. const x = this.x, y = this.y, z = this.z;
  2707. const e = m.elements;
  2708. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  2709. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  2710. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  2711. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  2712. return this;
  2713. }
  2714. applyQuaternion( q ) {
  2715. const x = this.x, y = this.y, z = this.z;
  2716. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  2717. // calculate quat * vector
  2718. const ix = qw * x + qy * z - qz * y;
  2719. const iy = qw * y + qz * x - qx * z;
  2720. const iz = qw * z + qx * y - qy * x;
  2721. const iw = - qx * x - qy * y - qz * z;
  2722. // calculate result * inverse quat
  2723. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  2724. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  2725. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  2726. return this;
  2727. }
  2728. project( camera ) {
  2729. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  2730. }
  2731. unproject( camera ) {
  2732. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  2733. }
  2734. transformDirection( m ) {
  2735. // input: THREE.Matrix4 affine matrix
  2736. // vector interpreted as a direction
  2737. const x = this.x, y = this.y, z = this.z;
  2738. const e = m.elements;
  2739. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  2740. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  2741. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  2742. return this.normalize();
  2743. }
  2744. divide( v ) {
  2745. this.x /= v.x;
  2746. this.y /= v.y;
  2747. this.z /= v.z;
  2748. return this;
  2749. }
  2750. divideScalar( scalar ) {
  2751. return this.multiplyScalar( 1 / scalar );
  2752. }
  2753. min( v ) {
  2754. this.x = Math.min( this.x, v.x );
  2755. this.y = Math.min( this.y, v.y );
  2756. this.z = Math.min( this.z, v.z );
  2757. return this;
  2758. }
  2759. max( v ) {
  2760. this.x = Math.max( this.x, v.x );
  2761. this.y = Math.max( this.y, v.y );
  2762. this.z = Math.max( this.z, v.z );
  2763. return this;
  2764. }
  2765. clamp( min, max ) {
  2766. // assumes min < max, componentwise
  2767. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  2768. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  2769. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  2770. return this;
  2771. }
  2772. clampScalar( minVal, maxVal ) {
  2773. this.x = Math.max( minVal, Math.min( maxVal, this.x ) );
  2774. this.y = Math.max( minVal, Math.min( maxVal, this.y ) );
  2775. this.z = Math.max( minVal, Math.min( maxVal, this.z ) );
  2776. return this;
  2777. }
  2778. clampLength( min, max ) {
  2779. const length = this.length();
  2780. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  2781. }
  2782. floor() {
  2783. this.x = Math.floor( this.x );
  2784. this.y = Math.floor( this.y );
  2785. this.z = Math.floor( this.z );
  2786. return this;
  2787. }
  2788. ceil() {
  2789. this.x = Math.ceil( this.x );
  2790. this.y = Math.ceil( this.y );
  2791. this.z = Math.ceil( this.z );
  2792. return this;
  2793. }
  2794. round() {
  2795. this.x = Math.round( this.x );
  2796. this.y = Math.round( this.y );
  2797. this.z = Math.round( this.z );
  2798. return this;
  2799. }
  2800. roundToZero() {
  2801. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  2802. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  2803. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  2804. return this;
  2805. }
  2806. negate() {
  2807. this.x = - this.x;
  2808. this.y = - this.y;
  2809. this.z = - this.z;
  2810. return this;
  2811. }
  2812. dot( v ) {
  2813. return this.x * v.x + this.y * v.y + this.z * v.z;
  2814. }
  2815. // TODO lengthSquared?
  2816. lengthSq() {
  2817. return this.x * this.x + this.y * this.y + this.z * this.z;
  2818. }
  2819. length() {
  2820. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  2821. }
  2822. manhattanLength() {
  2823. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  2824. }
  2825. normalize() {
  2826. return this.divideScalar( this.length() || 1 );
  2827. }
  2828. setLength( length ) {
  2829. return this.normalize().multiplyScalar( length );
  2830. }
  2831. lerp( v, alpha ) {
  2832. this.x += ( v.x - this.x ) * alpha;
  2833. this.y += ( v.y - this.y ) * alpha;
  2834. this.z += ( v.z - this.z ) * alpha;
  2835. return this;
  2836. }
  2837. lerpVectors( v1, v2, alpha ) {
  2838. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2839. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2840. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  2841. return this;
  2842. }
  2843. cross( v ) {
  2844. return this.crossVectors( this, v );
  2845. }
  2846. crossVectors( a, b ) {
  2847. const ax = a.x, ay = a.y, az = a.z;
  2848. const bx = b.x, by = b.y, bz = b.z;
  2849. this.x = ay * bz - az * by;
  2850. this.y = az * bx - ax * bz;
  2851. this.z = ax * by - ay * bx;
  2852. return this;
  2853. }
  2854. projectOnVector( v ) {
  2855. const denominator = v.lengthSq();
  2856. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  2857. const scalar = v.dot( this ) / denominator;
  2858. return this.copy( v ).multiplyScalar( scalar );
  2859. }
  2860. projectOnPlane( planeNormal ) {
  2861. _vector$c.copy( this ).projectOnVector( planeNormal );
  2862. return this.sub( _vector$c );
  2863. }
  2864. reflect( normal ) {
  2865. // reflect incident vector off plane orthogonal to normal
  2866. // normal is assumed to have unit length
  2867. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  2868. }
  2869. angleTo( v ) {
  2870. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2871. if ( denominator === 0 ) return Math.PI / 2;
  2872. const theta = this.dot( v ) / denominator;
  2873. // clamp, to handle numerical problems
  2874. return Math.acos( clamp( theta, - 1, 1 ) );
  2875. }
  2876. distanceTo( v ) {
  2877. return Math.sqrt( this.distanceToSquared( v ) );
  2878. }
  2879. distanceToSquared( v ) {
  2880. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  2881. return dx * dx + dy * dy + dz * dz;
  2882. }
  2883. manhattanDistanceTo( v ) {
  2884. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  2885. }
  2886. setFromSpherical( s ) {
  2887. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  2888. }
  2889. setFromSphericalCoords( radius, phi, theta ) {
  2890. const sinPhiRadius = Math.sin( phi ) * radius;
  2891. this.x = sinPhiRadius * Math.sin( theta );
  2892. this.y = Math.cos( phi ) * radius;
  2893. this.z = sinPhiRadius * Math.cos( theta );
  2894. return this;
  2895. }
  2896. setFromCylindrical( c ) {
  2897. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  2898. }
  2899. setFromCylindricalCoords( radius, theta, y ) {
  2900. this.x = radius * Math.sin( theta );
  2901. this.y = y;
  2902. this.z = radius * Math.cos( theta );
  2903. return this;
  2904. }
  2905. setFromMatrixPosition( m ) {
  2906. const e = m.elements;
  2907. this.x = e[ 12 ];
  2908. this.y = e[ 13 ];
  2909. this.z = e[ 14 ];
  2910. return this;
  2911. }
  2912. setFromMatrixScale( m ) {
  2913. const sx = this.setFromMatrixColumn( m, 0 ).length();
  2914. const sy = this.setFromMatrixColumn( m, 1 ).length();
  2915. const sz = this.setFromMatrixColumn( m, 2 ).length();
  2916. this.x = sx;
  2917. this.y = sy;
  2918. this.z = sz;
  2919. return this;
  2920. }
  2921. setFromMatrixColumn( m, index ) {
  2922. return this.fromArray( m.elements, index * 4 );
  2923. }
  2924. setFromMatrix3Column( m, index ) {
  2925. return this.fromArray( m.elements, index * 3 );
  2926. }
  2927. setFromEuler( e ) {
  2928. this.x = e._x;
  2929. this.y = e._y;
  2930. this.z = e._z;
  2931. return this;
  2932. }
  2933. equals( v ) {
  2934. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  2935. }
  2936. fromArray( array, offset = 0 ) {
  2937. this.x = array[ offset ];
  2938. this.y = array[ offset + 1 ];
  2939. this.z = array[ offset + 2 ];
  2940. return this;
  2941. }
  2942. toArray( array = [], offset = 0 ) {
  2943. array[ offset ] = this.x;
  2944. array[ offset + 1 ] = this.y;
  2945. array[ offset + 2 ] = this.z;
  2946. return array;
  2947. }
  2948. fromBufferAttribute( attribute, index ) {
  2949. this.x = attribute.getX( index );
  2950. this.y = attribute.getY( index );
  2951. this.z = attribute.getZ( index );
  2952. return this;
  2953. }
  2954. random() {
  2955. this.x = Math.random();
  2956. this.y = Math.random();
  2957. this.z = Math.random();
  2958. return this;
  2959. }
  2960. randomDirection() {
  2961. // Derived from https://mathworld.wolfram.com/SpherePointPicking.html
  2962. const u = ( Math.random() - 0.5 ) * 2;
  2963. const t = Math.random() * Math.PI * 2;
  2964. const f = Math.sqrt( 1 - u ** 2 );
  2965. this.x = f * Math.cos( t );
  2966. this.y = f * Math.sin( t );
  2967. this.z = u;
  2968. return this;
  2969. }
  2970. *[ Symbol.iterator ]() {
  2971. yield this.x;
  2972. yield this.y;
  2973. yield this.z;
  2974. }
  2975. }
  2976. const _vector$c = /*@__PURE__*/ new Vector3();
  2977. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  2978. class Box3 {
  2979. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  2980. this.isBox3 = true;
  2981. this.min = min;
  2982. this.max = max;
  2983. }
  2984. set( min, max ) {
  2985. this.min.copy( min );
  2986. this.max.copy( max );
  2987. return this;
  2988. }
  2989. setFromArray( array ) {
  2990. let minX = + Infinity;
  2991. let minY = + Infinity;
  2992. let minZ = + Infinity;
  2993. let maxX = - Infinity;
  2994. let maxY = - Infinity;
  2995. let maxZ = - Infinity;
  2996. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  2997. const x = array[ i ];
  2998. const y = array[ i + 1 ];
  2999. const z = array[ i + 2 ];
  3000. if ( x < minX ) minX = x;
  3001. if ( y < minY ) minY = y;
  3002. if ( z < minZ ) minZ = z;
  3003. if ( x > maxX ) maxX = x;
  3004. if ( y > maxY ) maxY = y;
  3005. if ( z > maxZ ) maxZ = z;
  3006. }
  3007. this.min.set( minX, minY, minZ );
  3008. this.max.set( maxX, maxY, maxZ );
  3009. return this;
  3010. }
  3011. setFromBufferAttribute( attribute ) {
  3012. let minX = + Infinity;
  3013. let minY = + Infinity;
  3014. let minZ = + Infinity;
  3015. let maxX = - Infinity;
  3016. let maxY = - Infinity;
  3017. let maxZ = - Infinity;
  3018. for ( let i = 0, l = attribute.count; i < l; i ++ ) {
  3019. const x = attribute.getX( i );
  3020. const y = attribute.getY( i );
  3021. const z = attribute.getZ( i );
  3022. if ( x < minX ) minX = x;
  3023. if ( y < minY ) minY = y;
  3024. if ( z < minZ ) minZ = z;
  3025. if ( x > maxX ) maxX = x;
  3026. if ( y > maxY ) maxY = y;
  3027. if ( z > maxZ ) maxZ = z;
  3028. }
  3029. this.min.set( minX, minY, minZ );
  3030. this.max.set( maxX, maxY, maxZ );
  3031. return this;
  3032. }
  3033. setFromPoints( points ) {
  3034. this.makeEmpty();
  3035. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3036. this.expandByPoint( points[ i ] );
  3037. }
  3038. return this;
  3039. }
  3040. setFromCenterAndSize( center, size ) {
  3041. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  3042. this.min.copy( center ).sub( halfSize );
  3043. this.max.copy( center ).add( halfSize );
  3044. return this;
  3045. }
  3046. setFromObject( object, precise = false ) {
  3047. this.makeEmpty();
  3048. return this.expandByObject( object, precise );
  3049. }
  3050. clone() {
  3051. return new this.constructor().copy( this );
  3052. }
  3053. copy( box ) {
  3054. this.min.copy( box.min );
  3055. this.max.copy( box.max );
  3056. return this;
  3057. }
  3058. makeEmpty() {
  3059. this.min.x = this.min.y = this.min.z = + Infinity;
  3060. this.max.x = this.max.y = this.max.z = - Infinity;
  3061. return this;
  3062. }
  3063. isEmpty() {
  3064. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  3065. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  3066. }
  3067. getCenter( target ) {
  3068. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  3069. }
  3070. getSize( target ) {
  3071. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  3072. }
  3073. expandByPoint( point ) {
  3074. this.min.min( point );
  3075. this.max.max( point );
  3076. return this;
  3077. }
  3078. expandByVector( vector ) {
  3079. this.min.sub( vector );
  3080. this.max.add( vector );
  3081. return this;
  3082. }
  3083. expandByScalar( scalar ) {
  3084. this.min.addScalar( - scalar );
  3085. this.max.addScalar( scalar );
  3086. return this;
  3087. }
  3088. expandByObject( object, precise = false ) {
  3089. // Computes the world-axis-aligned bounding box of an object (including its children),
  3090. // accounting for both the object's, and children's, world transforms
  3091. object.updateWorldMatrix( false, false );
  3092. const geometry = object.geometry;
  3093. if ( geometry !== undefined ) {
  3094. if ( precise && geometry.attributes != undefined && geometry.attributes.position !== undefined ) {
  3095. const position = geometry.attributes.position;
  3096. for ( let i = 0, l = position.count; i < l; i ++ ) {
  3097. _vector$b.fromBufferAttribute( position, i ).applyMatrix4( object.matrixWorld );
  3098. this.expandByPoint( _vector$b );
  3099. }
  3100. } else {
  3101. if ( geometry.boundingBox === null ) {
  3102. geometry.computeBoundingBox();
  3103. }
  3104. _box$3.copy( geometry.boundingBox );
  3105. _box$3.applyMatrix4( object.matrixWorld );
  3106. this.union( _box$3 );
  3107. }
  3108. }
  3109. const children = object.children;
  3110. for ( let i = 0, l = children.length; i < l; i ++ ) {
  3111. this.expandByObject( children[ i ], precise );
  3112. }
  3113. return this;
  3114. }
  3115. containsPoint( point ) {
  3116. return point.x < this.min.x || point.x > this.max.x ||
  3117. point.y < this.min.y || point.y > this.max.y ||
  3118. point.z < this.min.z || point.z > this.max.z ? false : true;
  3119. }
  3120. containsBox( box ) {
  3121. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  3122. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  3123. this.min.z <= box.min.z && box.max.z <= this.max.z;
  3124. }
  3125. getParameter( point, target ) {
  3126. // This can potentially have a divide by zero if the box
  3127. // has a size dimension of 0.
  3128. return target.set(
  3129. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  3130. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  3131. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  3132. );
  3133. }
  3134. intersectsBox( box ) {
  3135. // using 6 splitting planes to rule out intersections.
  3136. return box.max.x < this.min.x || box.min.x > this.max.x ||
  3137. box.max.y < this.min.y || box.min.y > this.max.y ||
  3138. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  3139. }
  3140. intersectsSphere( sphere ) {
  3141. // Find the point on the AABB closest to the sphere center.
  3142. this.clampPoint( sphere.center, _vector$b );
  3143. // If that point is inside the sphere, the AABB and sphere intersect.
  3144. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  3145. }
  3146. intersectsPlane( plane ) {
  3147. // We compute the minimum and maximum dot product values. If those values
  3148. // are on the same side (back or front) of the plane, then there is no intersection.
  3149. let min, max;
  3150. if ( plane.normal.x > 0 ) {
  3151. min = plane.normal.x * this.min.x;
  3152. max = plane.normal.x * this.max.x;
  3153. } else {
  3154. min = plane.normal.x * this.max.x;
  3155. max = plane.normal.x * this.min.x;
  3156. }
  3157. if ( plane.normal.y > 0 ) {
  3158. min += plane.normal.y * this.min.y;
  3159. max += plane.normal.y * this.max.y;
  3160. } else {
  3161. min += plane.normal.y * this.max.y;
  3162. max += plane.normal.y * this.min.y;
  3163. }
  3164. if ( plane.normal.z > 0 ) {
  3165. min += plane.normal.z * this.min.z;
  3166. max += plane.normal.z * this.max.z;
  3167. } else {
  3168. min += plane.normal.z * this.max.z;
  3169. max += plane.normal.z * this.min.z;
  3170. }
  3171. return ( min <= - plane.constant && max >= - plane.constant );
  3172. }
  3173. intersectsTriangle( triangle ) {
  3174. if ( this.isEmpty() ) {
  3175. return false;
  3176. }
  3177. // compute box center and extents
  3178. this.getCenter( _center );
  3179. _extents.subVectors( this.max, _center );
  3180. // translate triangle to aabb origin
  3181. _v0$2.subVectors( triangle.a, _center );
  3182. _v1$7.subVectors( triangle.b, _center );
  3183. _v2$3.subVectors( triangle.c, _center );
  3184. // compute edge vectors for triangle
  3185. _f0.subVectors( _v1$7, _v0$2 );
  3186. _f1.subVectors( _v2$3, _v1$7 );
  3187. _f2.subVectors( _v0$2, _v2$3 );
  3188. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  3189. // 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
  3190. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  3191. let axes = [
  3192. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  3193. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  3194. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  3195. ];
  3196. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ) ) {
  3197. return false;
  3198. }
  3199. // test 3 face normals from the aabb
  3200. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  3201. if ( ! satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents ) ) {
  3202. return false;
  3203. }
  3204. // finally testing the face normal of the triangle
  3205. // use already existing triangle edge vectors here
  3206. _triangleNormal.crossVectors( _f0, _f1 );
  3207. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  3208. return satForAxes( axes, _v0$2, _v1$7, _v2$3, _extents );
  3209. }
  3210. clampPoint( point, target ) {
  3211. return target.copy( point ).clamp( this.min, this.max );
  3212. }
  3213. distanceToPoint( point ) {
  3214. const clampedPoint = _vector$b.copy( point ).clamp( this.min, this.max );
  3215. return clampedPoint.sub( point ).length();
  3216. }
  3217. getBoundingSphere( target ) {
  3218. this.getCenter( target.center );
  3219. target.radius = this.getSize( _vector$b ).length() * 0.5;
  3220. return target;
  3221. }
  3222. intersect( box ) {
  3223. this.min.max( box.min );
  3224. this.max.min( box.max );
  3225. // 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.
  3226. if ( this.isEmpty() ) this.makeEmpty();
  3227. return this;
  3228. }
  3229. union( box ) {
  3230. this.min.min( box.min );
  3231. this.max.max( box.max );
  3232. return this;
  3233. }
  3234. applyMatrix4( matrix ) {
  3235. // transform of empty box is an empty box.
  3236. if ( this.isEmpty() ) return this;
  3237. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  3238. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  3239. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  3240. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  3241. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  3242. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  3243. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  3244. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  3245. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  3246. this.setFromPoints( _points );
  3247. return this;
  3248. }
  3249. translate( offset ) {
  3250. this.min.add( offset );
  3251. this.max.add( offset );
  3252. return this;
  3253. }
  3254. equals( box ) {
  3255. return box.min.equals( this.min ) && box.max.equals( this.max );
  3256. }
  3257. }
  3258. const _points = [
  3259. /*@__PURE__*/ new Vector3(),
  3260. /*@__PURE__*/ new Vector3(),
  3261. /*@__PURE__*/ new Vector3(),
  3262. /*@__PURE__*/ new Vector3(),
  3263. /*@__PURE__*/ new Vector3(),
  3264. /*@__PURE__*/ new Vector3(),
  3265. /*@__PURE__*/ new Vector3(),
  3266. /*@__PURE__*/ new Vector3()
  3267. ];
  3268. const _vector$b = /*@__PURE__*/ new Vector3();
  3269. const _box$3 = /*@__PURE__*/ new Box3();
  3270. // triangle centered vertices
  3271. const _v0$2 = /*@__PURE__*/ new Vector3();
  3272. const _v1$7 = /*@__PURE__*/ new Vector3();
  3273. const _v2$3 = /*@__PURE__*/ new Vector3();
  3274. // triangle edge vectors
  3275. const _f0 = /*@__PURE__*/ new Vector3();
  3276. const _f1 = /*@__PURE__*/ new Vector3();
  3277. const _f2 = /*@__PURE__*/ new Vector3();
  3278. const _center = /*@__PURE__*/ new Vector3();
  3279. const _extents = /*@__PURE__*/ new Vector3();
  3280. const _triangleNormal = /*@__PURE__*/ new Vector3();
  3281. const _testAxis = /*@__PURE__*/ new Vector3();
  3282. function satForAxes( axes, v0, v1, v2, extents ) {
  3283. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  3284. _testAxis.fromArray( axes, i );
  3285. // project the aabb onto the separating axis
  3286. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  3287. // project all 3 vertices of the triangle onto the separating axis
  3288. const p0 = v0.dot( _testAxis );
  3289. const p1 = v1.dot( _testAxis );
  3290. const p2 = v2.dot( _testAxis );
  3291. // actual test, basically see if either of the most extreme of the triangle points intersects r
  3292. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  3293. // points of the projected triangle are outside the projected half-length of the aabb
  3294. // the axis is separating and we can exit
  3295. return false;
  3296. }
  3297. }
  3298. return true;
  3299. }
  3300. const _box$2 = /*@__PURE__*/ new Box3();
  3301. const _v1$6 = /*@__PURE__*/ new Vector3();
  3302. const _toFarthestPoint = /*@__PURE__*/ new Vector3();
  3303. const _toPoint = /*@__PURE__*/ new Vector3();
  3304. class Sphere {
  3305. constructor( center = new Vector3(), radius = - 1 ) {
  3306. this.center = center;
  3307. this.radius = radius;
  3308. }
  3309. set( center, radius ) {
  3310. this.center.copy( center );
  3311. this.radius = radius;
  3312. return this;
  3313. }
  3314. setFromPoints( points, optionalCenter ) {
  3315. const center = this.center;
  3316. if ( optionalCenter !== undefined ) {
  3317. center.copy( optionalCenter );
  3318. } else {
  3319. _box$2.setFromPoints( points ).getCenter( center );
  3320. }
  3321. let maxRadiusSq = 0;
  3322. for ( let i = 0, il = points.length; i < il; i ++ ) {
  3323. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3324. }
  3325. this.radius = Math.sqrt( maxRadiusSq );
  3326. return this;
  3327. }
  3328. copy( sphere ) {
  3329. this.center.copy( sphere.center );
  3330. this.radius = sphere.radius;
  3331. return this;
  3332. }
  3333. isEmpty() {
  3334. return ( this.radius < 0 );
  3335. }
  3336. makeEmpty() {
  3337. this.center.set( 0, 0, 0 );
  3338. this.radius = - 1;
  3339. return this;
  3340. }
  3341. containsPoint( point ) {
  3342. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3343. }
  3344. distanceToPoint( point ) {
  3345. return ( point.distanceTo( this.center ) - this.radius );
  3346. }
  3347. intersectsSphere( sphere ) {
  3348. const radiusSum = this.radius + sphere.radius;
  3349. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3350. }
  3351. intersectsBox( box ) {
  3352. return box.intersectsSphere( this );
  3353. }
  3354. intersectsPlane( plane ) {
  3355. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  3356. }
  3357. clampPoint( point, target ) {
  3358. const deltaLengthSq = this.center.distanceToSquared( point );
  3359. target.copy( point );
  3360. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3361. target.sub( this.center ).normalize();
  3362. target.multiplyScalar( this.radius ).add( this.center );
  3363. }
  3364. return target;
  3365. }
  3366. getBoundingBox( target ) {
  3367. if ( this.isEmpty() ) {
  3368. // Empty sphere produces empty bounding box
  3369. target.makeEmpty();
  3370. return target;
  3371. }
  3372. target.set( this.center, this.center );
  3373. target.expandByScalar( this.radius );
  3374. return target;
  3375. }
  3376. applyMatrix4( matrix ) {
  3377. this.center.applyMatrix4( matrix );
  3378. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3379. return this;
  3380. }
  3381. translate( offset ) {
  3382. this.center.add( offset );
  3383. return this;
  3384. }
  3385. expandByPoint( point ) {
  3386. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L649-L671
  3387. _toPoint.subVectors( point, this.center );
  3388. const lengthSq = _toPoint.lengthSq();
  3389. if ( lengthSq > ( this.radius * this.radius ) ) {
  3390. const length = Math.sqrt( lengthSq );
  3391. const missingRadiusHalf = ( length - this.radius ) * 0.5;
  3392. // Nudge this sphere towards the target point. Add half the missing distance to radius,
  3393. // and the other half to position. This gives a tighter enclosure, instead of if
  3394. // the whole missing distance were just added to radius.
  3395. this.center.add( _toPoint.multiplyScalar( missingRadiusHalf / length ) );
  3396. this.radius += missingRadiusHalf;
  3397. }
  3398. return this;
  3399. }
  3400. union( sphere ) {
  3401. // from https://github.com/juj/MathGeoLib/blob/2940b99b99cfe575dd45103ef20f4019dee15b54/src/Geometry/Sphere.cpp#L759-L769
  3402. // To enclose another sphere into this sphere, we only need to enclose two points:
  3403. // 1) Enclose the farthest point on the other sphere into this sphere.
  3404. // 2) Enclose the opposite point of the farthest point into this sphere.
  3405. if ( this.center.equals( sphere.center ) === true ) {
  3406. _toFarthestPoint.set( 0, 0, 1 ).multiplyScalar( sphere.radius );
  3407. } else {
  3408. _toFarthestPoint.subVectors( sphere.center, this.center ).normalize().multiplyScalar( sphere.radius );
  3409. }
  3410. this.expandByPoint( _v1$6.copy( sphere.center ).add( _toFarthestPoint ) );
  3411. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _toFarthestPoint ) );
  3412. return this;
  3413. }
  3414. equals( sphere ) {
  3415. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3416. }
  3417. clone() {
  3418. return new this.constructor().copy( this );
  3419. }
  3420. }
  3421. const _vector$a = /*@__PURE__*/ new Vector3();
  3422. const _segCenter = /*@__PURE__*/ new Vector3();
  3423. const _segDir = /*@__PURE__*/ new Vector3();
  3424. const _diff = /*@__PURE__*/ new Vector3();
  3425. const _edge1 = /*@__PURE__*/ new Vector3();
  3426. const _edge2 = /*@__PURE__*/ new Vector3();
  3427. const _normal$1 = /*@__PURE__*/ new Vector3();
  3428. class Ray {
  3429. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, - 1 ) ) {
  3430. this.origin = origin;
  3431. this.direction = direction;
  3432. }
  3433. set( origin, direction ) {
  3434. this.origin.copy( origin );
  3435. this.direction.copy( direction );
  3436. return this;
  3437. }
  3438. copy( ray ) {
  3439. this.origin.copy( ray.origin );
  3440. this.direction.copy( ray.direction );
  3441. return this;
  3442. }
  3443. at( t, target ) {
  3444. return target.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3445. }
  3446. lookAt( v ) {
  3447. this.direction.copy( v ).sub( this.origin ).normalize();
  3448. return this;
  3449. }
  3450. recast( t ) {
  3451. this.origin.copy( this.at( t, _vector$a ) );
  3452. return this;
  3453. }
  3454. closestPointToPoint( point, target ) {
  3455. target.subVectors( point, this.origin );
  3456. const directionDistance = target.dot( this.direction );
  3457. if ( directionDistance < 0 ) {
  3458. return target.copy( this.origin );
  3459. }
  3460. return target.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3461. }
  3462. distanceToPoint( point ) {
  3463. return Math.sqrt( this.distanceSqToPoint( point ) );
  3464. }
  3465. distanceSqToPoint( point ) {
  3466. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  3467. // point behind the ray
  3468. if ( directionDistance < 0 ) {
  3469. return this.origin.distanceToSquared( point );
  3470. }
  3471. _vector$a.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3472. return _vector$a.distanceToSquared( point );
  3473. }
  3474. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3475. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  3476. // It returns the min distance between the ray and the segment
  3477. // defined by v0 and v1
  3478. // It can also set two optional targets :
  3479. // - The closest point on the ray
  3480. // - The closest point on the segment
  3481. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3482. _segDir.copy( v1 ).sub( v0 ).normalize();
  3483. _diff.copy( this.origin ).sub( _segCenter );
  3484. const segExtent = v0.distanceTo( v1 ) * 0.5;
  3485. const a01 = - this.direction.dot( _segDir );
  3486. const b0 = _diff.dot( this.direction );
  3487. const b1 = - _diff.dot( _segDir );
  3488. const c = _diff.lengthSq();
  3489. const det = Math.abs( 1 - a01 * a01 );
  3490. let s0, s1, sqrDist, extDet;
  3491. if ( det > 0 ) {
  3492. // The ray and segment are not parallel.
  3493. s0 = a01 * b1 - b0;
  3494. s1 = a01 * b0 - b1;
  3495. extDet = segExtent * det;
  3496. if ( s0 >= 0 ) {
  3497. if ( s1 >= - extDet ) {
  3498. if ( s1 <= extDet ) {
  3499. // region 0
  3500. // Minimum at interior points of ray and segment.
  3501. const invDet = 1 / det;
  3502. s0 *= invDet;
  3503. s1 *= invDet;
  3504. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3505. } else {
  3506. // region 1
  3507. s1 = segExtent;
  3508. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3509. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3510. }
  3511. } else {
  3512. // region 5
  3513. s1 = - segExtent;
  3514. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3515. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3516. }
  3517. } else {
  3518. if ( s1 <= - extDet ) {
  3519. // region 4
  3520. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3521. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3522. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3523. } else if ( s1 <= extDet ) {
  3524. // region 3
  3525. s0 = 0;
  3526. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3527. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3528. } else {
  3529. // region 2
  3530. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3531. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3532. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3533. }
  3534. }
  3535. } else {
  3536. // Ray and segment are parallel.
  3537. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3538. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3539. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3540. }
  3541. if ( optionalPointOnRay ) {
  3542. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  3543. }
  3544. if ( optionalPointOnSegment ) {
  3545. optionalPointOnSegment.copy( _segDir ).multiplyScalar( s1 ).add( _segCenter );
  3546. }
  3547. return sqrDist;
  3548. }
  3549. intersectSphere( sphere, target ) {
  3550. _vector$a.subVectors( sphere.center, this.origin );
  3551. const tca = _vector$a.dot( this.direction );
  3552. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  3553. const radius2 = sphere.radius * sphere.radius;
  3554. if ( d2 > radius2 ) return null;
  3555. const thc = Math.sqrt( radius2 - d2 );
  3556. // t0 = first intersect point - entrance on front of sphere
  3557. const t0 = tca - thc;
  3558. // t1 = second intersect point - exit point on back of sphere
  3559. const t1 = tca + thc;
  3560. // test to see if both t0 and t1 are behind the ray - if so, return null
  3561. if ( t0 < 0 && t1 < 0 ) return null;
  3562. // test to see if t0 is behind the ray:
  3563. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3564. // in order to always return an intersect point that is in front of the ray.
  3565. if ( t0 < 0 ) return this.at( t1, target );
  3566. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3567. return this.at( t0, target );
  3568. }
  3569. intersectsSphere( sphere ) {
  3570. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  3571. }
  3572. distanceToPlane( plane ) {
  3573. const denominator = plane.normal.dot( this.direction );
  3574. if ( denominator === 0 ) {
  3575. // line is coplanar, return origin
  3576. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3577. return 0;
  3578. }
  3579. // Null is preferable to undefined since undefined means.... it is undefined
  3580. return null;
  3581. }
  3582. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3583. // Return if the ray never intersects the plane
  3584. return t >= 0 ? t : null;
  3585. }
  3586. intersectPlane( plane, target ) {
  3587. const t = this.distanceToPlane( plane );
  3588. if ( t === null ) {
  3589. return null;
  3590. }
  3591. return this.at( t, target );
  3592. }
  3593. intersectsPlane( plane ) {
  3594. // check if the ray lies on the plane first
  3595. const distToPoint = plane.distanceToPoint( this.origin );
  3596. if ( distToPoint === 0 ) {
  3597. return true;
  3598. }
  3599. const denominator = plane.normal.dot( this.direction );
  3600. if ( denominator * distToPoint < 0 ) {
  3601. return true;
  3602. }
  3603. // ray origin is behind the plane (and is pointing behind it)
  3604. return false;
  3605. }
  3606. intersectBox( box, target ) {
  3607. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  3608. const invdirx = 1 / this.direction.x,
  3609. invdiry = 1 / this.direction.y,
  3610. invdirz = 1 / this.direction.z;
  3611. const origin = this.origin;
  3612. if ( invdirx >= 0 ) {
  3613. tmin = ( box.min.x - origin.x ) * invdirx;
  3614. tmax = ( box.max.x - origin.x ) * invdirx;
  3615. } else {
  3616. tmin = ( box.max.x - origin.x ) * invdirx;
  3617. tmax = ( box.min.x - origin.x ) * invdirx;
  3618. }
  3619. if ( invdiry >= 0 ) {
  3620. tymin = ( box.min.y - origin.y ) * invdiry;
  3621. tymax = ( box.max.y - origin.y ) * invdiry;
  3622. } else {
  3623. tymin = ( box.max.y - origin.y ) * invdiry;
  3624. tymax = ( box.min.y - origin.y ) * invdiry;
  3625. }
  3626. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3627. // These lines also handle the case where tmin or tmax is NaN
  3628. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3629. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  3630. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  3631. if ( invdirz >= 0 ) {
  3632. tzmin = ( box.min.z - origin.z ) * invdirz;
  3633. tzmax = ( box.max.z - origin.z ) * invdirz;
  3634. } else {
  3635. tzmin = ( box.max.z - origin.z ) * invdirz;
  3636. tzmax = ( box.min.z - origin.z ) * invdirz;
  3637. }
  3638. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3639. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3640. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3641. //return point closest to the ray (positive side)
  3642. if ( tmax < 0 ) return null;
  3643. return this.at( tmin >= 0 ? tmin : tmax, target );
  3644. }
  3645. intersectsBox( box ) {
  3646. return this.intersectBox( box, _vector$a ) !== null;
  3647. }
  3648. intersectTriangle( a, b, c, backfaceCulling, target ) {
  3649. // Compute the offset origin, edges, and normal.
  3650. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  3651. _edge1.subVectors( b, a );
  3652. _edge2.subVectors( c, a );
  3653. _normal$1.crossVectors( _edge1, _edge2 );
  3654. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3655. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3656. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3657. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3658. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3659. let DdN = this.direction.dot( _normal$1 );
  3660. let sign;
  3661. if ( DdN > 0 ) {
  3662. if ( backfaceCulling ) return null;
  3663. sign = 1;
  3664. } else if ( DdN < 0 ) {
  3665. sign = - 1;
  3666. DdN = - DdN;
  3667. } else {
  3668. return null;
  3669. }
  3670. _diff.subVectors( this.origin, a );
  3671. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  3672. // b1 < 0, no intersection
  3673. if ( DdQxE2 < 0 ) {
  3674. return null;
  3675. }
  3676. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  3677. // b2 < 0, no intersection
  3678. if ( DdE1xQ < 0 ) {
  3679. return null;
  3680. }
  3681. // b1+b2 > 1, no intersection
  3682. if ( DdQxE2 + DdE1xQ > DdN ) {
  3683. return null;
  3684. }
  3685. // Line intersects triangle, check if ray does.
  3686. const QdN = - sign * _diff.dot( _normal$1 );
  3687. // t < 0, no intersection
  3688. if ( QdN < 0 ) {
  3689. return null;
  3690. }
  3691. // Ray intersects triangle.
  3692. return this.at( QdN / DdN, target );
  3693. }
  3694. applyMatrix4( matrix4 ) {
  3695. this.origin.applyMatrix4( matrix4 );
  3696. this.direction.transformDirection( matrix4 );
  3697. return this;
  3698. }
  3699. equals( ray ) {
  3700. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3701. }
  3702. clone() {
  3703. return new this.constructor().copy( this );
  3704. }
  3705. }
  3706. class Matrix4 {
  3707. constructor() {
  3708. Matrix4.prototype.isMatrix4 = true;
  3709. this.elements = [
  3710. 1, 0, 0, 0,
  3711. 0, 1, 0, 0,
  3712. 0, 0, 1, 0,
  3713. 0, 0, 0, 1
  3714. ];
  3715. }
  3716. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  3717. const te = this.elements;
  3718. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  3719. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  3720. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  3721. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  3722. return this;
  3723. }
  3724. identity() {
  3725. this.set(
  3726. 1, 0, 0, 0,
  3727. 0, 1, 0, 0,
  3728. 0, 0, 1, 0,
  3729. 0, 0, 0, 1
  3730. );
  3731. return this;
  3732. }
  3733. clone() {
  3734. return new Matrix4().fromArray( this.elements );
  3735. }
  3736. copy( m ) {
  3737. const te = this.elements;
  3738. const me = m.elements;
  3739. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  3740. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  3741. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  3742. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  3743. return this;
  3744. }
  3745. copyPosition( m ) {
  3746. const te = this.elements, me = m.elements;
  3747. te[ 12 ] = me[ 12 ];
  3748. te[ 13 ] = me[ 13 ];
  3749. te[ 14 ] = me[ 14 ];
  3750. return this;
  3751. }
  3752. setFromMatrix3( m ) {
  3753. const me = m.elements;
  3754. this.set(
  3755. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  3756. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  3757. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  3758. 0, 0, 0, 1
  3759. );
  3760. return this;
  3761. }
  3762. extractBasis( xAxis, yAxis, zAxis ) {
  3763. xAxis.setFromMatrixColumn( this, 0 );
  3764. yAxis.setFromMatrixColumn( this, 1 );
  3765. zAxis.setFromMatrixColumn( this, 2 );
  3766. return this;
  3767. }
  3768. makeBasis( xAxis, yAxis, zAxis ) {
  3769. this.set(
  3770. xAxis.x, yAxis.x, zAxis.x, 0,
  3771. xAxis.y, yAxis.y, zAxis.y, 0,
  3772. xAxis.z, yAxis.z, zAxis.z, 0,
  3773. 0, 0, 0, 1
  3774. );
  3775. return this;
  3776. }
  3777. extractRotation( m ) {
  3778. // this method does not support reflection matrices
  3779. const te = this.elements;
  3780. const me = m.elements;
  3781. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  3782. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  3783. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  3784. te[ 0 ] = me[ 0 ] * scaleX;
  3785. te[ 1 ] = me[ 1 ] * scaleX;
  3786. te[ 2 ] = me[ 2 ] * scaleX;
  3787. te[ 3 ] = 0;
  3788. te[ 4 ] = me[ 4 ] * scaleY;
  3789. te[ 5 ] = me[ 5 ] * scaleY;
  3790. te[ 6 ] = me[ 6 ] * scaleY;
  3791. te[ 7 ] = 0;
  3792. te[ 8 ] = me[ 8 ] * scaleZ;
  3793. te[ 9 ] = me[ 9 ] * scaleZ;
  3794. te[ 10 ] = me[ 10 ] * scaleZ;
  3795. te[ 11 ] = 0;
  3796. te[ 12 ] = 0;
  3797. te[ 13 ] = 0;
  3798. te[ 14 ] = 0;
  3799. te[ 15 ] = 1;
  3800. return this;
  3801. }
  3802. makeRotationFromEuler( euler ) {
  3803. const te = this.elements;
  3804. const x = euler.x, y = euler.y, z = euler.z;
  3805. const a = Math.cos( x ), b = Math.sin( x );
  3806. const c = Math.cos( y ), d = Math.sin( y );
  3807. const e = Math.cos( z ), f = Math.sin( z );
  3808. if ( euler.order === 'XYZ' ) {
  3809. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3810. te[ 0 ] = c * e;
  3811. te[ 4 ] = - c * f;
  3812. te[ 8 ] = d;
  3813. te[ 1 ] = af + be * d;
  3814. te[ 5 ] = ae - bf * d;
  3815. te[ 9 ] = - b * c;
  3816. te[ 2 ] = bf - ae * d;
  3817. te[ 6 ] = be + af * d;
  3818. te[ 10 ] = a * c;
  3819. } else if ( euler.order === 'YXZ' ) {
  3820. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3821. te[ 0 ] = ce + df * b;
  3822. te[ 4 ] = de * b - cf;
  3823. te[ 8 ] = a * d;
  3824. te[ 1 ] = a * f;
  3825. te[ 5 ] = a * e;
  3826. te[ 9 ] = - b;
  3827. te[ 2 ] = cf * b - de;
  3828. te[ 6 ] = df + ce * b;
  3829. te[ 10 ] = a * c;
  3830. } else if ( euler.order === 'ZXY' ) {
  3831. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  3832. te[ 0 ] = ce - df * b;
  3833. te[ 4 ] = - a * f;
  3834. te[ 8 ] = de + cf * b;
  3835. te[ 1 ] = cf + de * b;
  3836. te[ 5 ] = a * e;
  3837. te[ 9 ] = df - ce * b;
  3838. te[ 2 ] = - a * d;
  3839. te[ 6 ] = b;
  3840. te[ 10 ] = a * c;
  3841. } else if ( euler.order === 'ZYX' ) {
  3842. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  3843. te[ 0 ] = c * e;
  3844. te[ 4 ] = be * d - af;
  3845. te[ 8 ] = ae * d + bf;
  3846. te[ 1 ] = c * f;
  3847. te[ 5 ] = bf * d + ae;
  3848. te[ 9 ] = af * d - be;
  3849. te[ 2 ] = - d;
  3850. te[ 6 ] = b * c;
  3851. te[ 10 ] = a * c;
  3852. } else if ( euler.order === 'YZX' ) {
  3853. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3854. te[ 0 ] = c * e;
  3855. te[ 4 ] = bd - ac * f;
  3856. te[ 8 ] = bc * f + ad;
  3857. te[ 1 ] = f;
  3858. te[ 5 ] = a * e;
  3859. te[ 9 ] = - b * e;
  3860. te[ 2 ] = - d * e;
  3861. te[ 6 ] = ad * f + bc;
  3862. te[ 10 ] = ac - bd * f;
  3863. } else if ( euler.order === 'XZY' ) {
  3864. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  3865. te[ 0 ] = c * e;
  3866. te[ 4 ] = - f;
  3867. te[ 8 ] = d * e;
  3868. te[ 1 ] = ac * f + bd;
  3869. te[ 5 ] = a * e;
  3870. te[ 9 ] = ad * f - bc;
  3871. te[ 2 ] = bc * f - ad;
  3872. te[ 6 ] = b * e;
  3873. te[ 10 ] = bd * f + ac;
  3874. }
  3875. // bottom row
  3876. te[ 3 ] = 0;
  3877. te[ 7 ] = 0;
  3878. te[ 11 ] = 0;
  3879. // last column
  3880. te[ 12 ] = 0;
  3881. te[ 13 ] = 0;
  3882. te[ 14 ] = 0;
  3883. te[ 15 ] = 1;
  3884. return this;
  3885. }
  3886. makeRotationFromQuaternion( q ) {
  3887. return this.compose( _zero, q, _one );
  3888. }
  3889. lookAt( eye, target, up ) {
  3890. const te = this.elements;
  3891. _z.subVectors( eye, target );
  3892. if ( _z.lengthSq() === 0 ) {
  3893. // eye and target are in the same position
  3894. _z.z = 1;
  3895. }
  3896. _z.normalize();
  3897. _x.crossVectors( up, _z );
  3898. if ( _x.lengthSq() === 0 ) {
  3899. // up and z are parallel
  3900. if ( Math.abs( up.z ) === 1 ) {
  3901. _z.x += 0.0001;
  3902. } else {
  3903. _z.z += 0.0001;
  3904. }
  3905. _z.normalize();
  3906. _x.crossVectors( up, _z );
  3907. }
  3908. _x.normalize();
  3909. _y.crossVectors( _z, _x );
  3910. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  3911. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  3912. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  3913. return this;
  3914. }
  3915. multiply( m ) {
  3916. return this.multiplyMatrices( this, m );
  3917. }
  3918. premultiply( m ) {
  3919. return this.multiplyMatrices( m, this );
  3920. }
  3921. multiplyMatrices( a, b ) {
  3922. const ae = a.elements;
  3923. const be = b.elements;
  3924. const te = this.elements;
  3925. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3926. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3927. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3928. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3929. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3930. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3931. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3932. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3933. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3934. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3935. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3936. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3937. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3938. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3939. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3940. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3941. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3942. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3943. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3944. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3945. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3946. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3947. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3948. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3949. return this;
  3950. }
  3951. multiplyScalar( s ) {
  3952. const te = this.elements;
  3953. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3954. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3955. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3956. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3957. return this;
  3958. }
  3959. determinant() {
  3960. const te = this.elements;
  3961. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3962. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3963. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3964. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3965. //TODO: make this more efficient
  3966. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3967. return (
  3968. n41 * (
  3969. + n14 * n23 * n32
  3970. - n13 * n24 * n32
  3971. - n14 * n22 * n33
  3972. + n12 * n24 * n33
  3973. + n13 * n22 * n34
  3974. - n12 * n23 * n34
  3975. ) +
  3976. n42 * (
  3977. + n11 * n23 * n34
  3978. - n11 * n24 * n33
  3979. + n14 * n21 * n33
  3980. - n13 * n21 * n34
  3981. + n13 * n24 * n31
  3982. - n14 * n23 * n31
  3983. ) +
  3984. n43 * (
  3985. + n11 * n24 * n32
  3986. - n11 * n22 * n34
  3987. - n14 * n21 * n32
  3988. + n12 * n21 * n34
  3989. + n14 * n22 * n31
  3990. - n12 * n24 * n31
  3991. ) +
  3992. n44 * (
  3993. - n13 * n22 * n31
  3994. - n11 * n23 * n32
  3995. + n11 * n22 * n33
  3996. + n13 * n21 * n32
  3997. - n12 * n21 * n33
  3998. + n12 * n23 * n31
  3999. )
  4000. );
  4001. }
  4002. transpose() {
  4003. const te = this.elements;
  4004. let tmp;
  4005. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  4006. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  4007. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  4008. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  4009. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  4010. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  4011. return this;
  4012. }
  4013. setPosition( x, y, z ) {
  4014. const te = this.elements;
  4015. if ( x.isVector3 ) {
  4016. te[ 12 ] = x.x;
  4017. te[ 13 ] = x.y;
  4018. te[ 14 ] = x.z;
  4019. } else {
  4020. te[ 12 ] = x;
  4021. te[ 13 ] = y;
  4022. te[ 14 ] = z;
  4023. }
  4024. return this;
  4025. }
  4026. invert() {
  4027. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  4028. const te = this.elements,
  4029. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  4030. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  4031. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  4032. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  4033. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  4034. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  4035. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  4036. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  4037. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  4038. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4039. const detInv = 1 / det;
  4040. te[ 0 ] = t11 * detInv;
  4041. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  4042. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  4043. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  4044. te[ 4 ] = t12 * detInv;
  4045. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  4046. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  4047. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  4048. te[ 8 ] = t13 * detInv;
  4049. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  4050. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  4051. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  4052. te[ 12 ] = t14 * detInv;
  4053. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  4054. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  4055. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  4056. return this;
  4057. }
  4058. scale( v ) {
  4059. const te = this.elements;
  4060. const x = v.x, y = v.y, z = v.z;
  4061. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  4062. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  4063. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  4064. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  4065. return this;
  4066. }
  4067. getMaxScaleOnAxis() {
  4068. const te = this.elements;
  4069. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  4070. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  4071. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  4072. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  4073. }
  4074. makeTranslation( x, y, z ) {
  4075. this.set(
  4076. 1, 0, 0, x,
  4077. 0, 1, 0, y,
  4078. 0, 0, 1, z,
  4079. 0, 0, 0, 1
  4080. );
  4081. return this;
  4082. }
  4083. makeRotationX( theta ) {
  4084. const c = Math.cos( theta ), s = Math.sin( theta );
  4085. this.set(
  4086. 1, 0, 0, 0,
  4087. 0, c, - s, 0,
  4088. 0, s, c, 0,
  4089. 0, 0, 0, 1
  4090. );
  4091. return this;
  4092. }
  4093. makeRotationY( theta ) {
  4094. const c = Math.cos( theta ), s = Math.sin( theta );
  4095. this.set(
  4096. c, 0, s, 0,
  4097. 0, 1, 0, 0,
  4098. - s, 0, c, 0,
  4099. 0, 0, 0, 1
  4100. );
  4101. return this;
  4102. }
  4103. makeRotationZ( theta ) {
  4104. const c = Math.cos( theta ), s = Math.sin( theta );
  4105. this.set(
  4106. c, - s, 0, 0,
  4107. s, c, 0, 0,
  4108. 0, 0, 1, 0,
  4109. 0, 0, 0, 1
  4110. );
  4111. return this;
  4112. }
  4113. makeRotationAxis( axis, angle ) {
  4114. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  4115. const c = Math.cos( angle );
  4116. const s = Math.sin( angle );
  4117. const t = 1 - c;
  4118. const x = axis.x, y = axis.y, z = axis.z;
  4119. const tx = t * x, ty = t * y;
  4120. this.set(
  4121. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  4122. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  4123. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  4124. 0, 0, 0, 1
  4125. );
  4126. return this;
  4127. }
  4128. makeScale( x, y, z ) {
  4129. this.set(
  4130. x, 0, 0, 0,
  4131. 0, y, 0, 0,
  4132. 0, 0, z, 0,
  4133. 0, 0, 0, 1
  4134. );
  4135. return this;
  4136. }
  4137. makeShear( xy, xz, yx, yz, zx, zy ) {
  4138. this.set(
  4139. 1, yx, zx, 0,
  4140. xy, 1, zy, 0,
  4141. xz, yz, 1, 0,
  4142. 0, 0, 0, 1
  4143. );
  4144. return this;
  4145. }
  4146. compose( position, quaternion, scale ) {
  4147. const te = this.elements;
  4148. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  4149. const x2 = x + x, y2 = y + y, z2 = z + z;
  4150. const xx = x * x2, xy = x * y2, xz = x * z2;
  4151. const yy = y * y2, yz = y * z2, zz = z * z2;
  4152. const wx = w * x2, wy = w * y2, wz = w * z2;
  4153. const sx = scale.x, sy = scale.y, sz = scale.z;
  4154. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  4155. te[ 1 ] = ( xy + wz ) * sx;
  4156. te[ 2 ] = ( xz - wy ) * sx;
  4157. te[ 3 ] = 0;
  4158. te[ 4 ] = ( xy - wz ) * sy;
  4159. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  4160. te[ 6 ] = ( yz + wx ) * sy;
  4161. te[ 7 ] = 0;
  4162. te[ 8 ] = ( xz + wy ) * sz;
  4163. te[ 9 ] = ( yz - wx ) * sz;
  4164. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  4165. te[ 11 ] = 0;
  4166. te[ 12 ] = position.x;
  4167. te[ 13 ] = position.y;
  4168. te[ 14 ] = position.z;
  4169. te[ 15 ] = 1;
  4170. return this;
  4171. }
  4172. decompose( position, quaternion, scale ) {
  4173. const te = this.elements;
  4174. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  4175. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  4176. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  4177. // if determine is negative, we need to invert one scale
  4178. const det = this.determinant();
  4179. if ( det < 0 ) sx = - sx;
  4180. position.x = te[ 12 ];
  4181. position.y = te[ 13 ];
  4182. position.z = te[ 14 ];
  4183. // scale the rotation part
  4184. _m1$2.copy( this );
  4185. const invSX = 1 / sx;
  4186. const invSY = 1 / sy;
  4187. const invSZ = 1 / sz;
  4188. _m1$2.elements[ 0 ] *= invSX;
  4189. _m1$2.elements[ 1 ] *= invSX;
  4190. _m1$2.elements[ 2 ] *= invSX;
  4191. _m1$2.elements[ 4 ] *= invSY;
  4192. _m1$2.elements[ 5 ] *= invSY;
  4193. _m1$2.elements[ 6 ] *= invSY;
  4194. _m1$2.elements[ 8 ] *= invSZ;
  4195. _m1$2.elements[ 9 ] *= invSZ;
  4196. _m1$2.elements[ 10 ] *= invSZ;
  4197. quaternion.setFromRotationMatrix( _m1$2 );
  4198. scale.x = sx;
  4199. scale.y = sy;
  4200. scale.z = sz;
  4201. return this;
  4202. }
  4203. makePerspective( left, right, top, bottom, near, far ) {
  4204. const te = this.elements;
  4205. const x = 2 * near / ( right - left );
  4206. const y = 2 * near / ( top - bottom );
  4207. const a = ( right + left ) / ( right - left );
  4208. const b = ( top + bottom ) / ( top - bottom );
  4209. const c = - ( far + near ) / ( far - near );
  4210. const d = - 2 * far * near / ( far - near );
  4211. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  4212. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  4213. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  4214. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  4215. return this;
  4216. }
  4217. makeOrthographic( left, right, top, bottom, near, far ) {
  4218. const te = this.elements;
  4219. const w = 1.0 / ( right - left );
  4220. const h = 1.0 / ( top - bottom );
  4221. const p = 1.0 / ( far - near );
  4222. const x = ( right + left ) * w;
  4223. const y = ( top + bottom ) * h;
  4224. const z = ( far + near ) * p;
  4225. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  4226. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  4227. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  4228. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  4229. return this;
  4230. }
  4231. equals( matrix ) {
  4232. const te = this.elements;
  4233. const me = matrix.elements;
  4234. for ( let i = 0; i < 16; i ++ ) {
  4235. if ( te[ i ] !== me[ i ] ) return false;
  4236. }
  4237. return true;
  4238. }
  4239. fromArray( array, offset = 0 ) {
  4240. for ( let i = 0; i < 16; i ++ ) {
  4241. this.elements[ i ] = array[ i + offset ];
  4242. }
  4243. return this;
  4244. }
  4245. toArray( array = [], offset = 0 ) {
  4246. const te = this.elements;
  4247. array[ offset ] = te[ 0 ];
  4248. array[ offset + 1 ] = te[ 1 ];
  4249. array[ offset + 2 ] = te[ 2 ];
  4250. array[ offset + 3 ] = te[ 3 ];
  4251. array[ offset + 4 ] = te[ 4 ];
  4252. array[ offset + 5 ] = te[ 5 ];
  4253. array[ offset + 6 ] = te[ 6 ];
  4254. array[ offset + 7 ] = te[ 7 ];
  4255. array[ offset + 8 ] = te[ 8 ];
  4256. array[ offset + 9 ] = te[ 9 ];
  4257. array[ offset + 10 ] = te[ 10 ];
  4258. array[ offset + 11 ] = te[ 11 ];
  4259. array[ offset + 12 ] = te[ 12 ];
  4260. array[ offset + 13 ] = te[ 13 ];
  4261. array[ offset + 14 ] = te[ 14 ];
  4262. array[ offset + 15 ] = te[ 15 ];
  4263. return array;
  4264. }
  4265. }
  4266. const _v1$5 = /*@__PURE__*/ new Vector3();
  4267. const _m1$2 = /*@__PURE__*/ new Matrix4();
  4268. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  4269. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  4270. const _x = /*@__PURE__*/ new Vector3();
  4271. const _y = /*@__PURE__*/ new Vector3();
  4272. const _z = /*@__PURE__*/ new Vector3();
  4273. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  4274. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  4275. class Euler {
  4276. constructor( x = 0, y = 0, z = 0, order = Euler.DefaultOrder ) {
  4277. this.isEuler = true;
  4278. this._x = x;
  4279. this._y = y;
  4280. this._z = z;
  4281. this._order = order;
  4282. }
  4283. get x() {
  4284. return this._x;
  4285. }
  4286. set x( value ) {
  4287. this._x = value;
  4288. this._onChangeCallback();
  4289. }
  4290. get y() {
  4291. return this._y;
  4292. }
  4293. set y( value ) {
  4294. this._y = value;
  4295. this._onChangeCallback();
  4296. }
  4297. get z() {
  4298. return this._z;
  4299. }
  4300. set z( value ) {
  4301. this._z = value;
  4302. this._onChangeCallback();
  4303. }
  4304. get order() {
  4305. return this._order;
  4306. }
  4307. set order( value ) {
  4308. this._order = value;
  4309. this._onChangeCallback();
  4310. }
  4311. set( x, y, z, order = this._order ) {
  4312. this._x = x;
  4313. this._y = y;
  4314. this._z = z;
  4315. this._order = order;
  4316. this._onChangeCallback();
  4317. return this;
  4318. }
  4319. clone() {
  4320. return new this.constructor( this._x, this._y, this._z, this._order );
  4321. }
  4322. copy( euler ) {
  4323. this._x = euler._x;
  4324. this._y = euler._y;
  4325. this._z = euler._z;
  4326. this._order = euler._order;
  4327. this._onChangeCallback();
  4328. return this;
  4329. }
  4330. setFromRotationMatrix( m, order = this._order, update = true ) {
  4331. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4332. const te = m.elements;
  4333. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  4334. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  4335. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  4336. switch ( order ) {
  4337. case 'XYZ':
  4338. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  4339. if ( Math.abs( m13 ) < 0.9999999 ) {
  4340. this._x = Math.atan2( - m23, m33 );
  4341. this._z = Math.atan2( - m12, m11 );
  4342. } else {
  4343. this._x = Math.atan2( m32, m22 );
  4344. this._z = 0;
  4345. }
  4346. break;
  4347. case 'YXZ':
  4348. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  4349. if ( Math.abs( m23 ) < 0.9999999 ) {
  4350. this._y = Math.atan2( m13, m33 );
  4351. this._z = Math.atan2( m21, m22 );
  4352. } else {
  4353. this._y = Math.atan2( - m31, m11 );
  4354. this._z = 0;
  4355. }
  4356. break;
  4357. case 'ZXY':
  4358. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  4359. if ( Math.abs( m32 ) < 0.9999999 ) {
  4360. this._y = Math.atan2( - m31, m33 );
  4361. this._z = Math.atan2( - m12, m22 );
  4362. } else {
  4363. this._y = 0;
  4364. this._z = Math.atan2( m21, m11 );
  4365. }
  4366. break;
  4367. case 'ZYX':
  4368. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  4369. if ( Math.abs( m31 ) < 0.9999999 ) {
  4370. this._x = Math.atan2( m32, m33 );
  4371. this._z = Math.atan2( m21, m11 );
  4372. } else {
  4373. this._x = 0;
  4374. this._z = Math.atan2( - m12, m22 );
  4375. }
  4376. break;
  4377. case 'YZX':
  4378. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  4379. if ( Math.abs( m21 ) < 0.9999999 ) {
  4380. this._x = Math.atan2( - m23, m22 );
  4381. this._y = Math.atan2( - m31, m11 );
  4382. } else {
  4383. this._x = 0;
  4384. this._y = Math.atan2( m13, m33 );
  4385. }
  4386. break;
  4387. case 'XZY':
  4388. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  4389. if ( Math.abs( m12 ) < 0.9999999 ) {
  4390. this._x = Math.atan2( m32, m22 );
  4391. this._y = Math.atan2( m13, m11 );
  4392. } else {
  4393. this._x = Math.atan2( - m23, m33 );
  4394. this._y = 0;
  4395. }
  4396. break;
  4397. default:
  4398. console.warn( 'THREE.Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  4399. }
  4400. this._order = order;
  4401. if ( update === true ) this._onChangeCallback();
  4402. return this;
  4403. }
  4404. setFromQuaternion( q, order, update ) {
  4405. _matrix$1.makeRotationFromQuaternion( q );
  4406. return this.setFromRotationMatrix( _matrix$1, order, update );
  4407. }
  4408. setFromVector3( v, order = this._order ) {
  4409. return this.set( v.x, v.y, v.z, order );
  4410. }
  4411. reorder( newOrder ) {
  4412. // WARNING: this discards revolution information -bhouston
  4413. _quaternion$3.setFromEuler( this );
  4414. return this.setFromQuaternion( _quaternion$3, newOrder );
  4415. }
  4416. equals( euler ) {
  4417. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  4418. }
  4419. fromArray( array ) {
  4420. this._x = array[ 0 ];
  4421. this._y = array[ 1 ];
  4422. this._z = array[ 2 ];
  4423. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  4424. this._onChangeCallback();
  4425. return this;
  4426. }
  4427. toArray( array = [], offset = 0 ) {
  4428. array[ offset ] = this._x;
  4429. array[ offset + 1 ] = this._y;
  4430. array[ offset + 2 ] = this._z;
  4431. array[ offset + 3 ] = this._order;
  4432. return array;
  4433. }
  4434. _onChange( callback ) {
  4435. this._onChangeCallback = callback;
  4436. return this;
  4437. }
  4438. _onChangeCallback() {}
  4439. *[ Symbol.iterator ]() {
  4440. yield this._x;
  4441. yield this._y;
  4442. yield this._z;
  4443. yield this._order;
  4444. }
  4445. // @deprecated since r138, 02cf0df1cb4575d5842fef9c85bb5a89fe020d53
  4446. toVector3() {
  4447. console.error( 'THREE.Euler: .toVector3() has been removed. Use Vector3.setFromEuler() instead' );
  4448. }
  4449. }
  4450. Euler.DefaultOrder = 'XYZ';
  4451. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  4452. class Layers {
  4453. constructor() {
  4454. this.mask = 1 | 0;
  4455. }
  4456. set( channel ) {
  4457. this.mask = ( 1 << channel | 0 ) >>> 0;
  4458. }
  4459. enable( channel ) {
  4460. this.mask |= 1 << channel | 0;
  4461. }
  4462. enableAll() {
  4463. this.mask = 0xffffffff | 0;
  4464. }
  4465. toggle( channel ) {
  4466. this.mask ^= 1 << channel | 0;
  4467. }
  4468. disable( channel ) {
  4469. this.mask &= ~ ( 1 << channel | 0 );
  4470. }
  4471. disableAll() {
  4472. this.mask = 0;
  4473. }
  4474. test( layers ) {
  4475. return ( this.mask & layers.mask ) !== 0;
  4476. }
  4477. isEnabled( channel ) {
  4478. return ( this.mask & ( 1 << channel | 0 ) ) !== 0;
  4479. }
  4480. }
  4481. let _object3DId = 0;
  4482. const _v1$4 = /*@__PURE__*/ new Vector3();
  4483. const _q1 = /*@__PURE__*/ new Quaternion();
  4484. const _m1$1 = /*@__PURE__*/ new Matrix4();
  4485. const _target = /*@__PURE__*/ new Vector3();
  4486. const _position$3 = /*@__PURE__*/ new Vector3();
  4487. const _scale$2 = /*@__PURE__*/ new Vector3();
  4488. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  4489. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  4490. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4491. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  4492. const _addedEvent = { type: 'added' };
  4493. const _removedEvent = { type: 'removed' };
  4494. class Object3D extends EventDispatcher {
  4495. constructor() {
  4496. super();
  4497. this.isObject3D = true;
  4498. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  4499. this.uuid = generateUUID();
  4500. this.name = '';
  4501. this.type = 'Object3D';
  4502. this.parent = null;
  4503. this.children = [];
  4504. this.up = Object3D.DefaultUp.clone();
  4505. const position = new Vector3();
  4506. const rotation = new Euler();
  4507. const quaternion = new Quaternion();
  4508. const scale = new Vector3( 1, 1, 1 );
  4509. function onRotationChange() {
  4510. quaternion.setFromEuler( rotation, false );
  4511. }
  4512. function onQuaternionChange() {
  4513. rotation.setFromQuaternion( quaternion, undefined, false );
  4514. }
  4515. rotation._onChange( onRotationChange );
  4516. quaternion._onChange( onQuaternionChange );
  4517. Object.defineProperties( this, {
  4518. position: {
  4519. configurable: true,
  4520. enumerable: true,
  4521. value: position
  4522. },
  4523. rotation: {
  4524. configurable: true,
  4525. enumerable: true,
  4526. value: rotation
  4527. },
  4528. quaternion: {
  4529. configurable: true,
  4530. enumerable: true,
  4531. value: quaternion
  4532. },
  4533. scale: {
  4534. configurable: true,
  4535. enumerable: true,
  4536. value: scale
  4537. },
  4538. modelViewMatrix: {
  4539. value: new Matrix4()
  4540. },
  4541. normalMatrix: {
  4542. value: new Matrix3()
  4543. }
  4544. } );
  4545. this.matrix = new Matrix4();
  4546. this.matrixWorld = new Matrix4();
  4547. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  4548. this.matrixWorldNeedsUpdate = false;
  4549. this.layers = new Layers();
  4550. this.visible = true;
  4551. this.castShadow = false;
  4552. this.receiveShadow = false;
  4553. this.frustumCulled = true;
  4554. this.renderOrder = 0;
  4555. this.animations = [];
  4556. this.userData = {};
  4557. }
  4558. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4559. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  4560. applyMatrix4( matrix ) {
  4561. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4562. this.matrix.premultiply( matrix );
  4563. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4564. }
  4565. applyQuaternion( q ) {
  4566. this.quaternion.premultiply( q );
  4567. return this;
  4568. }
  4569. setRotationFromAxisAngle( axis, angle ) {
  4570. // assumes axis is normalized
  4571. this.quaternion.setFromAxisAngle( axis, angle );
  4572. }
  4573. setRotationFromEuler( euler ) {
  4574. this.quaternion.setFromEuler( euler, true );
  4575. }
  4576. setRotationFromMatrix( m ) {
  4577. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4578. this.quaternion.setFromRotationMatrix( m );
  4579. }
  4580. setRotationFromQuaternion( q ) {
  4581. // assumes q is normalized
  4582. this.quaternion.copy( q );
  4583. }
  4584. rotateOnAxis( axis, angle ) {
  4585. // rotate object on axis in object space
  4586. // axis is assumed to be normalized
  4587. _q1.setFromAxisAngle( axis, angle );
  4588. this.quaternion.multiply( _q1 );
  4589. return this;
  4590. }
  4591. rotateOnWorldAxis( axis, angle ) {
  4592. // rotate object on axis in world space
  4593. // axis is assumed to be normalized
  4594. // method assumes no rotated parent
  4595. _q1.setFromAxisAngle( axis, angle );
  4596. this.quaternion.premultiply( _q1 );
  4597. return this;
  4598. }
  4599. rotateX( angle ) {
  4600. return this.rotateOnAxis( _xAxis, angle );
  4601. }
  4602. rotateY( angle ) {
  4603. return this.rotateOnAxis( _yAxis, angle );
  4604. }
  4605. rotateZ( angle ) {
  4606. return this.rotateOnAxis( _zAxis, angle );
  4607. }
  4608. translateOnAxis( axis, distance ) {
  4609. // translate object by distance along axis in object space
  4610. // axis is assumed to be normalized
  4611. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  4612. this.position.add( _v1$4.multiplyScalar( distance ) );
  4613. return this;
  4614. }
  4615. translateX( distance ) {
  4616. return this.translateOnAxis( _xAxis, distance );
  4617. }
  4618. translateY( distance ) {
  4619. return this.translateOnAxis( _yAxis, distance );
  4620. }
  4621. translateZ( distance ) {
  4622. return this.translateOnAxis( _zAxis, distance );
  4623. }
  4624. localToWorld( vector ) {
  4625. return vector.applyMatrix4( this.matrixWorld );
  4626. }
  4627. worldToLocal( vector ) {
  4628. return vector.applyMatrix4( _m1$1.copy( this.matrixWorld ).invert() );
  4629. }
  4630. lookAt( x, y, z ) {
  4631. // This method does not support objects having non-uniformly-scaled parent(s)
  4632. if ( x.isVector3 ) {
  4633. _target.copy( x );
  4634. } else {
  4635. _target.set( x, y, z );
  4636. }
  4637. const parent = this.parent;
  4638. this.updateWorldMatrix( true, false );
  4639. _position$3.setFromMatrixPosition( this.matrixWorld );
  4640. if ( this.isCamera || this.isLight ) {
  4641. _m1$1.lookAt( _position$3, _target, this.up );
  4642. } else {
  4643. _m1$1.lookAt( _target, _position$3, this.up );
  4644. }
  4645. this.quaternion.setFromRotationMatrix( _m1$1 );
  4646. if ( parent ) {
  4647. _m1$1.extractRotation( parent.matrixWorld );
  4648. _q1.setFromRotationMatrix( _m1$1 );
  4649. this.quaternion.premultiply( _q1.invert() );
  4650. }
  4651. }
  4652. add( object ) {
  4653. if ( arguments.length > 1 ) {
  4654. for ( let i = 0; i < arguments.length; i ++ ) {
  4655. this.add( arguments[ i ] );
  4656. }
  4657. return this;
  4658. }
  4659. if ( object === this ) {
  4660. console.error( 'THREE.Object3D.add: object can\'t be added as a child of itself.', object );
  4661. return this;
  4662. }
  4663. if ( object && object.isObject3D ) {
  4664. if ( object.parent !== null ) {
  4665. object.parent.remove( object );
  4666. }
  4667. object.parent = this;
  4668. this.children.push( object );
  4669. object.dispatchEvent( _addedEvent );
  4670. } else {
  4671. console.error( 'THREE.Object3D.add: object not an instance of THREE.Object3D.', object );
  4672. }
  4673. return this;
  4674. }
  4675. remove( object ) {
  4676. if ( arguments.length > 1 ) {
  4677. for ( let i = 0; i < arguments.length; i ++ ) {
  4678. this.remove( arguments[ i ] );
  4679. }
  4680. return this;
  4681. }
  4682. const index = this.children.indexOf( object );
  4683. if ( index !== - 1 ) {
  4684. object.parent = null;
  4685. this.children.splice( index, 1 );
  4686. object.dispatchEvent( _removedEvent );
  4687. }
  4688. return this;
  4689. }
  4690. removeFromParent() {
  4691. const parent = this.parent;
  4692. if ( parent !== null ) {
  4693. parent.remove( this );
  4694. }
  4695. return this;
  4696. }
  4697. clear() {
  4698. for ( let i = 0; i < this.children.length; i ++ ) {
  4699. const object = this.children[ i ];
  4700. object.parent = null;
  4701. object.dispatchEvent( _removedEvent );
  4702. }
  4703. this.children.length = 0;
  4704. return this;
  4705. }
  4706. attach( object ) {
  4707. // adds object as a child of this, while maintaining the object's world transform
  4708. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  4709. this.updateWorldMatrix( true, false );
  4710. _m1$1.copy( this.matrixWorld ).invert();
  4711. if ( object.parent !== null ) {
  4712. object.parent.updateWorldMatrix( true, false );
  4713. _m1$1.multiply( object.parent.matrixWorld );
  4714. }
  4715. object.applyMatrix4( _m1$1 );
  4716. this.add( object );
  4717. object.updateWorldMatrix( false, true );
  4718. return this;
  4719. }
  4720. getObjectById( id ) {
  4721. return this.getObjectByProperty( 'id', id );
  4722. }
  4723. getObjectByName( name ) {
  4724. return this.getObjectByProperty( 'name', name );
  4725. }
  4726. getObjectByProperty( name, value ) {
  4727. if ( this[ name ] === value ) return this;
  4728. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  4729. const child = this.children[ i ];
  4730. const object = child.getObjectByProperty( name, value );
  4731. if ( object !== undefined ) {
  4732. return object;
  4733. }
  4734. }
  4735. return undefined;
  4736. }
  4737. getWorldPosition( target ) {
  4738. this.updateWorldMatrix( true, false );
  4739. return target.setFromMatrixPosition( this.matrixWorld );
  4740. }
  4741. getWorldQuaternion( target ) {
  4742. this.updateWorldMatrix( true, false );
  4743. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  4744. return target;
  4745. }
  4746. getWorldScale( target ) {
  4747. this.updateWorldMatrix( true, false );
  4748. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  4749. return target;
  4750. }
  4751. getWorldDirection( target ) {
  4752. this.updateWorldMatrix( true, false );
  4753. const e = this.matrixWorld.elements;
  4754. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  4755. }
  4756. raycast( /* raycaster, intersects */ ) {}
  4757. traverse( callback ) {
  4758. callback( this );
  4759. const children = this.children;
  4760. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4761. children[ i ].traverse( callback );
  4762. }
  4763. }
  4764. traverseVisible( callback ) {
  4765. if ( this.visible === false ) return;
  4766. callback( this );
  4767. const children = this.children;
  4768. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4769. children[ i ].traverseVisible( callback );
  4770. }
  4771. }
  4772. traverseAncestors( callback ) {
  4773. const parent = this.parent;
  4774. if ( parent !== null ) {
  4775. callback( parent );
  4776. parent.traverseAncestors( callback );
  4777. }
  4778. }
  4779. updateMatrix() {
  4780. this.matrix.compose( this.position, this.quaternion, this.scale );
  4781. this.matrixWorldNeedsUpdate = true;
  4782. }
  4783. updateMatrixWorld( force ) {
  4784. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4785. if ( this.matrixWorldNeedsUpdate || force ) {
  4786. if ( this.parent === null ) {
  4787. this.matrixWorld.copy( this.matrix );
  4788. } else {
  4789. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4790. }
  4791. this.matrixWorldNeedsUpdate = false;
  4792. force = true;
  4793. }
  4794. // update children
  4795. const children = this.children;
  4796. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4797. children[ i ].updateMatrixWorld( force );
  4798. }
  4799. }
  4800. updateWorldMatrix( updateParents, updateChildren ) {
  4801. const parent = this.parent;
  4802. if ( updateParents === true && parent !== null ) {
  4803. parent.updateWorldMatrix( true, false );
  4804. }
  4805. if ( this.matrixAutoUpdate ) this.updateMatrix();
  4806. if ( this.parent === null ) {
  4807. this.matrixWorld.copy( this.matrix );
  4808. } else {
  4809. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4810. }
  4811. // update children
  4812. if ( updateChildren === true ) {
  4813. const children = this.children;
  4814. for ( let i = 0, l = children.length; i < l; i ++ ) {
  4815. children[ i ].updateWorldMatrix( false, true );
  4816. }
  4817. }
  4818. }
  4819. toJSON( meta ) {
  4820. // meta is a string when called from JSON.stringify
  4821. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  4822. const output = {};
  4823. // meta is a hash used to collect geometries, materials.
  4824. // not providing it implies that this is the root object
  4825. // being serialized.
  4826. if ( isRootObject ) {
  4827. // initialize meta obj
  4828. meta = {
  4829. geometries: {},
  4830. materials: {},
  4831. textures: {},
  4832. images: {},
  4833. shapes: {},
  4834. skeletons: {},
  4835. animations: {},
  4836. nodes: {}
  4837. };
  4838. output.metadata = {
  4839. version: 4.5,
  4840. type: 'Object',
  4841. generator: 'Object3D.toJSON'
  4842. };
  4843. }
  4844. // standard Object3D serialization
  4845. const object = {};
  4846. object.uuid = this.uuid;
  4847. object.type = this.type;
  4848. if ( this.name !== '' ) object.name = this.name;
  4849. if ( this.castShadow === true ) object.castShadow = true;
  4850. if ( this.receiveShadow === true ) object.receiveShadow = true;
  4851. if ( this.visible === false ) object.visible = false;
  4852. if ( this.frustumCulled === false ) object.frustumCulled = false;
  4853. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  4854. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  4855. object.layers = this.layers.mask;
  4856. object.matrix = this.matrix.toArray();
  4857. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  4858. // object specific properties
  4859. if ( this.isInstancedMesh ) {
  4860. object.type = 'InstancedMesh';
  4861. object.count = this.count;
  4862. object.instanceMatrix = this.instanceMatrix.toJSON();
  4863. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  4864. }
  4865. //
  4866. function serialize( library, element ) {
  4867. if ( library[ element.uuid ] === undefined ) {
  4868. library[ element.uuid ] = element.toJSON( meta );
  4869. }
  4870. return element.uuid;
  4871. }
  4872. if ( this.isScene ) {
  4873. if ( this.background ) {
  4874. if ( this.background.isColor ) {
  4875. object.background = this.background.toJSON();
  4876. } else if ( this.background.isTexture ) {
  4877. object.background = this.background.toJSON( meta ).uuid;
  4878. }
  4879. }
  4880. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  4881. object.environment = this.environment.toJSON( meta ).uuid;
  4882. }
  4883. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  4884. object.geometry = serialize( meta.geometries, this.geometry );
  4885. const parameters = this.geometry.parameters;
  4886. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  4887. const shapes = parameters.shapes;
  4888. if ( Array.isArray( shapes ) ) {
  4889. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  4890. const shape = shapes[ i ];
  4891. serialize( meta.shapes, shape );
  4892. }
  4893. } else {
  4894. serialize( meta.shapes, shapes );
  4895. }
  4896. }
  4897. }
  4898. if ( this.isSkinnedMesh ) {
  4899. object.bindMode = this.bindMode;
  4900. object.bindMatrix = this.bindMatrix.toArray();
  4901. if ( this.skeleton !== undefined ) {
  4902. serialize( meta.skeletons, this.skeleton );
  4903. object.skeleton = this.skeleton.uuid;
  4904. }
  4905. }
  4906. if ( this.material !== undefined ) {
  4907. if ( Array.isArray( this.material ) ) {
  4908. const uuids = [];
  4909. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  4910. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  4911. }
  4912. object.material = uuids;
  4913. } else {
  4914. object.material = serialize( meta.materials, this.material );
  4915. }
  4916. }
  4917. //
  4918. if ( this.children.length > 0 ) {
  4919. object.children = [];
  4920. for ( let i = 0; i < this.children.length; i ++ ) {
  4921. object.children.push( this.children[ i ].toJSON( meta ).object );
  4922. }
  4923. }
  4924. //
  4925. if ( this.animations.length > 0 ) {
  4926. object.animations = [];
  4927. for ( let i = 0; i < this.animations.length; i ++ ) {
  4928. const animation = this.animations[ i ];
  4929. object.animations.push( serialize( meta.animations, animation ) );
  4930. }
  4931. }
  4932. if ( isRootObject ) {
  4933. const geometries = extractFromCache( meta.geometries );
  4934. const materials = extractFromCache( meta.materials );
  4935. const textures = extractFromCache( meta.textures );
  4936. const images = extractFromCache( meta.images );
  4937. const shapes = extractFromCache( meta.shapes );
  4938. const skeletons = extractFromCache( meta.skeletons );
  4939. const animations = extractFromCache( meta.animations );
  4940. const nodes = extractFromCache( meta.nodes );
  4941. if ( geometries.length > 0 ) output.geometries = geometries;
  4942. if ( materials.length > 0 ) output.materials = materials;
  4943. if ( textures.length > 0 ) output.textures = textures;
  4944. if ( images.length > 0 ) output.images = images;
  4945. if ( shapes.length > 0 ) output.shapes = shapes;
  4946. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  4947. if ( animations.length > 0 ) output.animations = animations;
  4948. if ( nodes.length > 0 ) output.nodes = nodes;
  4949. }
  4950. output.object = object;
  4951. return output;
  4952. // extract data from the cache hash
  4953. // remove metadata on each item
  4954. // and return as array
  4955. function extractFromCache( cache ) {
  4956. const values = [];
  4957. for ( const key in cache ) {
  4958. const data = cache[ key ];
  4959. delete data.metadata;
  4960. values.push( data );
  4961. }
  4962. return values;
  4963. }
  4964. }
  4965. clone( recursive ) {
  4966. return new this.constructor().copy( this, recursive );
  4967. }
  4968. copy( source, recursive = true ) {
  4969. this.name = source.name;
  4970. this.up.copy( source.up );
  4971. this.position.copy( source.position );
  4972. this.rotation.order = source.rotation.order;
  4973. this.quaternion.copy( source.quaternion );
  4974. this.scale.copy( source.scale );
  4975. this.matrix.copy( source.matrix );
  4976. this.matrixWorld.copy( source.matrixWorld );
  4977. this.matrixAutoUpdate = source.matrixAutoUpdate;
  4978. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  4979. this.layers.mask = source.layers.mask;
  4980. this.visible = source.visible;
  4981. this.castShadow = source.castShadow;
  4982. this.receiveShadow = source.receiveShadow;
  4983. this.frustumCulled = source.frustumCulled;
  4984. this.renderOrder = source.renderOrder;
  4985. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  4986. if ( recursive === true ) {
  4987. for ( let i = 0; i < source.children.length; i ++ ) {
  4988. const child = source.children[ i ];
  4989. this.add( child.clone() );
  4990. }
  4991. }
  4992. return this;
  4993. }
  4994. }
  4995. Object3D.DefaultUp = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  4996. Object3D.DefaultMatrixAutoUpdate = true;
  4997. const _v0$1 = /*@__PURE__*/ new Vector3();
  4998. const _v1$3 = /*@__PURE__*/ new Vector3();
  4999. const _v2$2 = /*@__PURE__*/ new Vector3();
  5000. const _v3$1 = /*@__PURE__*/ new Vector3();
  5001. const _vab = /*@__PURE__*/ new Vector3();
  5002. const _vac = /*@__PURE__*/ new Vector3();
  5003. const _vbc = /*@__PURE__*/ new Vector3();
  5004. const _vap = /*@__PURE__*/ new Vector3();
  5005. const _vbp = /*@__PURE__*/ new Vector3();
  5006. const _vcp = /*@__PURE__*/ new Vector3();
  5007. class Triangle {
  5008. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  5009. this.a = a;
  5010. this.b = b;
  5011. this.c = c;
  5012. }
  5013. static getNormal( a, b, c, target ) {
  5014. target.subVectors( c, b );
  5015. _v0$1.subVectors( a, b );
  5016. target.cross( _v0$1 );
  5017. const targetLengthSq = target.lengthSq();
  5018. if ( targetLengthSq > 0 ) {
  5019. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  5020. }
  5021. return target.set( 0, 0, 0 );
  5022. }
  5023. // static/instance method to calculate barycentric coordinates
  5024. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  5025. static getBarycoord( point, a, b, c, target ) {
  5026. _v0$1.subVectors( c, a );
  5027. _v1$3.subVectors( b, a );
  5028. _v2$2.subVectors( point, a );
  5029. const dot00 = _v0$1.dot( _v0$1 );
  5030. const dot01 = _v0$1.dot( _v1$3 );
  5031. const dot02 = _v0$1.dot( _v2$2 );
  5032. const dot11 = _v1$3.dot( _v1$3 );
  5033. const dot12 = _v1$3.dot( _v2$2 );
  5034. const denom = ( dot00 * dot11 - dot01 * dot01 );
  5035. // collinear or singular triangle
  5036. if ( denom === 0 ) {
  5037. // arbitrary location outside of triangle?
  5038. // not sure if this is the best idea, maybe should be returning undefined
  5039. return target.set( - 2, - 1, - 1 );
  5040. }
  5041. const invDenom = 1 / denom;
  5042. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  5043. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  5044. // barycentric coordinates must always sum to 1
  5045. return target.set( 1 - u - v, v, u );
  5046. }
  5047. static containsPoint( point, a, b, c ) {
  5048. this.getBarycoord( point, a, b, c, _v3$1 );
  5049. return ( _v3$1.x >= 0 ) && ( _v3$1.y >= 0 ) && ( ( _v3$1.x + _v3$1.y ) <= 1 );
  5050. }
  5051. static getUV( point, p1, p2, p3, uv1, uv2, uv3, target ) {
  5052. this.getBarycoord( point, p1, p2, p3, _v3$1 );
  5053. target.set( 0, 0 );
  5054. target.addScaledVector( uv1, _v3$1.x );
  5055. target.addScaledVector( uv2, _v3$1.y );
  5056. target.addScaledVector( uv3, _v3$1.z );
  5057. return target;
  5058. }
  5059. static isFrontFacing( a, b, c, direction ) {
  5060. _v0$1.subVectors( c, b );
  5061. _v1$3.subVectors( a, b );
  5062. // strictly front facing
  5063. return ( _v0$1.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  5064. }
  5065. set( a, b, c ) {
  5066. this.a.copy( a );
  5067. this.b.copy( b );
  5068. this.c.copy( c );
  5069. return this;
  5070. }
  5071. setFromPointsAndIndices( points, i0, i1, i2 ) {
  5072. this.a.copy( points[ i0 ] );
  5073. this.b.copy( points[ i1 ] );
  5074. this.c.copy( points[ i2 ] );
  5075. return this;
  5076. }
  5077. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  5078. this.a.fromBufferAttribute( attribute, i0 );
  5079. this.b.fromBufferAttribute( attribute, i1 );
  5080. this.c.fromBufferAttribute( attribute, i2 );
  5081. return this;
  5082. }
  5083. clone() {
  5084. return new this.constructor().copy( this );
  5085. }
  5086. copy( triangle ) {
  5087. this.a.copy( triangle.a );
  5088. this.b.copy( triangle.b );
  5089. this.c.copy( triangle.c );
  5090. return this;
  5091. }
  5092. getArea() {
  5093. _v0$1.subVectors( this.c, this.b );
  5094. _v1$3.subVectors( this.a, this.b );
  5095. return _v0$1.cross( _v1$3 ).length() * 0.5;
  5096. }
  5097. getMidpoint( target ) {
  5098. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  5099. }
  5100. getNormal( target ) {
  5101. return Triangle.getNormal( this.a, this.b, this.c, target );
  5102. }
  5103. getPlane( target ) {
  5104. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  5105. }
  5106. getBarycoord( point, target ) {
  5107. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  5108. }
  5109. getUV( point, uv1, uv2, uv3, target ) {
  5110. return Triangle.getUV( point, this.a, this.b, this.c, uv1, uv2, uv3, target );
  5111. }
  5112. containsPoint( point ) {
  5113. return Triangle.containsPoint( point, this.a, this.b, this.c );
  5114. }
  5115. isFrontFacing( direction ) {
  5116. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  5117. }
  5118. intersectsBox( box ) {
  5119. return box.intersectsTriangle( this );
  5120. }
  5121. closestPointToPoint( p, target ) {
  5122. const a = this.a, b = this.b, c = this.c;
  5123. let v, w;
  5124. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  5125. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  5126. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  5127. // basically, we're distinguishing which of the voronoi regions of the triangle
  5128. // the point lies in with the minimum amount of redundant computation.
  5129. _vab.subVectors( b, a );
  5130. _vac.subVectors( c, a );
  5131. _vap.subVectors( p, a );
  5132. const d1 = _vab.dot( _vap );
  5133. const d2 = _vac.dot( _vap );
  5134. if ( d1 <= 0 && d2 <= 0 ) {
  5135. // vertex region of A; barycentric coords (1, 0, 0)
  5136. return target.copy( a );
  5137. }
  5138. _vbp.subVectors( p, b );
  5139. const d3 = _vab.dot( _vbp );
  5140. const d4 = _vac.dot( _vbp );
  5141. if ( d3 >= 0 && d4 <= d3 ) {
  5142. // vertex region of B; barycentric coords (0, 1, 0)
  5143. return target.copy( b );
  5144. }
  5145. const vc = d1 * d4 - d3 * d2;
  5146. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  5147. v = d1 / ( d1 - d3 );
  5148. // edge region of AB; barycentric coords (1-v, v, 0)
  5149. return target.copy( a ).addScaledVector( _vab, v );
  5150. }
  5151. _vcp.subVectors( p, c );
  5152. const d5 = _vab.dot( _vcp );
  5153. const d6 = _vac.dot( _vcp );
  5154. if ( d6 >= 0 && d5 <= d6 ) {
  5155. // vertex region of C; barycentric coords (0, 0, 1)
  5156. return target.copy( c );
  5157. }
  5158. const vb = d5 * d2 - d1 * d6;
  5159. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  5160. w = d2 / ( d2 - d6 );
  5161. // edge region of AC; barycentric coords (1-w, 0, w)
  5162. return target.copy( a ).addScaledVector( _vac, w );
  5163. }
  5164. const va = d3 * d6 - d5 * d4;
  5165. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  5166. _vbc.subVectors( c, b );
  5167. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  5168. // edge region of BC; barycentric coords (0, 1-w, w)
  5169. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  5170. }
  5171. // face region
  5172. const denom = 1 / ( va + vb + vc );
  5173. // u = va * denom
  5174. v = vb * denom;
  5175. w = vc * denom;
  5176. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  5177. }
  5178. equals( triangle ) {
  5179. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  5180. }
  5181. }
  5182. let materialId = 0;
  5183. class Material extends EventDispatcher {
  5184. constructor() {
  5185. super();
  5186. this.isMaterial = true;
  5187. Object.defineProperty( this, 'id', { value: materialId ++ } );
  5188. this.uuid = generateUUID();
  5189. this.name = '';
  5190. this.type = 'Material';
  5191. this.blending = NormalBlending;
  5192. this.side = FrontSide;
  5193. this.vertexColors = false;
  5194. this.opacity = 1;
  5195. this.transparent = false;
  5196. this.blendSrc = SrcAlphaFactor;
  5197. this.blendDst = OneMinusSrcAlphaFactor;
  5198. this.blendEquation = AddEquation;
  5199. this.blendSrcAlpha = null;
  5200. this.blendDstAlpha = null;
  5201. this.blendEquationAlpha = null;
  5202. this.depthFunc = LessEqualDepth;
  5203. this.depthTest = true;
  5204. this.depthWrite = true;
  5205. this.stencilWriteMask = 0xff;
  5206. this.stencilFunc = AlwaysStencilFunc;
  5207. this.stencilRef = 0;
  5208. this.stencilFuncMask = 0xff;
  5209. this.stencilFail = KeepStencilOp;
  5210. this.stencilZFail = KeepStencilOp;
  5211. this.stencilZPass = KeepStencilOp;
  5212. this.stencilWrite = false;
  5213. this.clippingPlanes = null;
  5214. this.clipIntersection = false;
  5215. this.clipShadows = false;
  5216. this.shadowSide = null;
  5217. this.colorWrite = true;
  5218. this.precision = null; // override the renderer's default precision for this material
  5219. this.polygonOffset = false;
  5220. this.polygonOffsetFactor = 0;
  5221. this.polygonOffsetUnits = 0;
  5222. this.dithering = false;
  5223. this.alphaToCoverage = false;
  5224. this.premultipliedAlpha = false;
  5225. this.visible = true;
  5226. this.toneMapped = true;
  5227. this.userData = {};
  5228. this.version = 0;
  5229. this._alphaTest = 0;
  5230. }
  5231. get alphaTest() {
  5232. return this._alphaTest;
  5233. }
  5234. set alphaTest( value ) {
  5235. if ( this._alphaTest > 0 !== value > 0 ) {
  5236. this.version ++;
  5237. }
  5238. this._alphaTest = value;
  5239. }
  5240. onBuild( /* shaderobject, renderer */ ) {}
  5241. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  5242. onBeforeCompile( /* shaderobject, renderer */ ) {}
  5243. customProgramCacheKey() {
  5244. return this.onBeforeCompile.toString();
  5245. }
  5246. setValues( values ) {
  5247. if ( values === undefined ) return;
  5248. for ( const key in values ) {
  5249. const newValue = values[ key ];
  5250. if ( newValue === undefined ) {
  5251. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  5252. continue;
  5253. }
  5254. const currentValue = this[ key ];
  5255. if ( currentValue === undefined ) {
  5256. console.warn( 'THREE.' + this.type + ': \'' + key + '\' is not a property of this material.' );
  5257. continue;
  5258. }
  5259. if ( currentValue && currentValue.isColor ) {
  5260. currentValue.set( newValue );
  5261. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  5262. currentValue.copy( newValue );
  5263. } else {
  5264. this[ key ] = newValue;
  5265. }
  5266. }
  5267. }
  5268. toJSON( meta ) {
  5269. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5270. if ( isRootObject ) {
  5271. meta = {
  5272. textures: {},
  5273. images: {}
  5274. };
  5275. }
  5276. const data = {
  5277. metadata: {
  5278. version: 4.5,
  5279. type: 'Material',
  5280. generator: 'Material.toJSON'
  5281. }
  5282. };
  5283. // standard Material serialization
  5284. data.uuid = this.uuid;
  5285. data.type = this.type;
  5286. if ( this.name !== '' ) data.name = this.name;
  5287. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  5288. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  5289. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  5290. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  5291. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  5292. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  5293. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  5294. if ( this.emissiveIntensity && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  5295. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  5296. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  5297. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  5298. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  5299. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  5300. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  5301. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  5302. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  5303. }
  5304. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  5305. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  5306. }
  5307. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  5308. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  5309. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  5310. }
  5311. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  5312. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  5313. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  5314. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  5315. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  5316. }
  5317. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  5318. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  5319. }
  5320. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  5321. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  5322. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  5323. if ( this.lightMap && this.lightMap.isTexture ) {
  5324. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  5325. data.lightMapIntensity = this.lightMapIntensity;
  5326. }
  5327. if ( this.aoMap && this.aoMap.isTexture ) {
  5328. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  5329. data.aoMapIntensity = this.aoMapIntensity;
  5330. }
  5331. if ( this.bumpMap && this.bumpMap.isTexture ) {
  5332. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  5333. data.bumpScale = this.bumpScale;
  5334. }
  5335. if ( this.normalMap && this.normalMap.isTexture ) {
  5336. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  5337. data.normalMapType = this.normalMapType;
  5338. data.normalScale = this.normalScale.toArray();
  5339. }
  5340. if ( this.displacementMap && this.displacementMap.isTexture ) {
  5341. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  5342. data.displacementScale = this.displacementScale;
  5343. data.displacementBias = this.displacementBias;
  5344. }
  5345. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  5346. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  5347. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  5348. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  5349. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  5350. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  5351. if ( this.envMap && this.envMap.isTexture ) {
  5352. data.envMap = this.envMap.toJSON( meta ).uuid;
  5353. if ( this.combine !== undefined ) data.combine = this.combine;
  5354. }
  5355. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  5356. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  5357. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  5358. if ( this.gradientMap && this.gradientMap.isTexture ) {
  5359. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  5360. }
  5361. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  5362. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  5363. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  5364. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  5365. if ( this.attenuationDistance !== undefined ) data.attenuationDistance = this.attenuationDistance;
  5366. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  5367. if ( this.size !== undefined ) data.size = this.size;
  5368. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  5369. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  5370. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  5371. if ( this.side !== FrontSide ) data.side = this.side;
  5372. if ( this.vertexColors ) data.vertexColors = true;
  5373. if ( this.opacity < 1 ) data.opacity = this.opacity;
  5374. if ( this.transparent === true ) data.transparent = this.transparent;
  5375. data.depthFunc = this.depthFunc;
  5376. data.depthTest = this.depthTest;
  5377. data.depthWrite = this.depthWrite;
  5378. data.colorWrite = this.colorWrite;
  5379. data.stencilWrite = this.stencilWrite;
  5380. data.stencilWriteMask = this.stencilWriteMask;
  5381. data.stencilFunc = this.stencilFunc;
  5382. data.stencilRef = this.stencilRef;
  5383. data.stencilFuncMask = this.stencilFuncMask;
  5384. data.stencilFail = this.stencilFail;
  5385. data.stencilZFail = this.stencilZFail;
  5386. data.stencilZPass = this.stencilZPass;
  5387. // rotation (SpriteMaterial)
  5388. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  5389. if ( this.polygonOffset === true ) data.polygonOffset = true;
  5390. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  5391. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  5392. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  5393. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  5394. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  5395. if ( this.scale !== undefined ) data.scale = this.scale;
  5396. if ( this.dithering === true ) data.dithering = true;
  5397. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  5398. if ( this.alphaToCoverage === true ) data.alphaToCoverage = this.alphaToCoverage;
  5399. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  5400. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  5401. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  5402. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  5403. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  5404. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  5405. if ( this.visible === false ) data.visible = false;
  5406. if ( this.toneMapped === false ) data.toneMapped = false;
  5407. if ( this.fog === false ) data.fog = false;
  5408. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  5409. // TODO: Copied from Object3D.toJSON
  5410. function extractFromCache( cache ) {
  5411. const values = [];
  5412. for ( const key in cache ) {
  5413. const data = cache[ key ];
  5414. delete data.metadata;
  5415. values.push( data );
  5416. }
  5417. return values;
  5418. }
  5419. if ( isRootObject ) {
  5420. const textures = extractFromCache( meta.textures );
  5421. const images = extractFromCache( meta.images );
  5422. if ( textures.length > 0 ) data.textures = textures;
  5423. if ( images.length > 0 ) data.images = images;
  5424. }
  5425. return data;
  5426. }
  5427. clone() {
  5428. return new this.constructor().copy( this );
  5429. }
  5430. copy( source ) {
  5431. this.name = source.name;
  5432. this.blending = source.blending;
  5433. this.side = source.side;
  5434. this.vertexColors = source.vertexColors;
  5435. this.opacity = source.opacity;
  5436. this.transparent = source.transparent;
  5437. this.blendSrc = source.blendSrc;
  5438. this.blendDst = source.blendDst;
  5439. this.blendEquation = source.blendEquation;
  5440. this.blendSrcAlpha = source.blendSrcAlpha;
  5441. this.blendDstAlpha = source.blendDstAlpha;
  5442. this.blendEquationAlpha = source.blendEquationAlpha;
  5443. this.depthFunc = source.depthFunc;
  5444. this.depthTest = source.depthTest;
  5445. this.depthWrite = source.depthWrite;
  5446. this.stencilWriteMask = source.stencilWriteMask;
  5447. this.stencilFunc = source.stencilFunc;
  5448. this.stencilRef = source.stencilRef;
  5449. this.stencilFuncMask = source.stencilFuncMask;
  5450. this.stencilFail = source.stencilFail;
  5451. this.stencilZFail = source.stencilZFail;
  5452. this.stencilZPass = source.stencilZPass;
  5453. this.stencilWrite = source.stencilWrite;
  5454. const srcPlanes = source.clippingPlanes;
  5455. let dstPlanes = null;
  5456. if ( srcPlanes !== null ) {
  5457. const n = srcPlanes.length;
  5458. dstPlanes = new Array( n );
  5459. for ( let i = 0; i !== n; ++ i ) {
  5460. dstPlanes[ i ] = srcPlanes[ i ].clone();
  5461. }
  5462. }
  5463. this.clippingPlanes = dstPlanes;
  5464. this.clipIntersection = source.clipIntersection;
  5465. this.clipShadows = source.clipShadows;
  5466. this.shadowSide = source.shadowSide;
  5467. this.colorWrite = source.colorWrite;
  5468. this.precision = source.precision;
  5469. this.polygonOffset = source.polygonOffset;
  5470. this.polygonOffsetFactor = source.polygonOffsetFactor;
  5471. this.polygonOffsetUnits = source.polygonOffsetUnits;
  5472. this.dithering = source.dithering;
  5473. this.alphaTest = source.alphaTest;
  5474. this.alphaToCoverage = source.alphaToCoverage;
  5475. this.premultipliedAlpha = source.premultipliedAlpha;
  5476. this.visible = source.visible;
  5477. this.toneMapped = source.toneMapped;
  5478. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5479. return this;
  5480. }
  5481. dispose() {
  5482. this.dispatchEvent( { type: 'dispose' } );
  5483. }
  5484. set needsUpdate( value ) {
  5485. if ( value === true ) this.version ++;
  5486. }
  5487. }
  5488. class MeshBasicMaterial extends Material {
  5489. constructor( parameters ) {
  5490. super();
  5491. this.isMeshBasicMaterial = true;
  5492. this.type = 'MeshBasicMaterial';
  5493. this.color = new Color( 0xffffff ); // emissive
  5494. this.map = null;
  5495. this.lightMap = null;
  5496. this.lightMapIntensity = 1.0;
  5497. this.aoMap = null;
  5498. this.aoMapIntensity = 1.0;
  5499. this.specularMap = null;
  5500. this.alphaMap = null;
  5501. this.envMap = null;
  5502. this.combine = MultiplyOperation;
  5503. this.reflectivity = 1;
  5504. this.refractionRatio = 0.98;
  5505. this.wireframe = false;
  5506. this.wireframeLinewidth = 1;
  5507. this.wireframeLinecap = 'round';
  5508. this.wireframeLinejoin = 'round';
  5509. this.fog = true;
  5510. this.setValues( parameters );
  5511. }
  5512. copy( source ) {
  5513. super.copy( source );
  5514. this.color.copy( source.color );
  5515. this.map = source.map;
  5516. this.lightMap = source.lightMap;
  5517. this.lightMapIntensity = source.lightMapIntensity;
  5518. this.aoMap = source.aoMap;
  5519. this.aoMapIntensity = source.aoMapIntensity;
  5520. this.specularMap = source.specularMap;
  5521. this.alphaMap = source.alphaMap;
  5522. this.envMap = source.envMap;
  5523. this.combine = source.combine;
  5524. this.reflectivity = source.reflectivity;
  5525. this.refractionRatio = source.refractionRatio;
  5526. this.wireframe = source.wireframe;
  5527. this.wireframeLinewidth = source.wireframeLinewidth;
  5528. this.wireframeLinecap = source.wireframeLinecap;
  5529. this.wireframeLinejoin = source.wireframeLinejoin;
  5530. this.fog = source.fog;
  5531. return this;
  5532. }
  5533. }
  5534. const _vector$9 = /*@__PURE__*/ new Vector3();
  5535. const _vector2$1 = /*@__PURE__*/ new Vector2();
  5536. class BufferAttribute {
  5537. constructor( array, itemSize, normalized ) {
  5538. if ( Array.isArray( array ) ) {
  5539. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  5540. }
  5541. this.isBufferAttribute = true;
  5542. this.name = '';
  5543. this.array = array;
  5544. this.itemSize = itemSize;
  5545. this.count = array !== undefined ? array.length / itemSize : 0;
  5546. this.normalized = normalized === true;
  5547. this.usage = StaticDrawUsage;
  5548. this.updateRange = { offset: 0, count: - 1 };
  5549. this.version = 0;
  5550. }
  5551. onUploadCallback() {}
  5552. set needsUpdate( value ) {
  5553. if ( value === true ) this.version ++;
  5554. }
  5555. setUsage( value ) {
  5556. this.usage = value;
  5557. return this;
  5558. }
  5559. copy( source ) {
  5560. this.name = source.name;
  5561. this.array = new source.array.constructor( source.array );
  5562. this.itemSize = source.itemSize;
  5563. this.count = source.count;
  5564. this.normalized = source.normalized;
  5565. this.usage = source.usage;
  5566. return this;
  5567. }
  5568. copyAt( index1, attribute, index2 ) {
  5569. index1 *= this.itemSize;
  5570. index2 *= attribute.itemSize;
  5571. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  5572. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5573. }
  5574. return this;
  5575. }
  5576. copyArray( array ) {
  5577. this.array.set( array );
  5578. return this;
  5579. }
  5580. copyColorsArray( colors ) {
  5581. const array = this.array;
  5582. let offset = 0;
  5583. for ( let i = 0, l = colors.length; i < l; i ++ ) {
  5584. let color = colors[ i ];
  5585. if ( color === undefined ) {
  5586. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  5587. color = new Color();
  5588. }
  5589. array[ offset ++ ] = color.r;
  5590. array[ offset ++ ] = color.g;
  5591. array[ offset ++ ] = color.b;
  5592. }
  5593. return this;
  5594. }
  5595. copyVector2sArray( vectors ) {
  5596. const array = this.array;
  5597. let offset = 0;
  5598. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5599. let vector = vectors[ i ];
  5600. if ( vector === undefined ) {
  5601. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  5602. vector = new Vector2();
  5603. }
  5604. array[ offset ++ ] = vector.x;
  5605. array[ offset ++ ] = vector.y;
  5606. }
  5607. return this;
  5608. }
  5609. copyVector3sArray( vectors ) {
  5610. const array = this.array;
  5611. let offset = 0;
  5612. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5613. let vector = vectors[ i ];
  5614. if ( vector === undefined ) {
  5615. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  5616. vector = new Vector3();
  5617. }
  5618. array[ offset ++ ] = vector.x;
  5619. array[ offset ++ ] = vector.y;
  5620. array[ offset ++ ] = vector.z;
  5621. }
  5622. return this;
  5623. }
  5624. copyVector4sArray( vectors ) {
  5625. const array = this.array;
  5626. let offset = 0;
  5627. for ( let i = 0, l = vectors.length; i < l; i ++ ) {
  5628. let vector = vectors[ i ];
  5629. if ( vector === undefined ) {
  5630. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  5631. vector = new Vector4();
  5632. }
  5633. array[ offset ++ ] = vector.x;
  5634. array[ offset ++ ] = vector.y;
  5635. array[ offset ++ ] = vector.z;
  5636. array[ offset ++ ] = vector.w;
  5637. }
  5638. return this;
  5639. }
  5640. applyMatrix3( m ) {
  5641. if ( this.itemSize === 2 ) {
  5642. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5643. _vector2$1.fromBufferAttribute( this, i );
  5644. _vector2$1.applyMatrix3( m );
  5645. this.setXY( i, _vector2$1.x, _vector2$1.y );
  5646. }
  5647. } else if ( this.itemSize === 3 ) {
  5648. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5649. _vector$9.fromBufferAttribute( this, i );
  5650. _vector$9.applyMatrix3( m );
  5651. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5652. }
  5653. }
  5654. return this;
  5655. }
  5656. applyMatrix4( m ) {
  5657. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5658. _vector$9.fromBufferAttribute( this, i );
  5659. _vector$9.applyMatrix4( m );
  5660. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5661. }
  5662. return this;
  5663. }
  5664. applyNormalMatrix( m ) {
  5665. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5666. _vector$9.fromBufferAttribute( this, i );
  5667. _vector$9.applyNormalMatrix( m );
  5668. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5669. }
  5670. return this;
  5671. }
  5672. transformDirection( m ) {
  5673. for ( let i = 0, l = this.count; i < l; i ++ ) {
  5674. _vector$9.fromBufferAttribute( this, i );
  5675. _vector$9.transformDirection( m );
  5676. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  5677. }
  5678. return this;
  5679. }
  5680. set( value, offset = 0 ) {
  5681. this.array.set( value, offset );
  5682. return this;
  5683. }
  5684. getX( index ) {
  5685. return this.array[ index * this.itemSize ];
  5686. }
  5687. setX( index, x ) {
  5688. this.array[ index * this.itemSize ] = x;
  5689. return this;
  5690. }
  5691. getY( index ) {
  5692. return this.array[ index * this.itemSize + 1 ];
  5693. }
  5694. setY( index, y ) {
  5695. this.array[ index * this.itemSize + 1 ] = y;
  5696. return this;
  5697. }
  5698. getZ( index ) {
  5699. return this.array[ index * this.itemSize + 2 ];
  5700. }
  5701. setZ( index, z ) {
  5702. this.array[ index * this.itemSize + 2 ] = z;
  5703. return this;
  5704. }
  5705. getW( index ) {
  5706. return this.array[ index * this.itemSize + 3 ];
  5707. }
  5708. setW( index, w ) {
  5709. this.array[ index * this.itemSize + 3 ] = w;
  5710. return this;
  5711. }
  5712. setXY( index, x, y ) {
  5713. index *= this.itemSize;
  5714. this.array[ index + 0 ] = x;
  5715. this.array[ index + 1 ] = y;
  5716. return this;
  5717. }
  5718. setXYZ( index, x, y, z ) {
  5719. index *= this.itemSize;
  5720. this.array[ index + 0 ] = x;
  5721. this.array[ index + 1 ] = y;
  5722. this.array[ index + 2 ] = z;
  5723. return this;
  5724. }
  5725. setXYZW( index, x, y, z, w ) {
  5726. index *= this.itemSize;
  5727. this.array[ index + 0 ] = x;
  5728. this.array[ index + 1 ] = y;
  5729. this.array[ index + 2 ] = z;
  5730. this.array[ index + 3 ] = w;
  5731. return this;
  5732. }
  5733. onUpload( callback ) {
  5734. this.onUploadCallback = callback;
  5735. return this;
  5736. }
  5737. clone() {
  5738. return new this.constructor( this.array, this.itemSize ).copy( this );
  5739. }
  5740. toJSON() {
  5741. const data = {
  5742. itemSize: this.itemSize,
  5743. type: this.array.constructor.name,
  5744. array: Array.from( this.array ),
  5745. normalized: this.normalized
  5746. };
  5747. if ( this.name !== '' ) data.name = this.name;
  5748. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  5749. if ( this.updateRange.offset !== 0 || this.updateRange.count !== - 1 ) data.updateRange = this.updateRange;
  5750. return data;
  5751. }
  5752. }
  5753. //
  5754. class Int8BufferAttribute extends BufferAttribute {
  5755. constructor( array, itemSize, normalized ) {
  5756. super( new Int8Array( array ), itemSize, normalized );
  5757. }
  5758. }
  5759. class Uint8BufferAttribute extends BufferAttribute {
  5760. constructor( array, itemSize, normalized ) {
  5761. super( new Uint8Array( array ), itemSize, normalized );
  5762. }
  5763. }
  5764. class Uint8ClampedBufferAttribute extends BufferAttribute {
  5765. constructor( array, itemSize, normalized ) {
  5766. super( new Uint8ClampedArray( array ), itemSize, normalized );
  5767. }
  5768. }
  5769. class Int16BufferAttribute extends BufferAttribute {
  5770. constructor( array, itemSize, normalized ) {
  5771. super( new Int16Array( array ), itemSize, normalized );
  5772. }
  5773. }
  5774. class Uint16BufferAttribute extends BufferAttribute {
  5775. constructor( array, itemSize, normalized ) {
  5776. super( new Uint16Array( array ), itemSize, normalized );
  5777. }
  5778. }
  5779. class Int32BufferAttribute extends BufferAttribute {
  5780. constructor( array, itemSize, normalized ) {
  5781. super( new Int32Array( array ), itemSize, normalized );
  5782. }
  5783. }
  5784. class Uint32BufferAttribute extends BufferAttribute {
  5785. constructor( array, itemSize, normalized ) {
  5786. super( new Uint32Array( array ), itemSize, normalized );
  5787. }
  5788. }
  5789. class Float16BufferAttribute extends BufferAttribute {
  5790. constructor( array, itemSize, normalized ) {
  5791. super( new Uint16Array( array ), itemSize, normalized );
  5792. this.isFloat16BufferAttribute = true;
  5793. }
  5794. }
  5795. class Float32BufferAttribute extends BufferAttribute {
  5796. constructor( array, itemSize, normalized ) {
  5797. super( new Float32Array( array ), itemSize, normalized );
  5798. }
  5799. }
  5800. class Float64BufferAttribute extends BufferAttribute {
  5801. constructor( array, itemSize, normalized ) {
  5802. super( new Float64Array( array ), itemSize, normalized );
  5803. }
  5804. }
  5805. let _id$1 = 0;
  5806. const _m1 = /*@__PURE__*/ new Matrix4();
  5807. const _obj = /*@__PURE__*/ new Object3D();
  5808. const _offset = /*@__PURE__*/ new Vector3();
  5809. const _box$1 = /*@__PURE__*/ new Box3();
  5810. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  5811. const _vector$8 = /*@__PURE__*/ new Vector3();
  5812. class BufferGeometry extends EventDispatcher {
  5813. constructor() {
  5814. super();
  5815. this.isBufferGeometry = true;
  5816. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  5817. this.uuid = generateUUID();
  5818. this.name = '';
  5819. this.type = 'BufferGeometry';
  5820. this.index = null;
  5821. this.attributes = {};
  5822. this.morphAttributes = {};
  5823. this.morphTargetsRelative = false;
  5824. this.groups = [];
  5825. this.boundingBox = null;
  5826. this.boundingSphere = null;
  5827. this.drawRange = { start: 0, count: Infinity };
  5828. this.userData = {};
  5829. }
  5830. getIndex() {
  5831. return this.index;
  5832. }
  5833. setIndex( index ) {
  5834. if ( Array.isArray( index ) ) {
  5835. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  5836. } else {
  5837. this.index = index;
  5838. }
  5839. return this;
  5840. }
  5841. getAttribute( name ) {
  5842. return this.attributes[ name ];
  5843. }
  5844. setAttribute( name, attribute ) {
  5845. this.attributes[ name ] = attribute;
  5846. return this;
  5847. }
  5848. deleteAttribute( name ) {
  5849. delete this.attributes[ name ];
  5850. return this;
  5851. }
  5852. hasAttribute( name ) {
  5853. return this.attributes[ name ] !== undefined;
  5854. }
  5855. addGroup( start, count, materialIndex = 0 ) {
  5856. this.groups.push( {
  5857. start: start,
  5858. count: count,
  5859. materialIndex: materialIndex
  5860. } );
  5861. }
  5862. clearGroups() {
  5863. this.groups = [];
  5864. }
  5865. setDrawRange( start, count ) {
  5866. this.drawRange.start = start;
  5867. this.drawRange.count = count;
  5868. }
  5869. applyMatrix4( matrix ) {
  5870. const position = this.attributes.position;
  5871. if ( position !== undefined ) {
  5872. position.applyMatrix4( matrix );
  5873. position.needsUpdate = true;
  5874. }
  5875. const normal = this.attributes.normal;
  5876. if ( normal !== undefined ) {
  5877. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  5878. normal.applyNormalMatrix( normalMatrix );
  5879. normal.needsUpdate = true;
  5880. }
  5881. const tangent = this.attributes.tangent;
  5882. if ( tangent !== undefined ) {
  5883. tangent.transformDirection( matrix );
  5884. tangent.needsUpdate = true;
  5885. }
  5886. if ( this.boundingBox !== null ) {
  5887. this.computeBoundingBox();
  5888. }
  5889. if ( this.boundingSphere !== null ) {
  5890. this.computeBoundingSphere();
  5891. }
  5892. return this;
  5893. }
  5894. applyQuaternion( q ) {
  5895. _m1.makeRotationFromQuaternion( q );
  5896. this.applyMatrix4( _m1 );
  5897. return this;
  5898. }
  5899. rotateX( angle ) {
  5900. // rotate geometry around world x-axis
  5901. _m1.makeRotationX( angle );
  5902. this.applyMatrix4( _m1 );
  5903. return this;
  5904. }
  5905. rotateY( angle ) {
  5906. // rotate geometry around world y-axis
  5907. _m1.makeRotationY( angle );
  5908. this.applyMatrix4( _m1 );
  5909. return this;
  5910. }
  5911. rotateZ( angle ) {
  5912. // rotate geometry around world z-axis
  5913. _m1.makeRotationZ( angle );
  5914. this.applyMatrix4( _m1 );
  5915. return this;
  5916. }
  5917. translate( x, y, z ) {
  5918. // translate geometry
  5919. _m1.makeTranslation( x, y, z );
  5920. this.applyMatrix4( _m1 );
  5921. return this;
  5922. }
  5923. scale( x, y, z ) {
  5924. // scale geometry
  5925. _m1.makeScale( x, y, z );
  5926. this.applyMatrix4( _m1 );
  5927. return this;
  5928. }
  5929. lookAt( vector ) {
  5930. _obj.lookAt( vector );
  5931. _obj.updateMatrix();
  5932. this.applyMatrix4( _obj.matrix );
  5933. return this;
  5934. }
  5935. center() {
  5936. this.computeBoundingBox();
  5937. this.boundingBox.getCenter( _offset ).negate();
  5938. this.translate( _offset.x, _offset.y, _offset.z );
  5939. return this;
  5940. }
  5941. setFromPoints( points ) {
  5942. const position = [];
  5943. for ( let i = 0, l = points.length; i < l; i ++ ) {
  5944. const point = points[ i ];
  5945. position.push( point.x, point.y, point.z || 0 );
  5946. }
  5947. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  5948. return this;
  5949. }
  5950. computeBoundingBox() {
  5951. if ( this.boundingBox === null ) {
  5952. this.boundingBox = new Box3();
  5953. }
  5954. const position = this.attributes.position;
  5955. const morphAttributesPosition = this.morphAttributes.position;
  5956. if ( position && position.isGLBufferAttribute ) {
  5957. console.error( 'THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box. Alternatively set "mesh.frustumCulled" to "false".', this );
  5958. this.boundingBox.set(
  5959. new Vector3( - Infinity, - Infinity, - Infinity ),
  5960. new Vector3( + Infinity, + Infinity, + Infinity )
  5961. );
  5962. return;
  5963. }
  5964. if ( position !== undefined ) {
  5965. this.boundingBox.setFromBufferAttribute( position );
  5966. // process morph attributes if present
  5967. if ( morphAttributesPosition ) {
  5968. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  5969. const morphAttribute = morphAttributesPosition[ i ];
  5970. _box$1.setFromBufferAttribute( morphAttribute );
  5971. if ( this.morphTargetsRelative ) {
  5972. _vector$8.addVectors( this.boundingBox.min, _box$1.min );
  5973. this.boundingBox.expandByPoint( _vector$8 );
  5974. _vector$8.addVectors( this.boundingBox.max, _box$1.max );
  5975. this.boundingBox.expandByPoint( _vector$8 );
  5976. } else {
  5977. this.boundingBox.expandByPoint( _box$1.min );
  5978. this.boundingBox.expandByPoint( _box$1.max );
  5979. }
  5980. }
  5981. }
  5982. } else {
  5983. this.boundingBox.makeEmpty();
  5984. }
  5985. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  5986. console.error( 'THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  5987. }
  5988. }
  5989. computeBoundingSphere() {
  5990. if ( this.boundingSphere === null ) {
  5991. this.boundingSphere = new Sphere();
  5992. }
  5993. const position = this.attributes.position;
  5994. const morphAttributesPosition = this.morphAttributes.position;
  5995. if ( position && position.isGLBufferAttribute ) {
  5996. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere. Alternatively set "mesh.frustumCulled" to "false".', this );
  5997. this.boundingSphere.set( new Vector3(), Infinity );
  5998. return;
  5999. }
  6000. if ( position ) {
  6001. // first, find the center of the bounding sphere
  6002. const center = this.boundingSphere.center;
  6003. _box$1.setFromBufferAttribute( position );
  6004. // process morph attributes if present
  6005. if ( morphAttributesPosition ) {
  6006. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6007. const morphAttribute = morphAttributesPosition[ i ];
  6008. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  6009. if ( this.morphTargetsRelative ) {
  6010. _vector$8.addVectors( _box$1.min, _boxMorphTargets.min );
  6011. _box$1.expandByPoint( _vector$8 );
  6012. _vector$8.addVectors( _box$1.max, _boxMorphTargets.max );
  6013. _box$1.expandByPoint( _vector$8 );
  6014. } else {
  6015. _box$1.expandByPoint( _boxMorphTargets.min );
  6016. _box$1.expandByPoint( _boxMorphTargets.max );
  6017. }
  6018. }
  6019. }
  6020. _box$1.getCenter( center );
  6021. // second, try to find a boundingSphere with a radius smaller than the
  6022. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6023. let maxRadiusSq = 0;
  6024. for ( let i = 0, il = position.count; i < il; i ++ ) {
  6025. _vector$8.fromBufferAttribute( position, i );
  6026. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6027. }
  6028. // process morph attributes if present
  6029. if ( morphAttributesPosition ) {
  6030. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  6031. const morphAttribute = morphAttributesPosition[ i ];
  6032. const morphTargetsRelative = this.morphTargetsRelative;
  6033. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  6034. _vector$8.fromBufferAttribute( morphAttribute, j );
  6035. if ( morphTargetsRelative ) {
  6036. _offset.fromBufferAttribute( position, j );
  6037. _vector$8.add( _offset );
  6038. }
  6039. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  6040. }
  6041. }
  6042. }
  6043. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6044. if ( isNaN( this.boundingSphere.radius ) ) {
  6045. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6046. }
  6047. }
  6048. }
  6049. computeTangents() {
  6050. const index = this.index;
  6051. const attributes = this.attributes;
  6052. // based on http://www.terathon.com/code/tangent.html
  6053. // (per vertex tangents)
  6054. if ( index === null ||
  6055. attributes.position === undefined ||
  6056. attributes.normal === undefined ||
  6057. attributes.uv === undefined ) {
  6058. console.error( 'THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  6059. return;
  6060. }
  6061. const indices = index.array;
  6062. const positions = attributes.position.array;
  6063. const normals = attributes.normal.array;
  6064. const uvs = attributes.uv.array;
  6065. const nVertices = positions.length / 3;
  6066. if ( this.hasAttribute( 'tangent' ) === false ) {
  6067. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  6068. }
  6069. const tangents = this.getAttribute( 'tangent' ).array;
  6070. const tan1 = [], tan2 = [];
  6071. for ( let i = 0; i < nVertices; i ++ ) {
  6072. tan1[ i ] = new Vector3();
  6073. tan2[ i ] = new Vector3();
  6074. }
  6075. const vA = new Vector3(),
  6076. vB = new Vector3(),
  6077. vC = new Vector3(),
  6078. uvA = new Vector2(),
  6079. uvB = new Vector2(),
  6080. uvC = new Vector2(),
  6081. sdir = new Vector3(),
  6082. tdir = new Vector3();
  6083. function handleTriangle( a, b, c ) {
  6084. vA.fromArray( positions, a * 3 );
  6085. vB.fromArray( positions, b * 3 );
  6086. vC.fromArray( positions, c * 3 );
  6087. uvA.fromArray( uvs, a * 2 );
  6088. uvB.fromArray( uvs, b * 2 );
  6089. uvC.fromArray( uvs, c * 2 );
  6090. vB.sub( vA );
  6091. vC.sub( vA );
  6092. uvB.sub( uvA );
  6093. uvC.sub( uvA );
  6094. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  6095. // silently ignore degenerate uv triangles having coincident or colinear vertices
  6096. if ( ! isFinite( r ) ) return;
  6097. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  6098. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  6099. tan1[ a ].add( sdir );
  6100. tan1[ b ].add( sdir );
  6101. tan1[ c ].add( sdir );
  6102. tan2[ a ].add( tdir );
  6103. tan2[ b ].add( tdir );
  6104. tan2[ c ].add( tdir );
  6105. }
  6106. let groups = this.groups;
  6107. if ( groups.length === 0 ) {
  6108. groups = [ {
  6109. start: 0,
  6110. count: indices.length
  6111. } ];
  6112. }
  6113. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6114. const group = groups[ i ];
  6115. const start = group.start;
  6116. const count = group.count;
  6117. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6118. handleTriangle(
  6119. indices[ j + 0 ],
  6120. indices[ j + 1 ],
  6121. indices[ j + 2 ]
  6122. );
  6123. }
  6124. }
  6125. const tmp = new Vector3(), tmp2 = new Vector3();
  6126. const n = new Vector3(), n2 = new Vector3();
  6127. function handleVertex( v ) {
  6128. n.fromArray( normals, v * 3 );
  6129. n2.copy( n );
  6130. const t = tan1[ v ];
  6131. // Gram-Schmidt orthogonalize
  6132. tmp.copy( t );
  6133. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6134. // Calculate handedness
  6135. tmp2.crossVectors( n2, t );
  6136. const test = tmp2.dot( tan2[ v ] );
  6137. const w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6138. tangents[ v * 4 ] = tmp.x;
  6139. tangents[ v * 4 + 1 ] = tmp.y;
  6140. tangents[ v * 4 + 2 ] = tmp.z;
  6141. tangents[ v * 4 + 3 ] = w;
  6142. }
  6143. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  6144. const group = groups[ i ];
  6145. const start = group.start;
  6146. const count = group.count;
  6147. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  6148. handleVertex( indices[ j + 0 ] );
  6149. handleVertex( indices[ j + 1 ] );
  6150. handleVertex( indices[ j + 2 ] );
  6151. }
  6152. }
  6153. }
  6154. computeVertexNormals() {
  6155. const index = this.index;
  6156. const positionAttribute = this.getAttribute( 'position' );
  6157. if ( positionAttribute !== undefined ) {
  6158. let normalAttribute = this.getAttribute( 'normal' );
  6159. if ( normalAttribute === undefined ) {
  6160. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  6161. this.setAttribute( 'normal', normalAttribute );
  6162. } else {
  6163. // reset existing normals to zero
  6164. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  6165. normalAttribute.setXYZ( i, 0, 0, 0 );
  6166. }
  6167. }
  6168. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  6169. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  6170. const cb = new Vector3(), ab = new Vector3();
  6171. // indexed elements
  6172. if ( index ) {
  6173. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  6174. const vA = index.getX( i + 0 );
  6175. const vB = index.getX( i + 1 );
  6176. const vC = index.getX( i + 2 );
  6177. pA.fromBufferAttribute( positionAttribute, vA );
  6178. pB.fromBufferAttribute( positionAttribute, vB );
  6179. pC.fromBufferAttribute( positionAttribute, vC );
  6180. cb.subVectors( pC, pB );
  6181. ab.subVectors( pA, pB );
  6182. cb.cross( ab );
  6183. nA.fromBufferAttribute( normalAttribute, vA );
  6184. nB.fromBufferAttribute( normalAttribute, vB );
  6185. nC.fromBufferAttribute( normalAttribute, vC );
  6186. nA.add( cb );
  6187. nB.add( cb );
  6188. nC.add( cb );
  6189. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  6190. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  6191. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  6192. }
  6193. } else {
  6194. // non-indexed elements (unconnected triangle soup)
  6195. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  6196. pA.fromBufferAttribute( positionAttribute, i + 0 );
  6197. pB.fromBufferAttribute( positionAttribute, i + 1 );
  6198. pC.fromBufferAttribute( positionAttribute, i + 2 );
  6199. cb.subVectors( pC, pB );
  6200. ab.subVectors( pA, pB );
  6201. cb.cross( ab );
  6202. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  6203. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  6204. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  6205. }
  6206. }
  6207. this.normalizeNormals();
  6208. normalAttribute.needsUpdate = true;
  6209. }
  6210. }
  6211. // @deprecated since r144
  6212. merge() {
  6213. console.error( 'THREE.BufferGeometry.merge() has been removed. Use THREE.BufferGeometryUtils.mergeBufferGeometries() instead.' );
  6214. return this;
  6215. }
  6216. normalizeNormals() {
  6217. const normals = this.attributes.normal;
  6218. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  6219. _vector$8.fromBufferAttribute( normals, i );
  6220. _vector$8.normalize();
  6221. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  6222. }
  6223. }
  6224. toNonIndexed() {
  6225. function convertBufferAttribute( attribute, indices ) {
  6226. const array = attribute.array;
  6227. const itemSize = attribute.itemSize;
  6228. const normalized = attribute.normalized;
  6229. const array2 = new array.constructor( indices.length * itemSize );
  6230. let index = 0, index2 = 0;
  6231. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  6232. if ( attribute.isInterleavedBufferAttribute ) {
  6233. index = indices[ i ] * attribute.data.stride + attribute.offset;
  6234. } else {
  6235. index = indices[ i ] * itemSize;
  6236. }
  6237. for ( let j = 0; j < itemSize; j ++ ) {
  6238. array2[ index2 ++ ] = array[ index ++ ];
  6239. }
  6240. }
  6241. return new BufferAttribute( array2, itemSize, normalized );
  6242. }
  6243. //
  6244. if ( this.index === null ) {
  6245. console.warn( 'THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  6246. return this;
  6247. }
  6248. const geometry2 = new BufferGeometry();
  6249. const indices = this.index.array;
  6250. const attributes = this.attributes;
  6251. // attributes
  6252. for ( const name in attributes ) {
  6253. const attribute = attributes[ name ];
  6254. const newAttribute = convertBufferAttribute( attribute, indices );
  6255. geometry2.setAttribute( name, newAttribute );
  6256. }
  6257. // morph attributes
  6258. const morphAttributes = this.morphAttributes;
  6259. for ( const name in morphAttributes ) {
  6260. const morphArray = [];
  6261. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6262. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  6263. const attribute = morphAttribute[ i ];
  6264. const newAttribute = convertBufferAttribute( attribute, indices );
  6265. morphArray.push( newAttribute );
  6266. }
  6267. geometry2.morphAttributes[ name ] = morphArray;
  6268. }
  6269. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  6270. // groups
  6271. const groups = this.groups;
  6272. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6273. const group = groups[ i ];
  6274. geometry2.addGroup( group.start, group.count, group.materialIndex );
  6275. }
  6276. return geometry2;
  6277. }
  6278. toJSON() {
  6279. const data = {
  6280. metadata: {
  6281. version: 4.5,
  6282. type: 'BufferGeometry',
  6283. generator: 'BufferGeometry.toJSON'
  6284. }
  6285. };
  6286. // standard BufferGeometry serialization
  6287. data.uuid = this.uuid;
  6288. data.type = this.type;
  6289. if ( this.name !== '' ) data.name = this.name;
  6290. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  6291. if ( this.parameters !== undefined ) {
  6292. const parameters = this.parameters;
  6293. for ( const key in parameters ) {
  6294. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6295. }
  6296. return data;
  6297. }
  6298. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  6299. data.data = { attributes: {} };
  6300. const index = this.index;
  6301. if ( index !== null ) {
  6302. data.data.index = {
  6303. type: index.array.constructor.name,
  6304. array: Array.prototype.slice.call( index.array )
  6305. };
  6306. }
  6307. const attributes = this.attributes;
  6308. for ( const key in attributes ) {
  6309. const attribute = attributes[ key ];
  6310. data.data.attributes[ key ] = attribute.toJSON( data.data );
  6311. }
  6312. const morphAttributes = {};
  6313. let hasMorphAttributes = false;
  6314. for ( const key in this.morphAttributes ) {
  6315. const attributeArray = this.morphAttributes[ key ];
  6316. const array = [];
  6317. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  6318. const attribute = attributeArray[ i ];
  6319. array.push( attribute.toJSON( data.data ) );
  6320. }
  6321. if ( array.length > 0 ) {
  6322. morphAttributes[ key ] = array;
  6323. hasMorphAttributes = true;
  6324. }
  6325. }
  6326. if ( hasMorphAttributes ) {
  6327. data.data.morphAttributes = morphAttributes;
  6328. data.data.morphTargetsRelative = this.morphTargetsRelative;
  6329. }
  6330. const groups = this.groups;
  6331. if ( groups.length > 0 ) {
  6332. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  6333. }
  6334. const boundingSphere = this.boundingSphere;
  6335. if ( boundingSphere !== null ) {
  6336. data.data.boundingSphere = {
  6337. center: boundingSphere.center.toArray(),
  6338. radius: boundingSphere.radius
  6339. };
  6340. }
  6341. return data;
  6342. }
  6343. clone() {
  6344. return new this.constructor().copy( this );
  6345. }
  6346. copy( source ) {
  6347. // reset
  6348. this.index = null;
  6349. this.attributes = {};
  6350. this.morphAttributes = {};
  6351. this.groups = [];
  6352. this.boundingBox = null;
  6353. this.boundingSphere = null;
  6354. // used for storing cloned, shared data
  6355. const data = {};
  6356. // name
  6357. this.name = source.name;
  6358. // index
  6359. const index = source.index;
  6360. if ( index !== null ) {
  6361. this.setIndex( index.clone( data ) );
  6362. }
  6363. // attributes
  6364. const attributes = source.attributes;
  6365. for ( const name in attributes ) {
  6366. const attribute = attributes[ name ];
  6367. this.setAttribute( name, attribute.clone( data ) );
  6368. }
  6369. // morph attributes
  6370. const morphAttributes = source.morphAttributes;
  6371. for ( const name in morphAttributes ) {
  6372. const array = [];
  6373. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  6374. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  6375. array.push( morphAttribute[ i ].clone( data ) );
  6376. }
  6377. this.morphAttributes[ name ] = array;
  6378. }
  6379. this.morphTargetsRelative = source.morphTargetsRelative;
  6380. // groups
  6381. const groups = source.groups;
  6382. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  6383. const group = groups[ i ];
  6384. this.addGroup( group.start, group.count, group.materialIndex );
  6385. }
  6386. // bounding box
  6387. const boundingBox = source.boundingBox;
  6388. if ( boundingBox !== null ) {
  6389. this.boundingBox = boundingBox.clone();
  6390. }
  6391. // bounding sphere
  6392. const boundingSphere = source.boundingSphere;
  6393. if ( boundingSphere !== null ) {
  6394. this.boundingSphere = boundingSphere.clone();
  6395. }
  6396. // draw range
  6397. this.drawRange.start = source.drawRange.start;
  6398. this.drawRange.count = source.drawRange.count;
  6399. // user data
  6400. this.userData = source.userData;
  6401. // geometry generator parameters
  6402. if ( source.parameters !== undefined ) this.parameters = Object.assign( {}, source.parameters );
  6403. return this;
  6404. }
  6405. dispose() {
  6406. this.dispatchEvent( { type: 'dispose' } );
  6407. }
  6408. }
  6409. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  6410. const _ray$2 = /*@__PURE__*/ new Ray();
  6411. const _sphere$3 = /*@__PURE__*/ new Sphere();
  6412. const _vA$1 = /*@__PURE__*/ new Vector3();
  6413. const _vB$1 = /*@__PURE__*/ new Vector3();
  6414. const _vC$1 = /*@__PURE__*/ new Vector3();
  6415. const _tempA = /*@__PURE__*/ new Vector3();
  6416. const _tempB = /*@__PURE__*/ new Vector3();
  6417. const _tempC = /*@__PURE__*/ new Vector3();
  6418. const _morphA = /*@__PURE__*/ new Vector3();
  6419. const _morphB = /*@__PURE__*/ new Vector3();
  6420. const _morphC = /*@__PURE__*/ new Vector3();
  6421. const _uvA$1 = /*@__PURE__*/ new Vector2();
  6422. const _uvB$1 = /*@__PURE__*/ new Vector2();
  6423. const _uvC$1 = /*@__PURE__*/ new Vector2();
  6424. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  6425. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  6426. class Mesh extends Object3D {
  6427. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  6428. super();
  6429. this.isMesh = true;
  6430. this.type = 'Mesh';
  6431. this.geometry = geometry;
  6432. this.material = material;
  6433. this.updateMorphTargets();
  6434. }
  6435. copy( source, recursive ) {
  6436. super.copy( source, recursive );
  6437. if ( source.morphTargetInfluences !== undefined ) {
  6438. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  6439. }
  6440. if ( source.morphTargetDictionary !== undefined ) {
  6441. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  6442. }
  6443. this.material = source.material;
  6444. this.geometry = source.geometry;
  6445. return this;
  6446. }
  6447. updateMorphTargets() {
  6448. const geometry = this.geometry;
  6449. const morphAttributes = geometry.morphAttributes;
  6450. const keys = Object.keys( morphAttributes );
  6451. if ( keys.length > 0 ) {
  6452. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  6453. if ( morphAttribute !== undefined ) {
  6454. this.morphTargetInfluences = [];
  6455. this.morphTargetDictionary = {};
  6456. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  6457. const name = morphAttribute[ m ].name || String( m );
  6458. this.morphTargetInfluences.push( 0 );
  6459. this.morphTargetDictionary[ name ] = m;
  6460. }
  6461. }
  6462. }
  6463. }
  6464. raycast( raycaster, intersects ) {
  6465. const geometry = this.geometry;
  6466. const material = this.material;
  6467. const matrixWorld = this.matrixWorld;
  6468. if ( material === undefined ) return;
  6469. // Checking boundingSphere distance to ray
  6470. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  6471. _sphere$3.copy( geometry.boundingSphere );
  6472. _sphere$3.applyMatrix4( matrixWorld );
  6473. if ( raycaster.ray.intersectsSphere( _sphere$3 ) === false ) return;
  6474. //
  6475. _inverseMatrix$2.copy( matrixWorld ).invert();
  6476. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  6477. // Check boundingBox before continuing
  6478. if ( geometry.boundingBox !== null ) {
  6479. if ( _ray$2.intersectsBox( geometry.boundingBox ) === false ) return;
  6480. }
  6481. let intersection;
  6482. const index = geometry.index;
  6483. const position = geometry.attributes.position;
  6484. const morphPosition = geometry.morphAttributes.position;
  6485. const morphTargetsRelative = geometry.morphTargetsRelative;
  6486. const uv = geometry.attributes.uv;
  6487. const uv2 = geometry.attributes.uv2;
  6488. const groups = geometry.groups;
  6489. const drawRange = geometry.drawRange;
  6490. if ( index !== null ) {
  6491. // indexed buffer geometry
  6492. if ( Array.isArray( material ) ) {
  6493. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6494. const group = groups[ i ];
  6495. const groupMaterial = material[ group.materialIndex ];
  6496. const start = Math.max( group.start, drawRange.start );
  6497. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6498. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6499. const a = index.getX( j );
  6500. const b = index.getX( j + 1 );
  6501. const c = index.getX( j + 2 );
  6502. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6503. if ( intersection ) {
  6504. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  6505. intersection.face.materialIndex = group.materialIndex;
  6506. intersects.push( intersection );
  6507. }
  6508. }
  6509. }
  6510. } else {
  6511. const start = Math.max( 0, drawRange.start );
  6512. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  6513. for ( let i = start, il = end; i < il; i += 3 ) {
  6514. const a = index.getX( i );
  6515. const b = index.getX( i + 1 );
  6516. const c = index.getX( i + 2 );
  6517. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6518. if ( intersection ) {
  6519. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  6520. intersects.push( intersection );
  6521. }
  6522. }
  6523. }
  6524. } else if ( position !== undefined ) {
  6525. // non-indexed buffer geometry
  6526. if ( Array.isArray( material ) ) {
  6527. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  6528. const group = groups[ i ];
  6529. const groupMaterial = material[ group.materialIndex ];
  6530. const start = Math.max( group.start, drawRange.start );
  6531. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  6532. for ( let j = start, jl = end; j < jl; j += 3 ) {
  6533. const a = j;
  6534. const b = j + 1;
  6535. const c = j + 2;
  6536. intersection = checkBufferGeometryIntersection( this, groupMaterial, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6537. if ( intersection ) {
  6538. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  6539. intersection.face.materialIndex = group.materialIndex;
  6540. intersects.push( intersection );
  6541. }
  6542. }
  6543. }
  6544. } else {
  6545. const start = Math.max( 0, drawRange.start );
  6546. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  6547. for ( let i = start, il = end; i < il; i += 3 ) {
  6548. const a = i;
  6549. const b = i + 1;
  6550. const c = i + 2;
  6551. intersection = checkBufferGeometryIntersection( this, material, raycaster, _ray$2, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c );
  6552. if ( intersection ) {
  6553. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  6554. intersects.push( intersection );
  6555. }
  6556. }
  6557. }
  6558. }
  6559. }
  6560. }
  6561. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  6562. let intersect;
  6563. if ( material.side === BackSide ) {
  6564. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  6565. } else {
  6566. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  6567. }
  6568. if ( intersect === null ) return null;
  6569. _intersectionPointWorld.copy( point );
  6570. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  6571. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  6572. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  6573. return {
  6574. distance: distance,
  6575. point: _intersectionPointWorld.clone(),
  6576. object: object
  6577. };
  6578. }
  6579. function checkBufferGeometryIntersection( object, material, raycaster, ray, position, morphPosition, morphTargetsRelative, uv, uv2, a, b, c ) {
  6580. _vA$1.fromBufferAttribute( position, a );
  6581. _vB$1.fromBufferAttribute( position, b );
  6582. _vC$1.fromBufferAttribute( position, c );
  6583. const morphInfluences = object.morphTargetInfluences;
  6584. if ( morphPosition && morphInfluences ) {
  6585. _morphA.set( 0, 0, 0 );
  6586. _morphB.set( 0, 0, 0 );
  6587. _morphC.set( 0, 0, 0 );
  6588. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  6589. const influence = morphInfluences[ i ];
  6590. const morphAttribute = morphPosition[ i ];
  6591. if ( influence === 0 ) continue;
  6592. _tempA.fromBufferAttribute( morphAttribute, a );
  6593. _tempB.fromBufferAttribute( morphAttribute, b );
  6594. _tempC.fromBufferAttribute( morphAttribute, c );
  6595. if ( morphTargetsRelative ) {
  6596. _morphA.addScaledVector( _tempA, influence );
  6597. _morphB.addScaledVector( _tempB, influence );
  6598. _morphC.addScaledVector( _tempC, influence );
  6599. } else {
  6600. _morphA.addScaledVector( _tempA.sub( _vA$1 ), influence );
  6601. _morphB.addScaledVector( _tempB.sub( _vB$1 ), influence );
  6602. _morphC.addScaledVector( _tempC.sub( _vC$1 ), influence );
  6603. }
  6604. }
  6605. _vA$1.add( _morphA );
  6606. _vB$1.add( _morphB );
  6607. _vC$1.add( _morphC );
  6608. }
  6609. if ( object.isSkinnedMesh ) {
  6610. object.boneTransform( a, _vA$1 );
  6611. object.boneTransform( b, _vB$1 );
  6612. object.boneTransform( c, _vC$1 );
  6613. }
  6614. const intersection = checkIntersection( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  6615. if ( intersection ) {
  6616. if ( uv ) {
  6617. _uvA$1.fromBufferAttribute( uv, a );
  6618. _uvB$1.fromBufferAttribute( uv, b );
  6619. _uvC$1.fromBufferAttribute( uv, c );
  6620. intersection.uv = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6621. }
  6622. if ( uv2 ) {
  6623. _uvA$1.fromBufferAttribute( uv2, a );
  6624. _uvB$1.fromBufferAttribute( uv2, b );
  6625. _uvC$1.fromBufferAttribute( uv2, c );
  6626. intersection.uv2 = Triangle.getUV( _intersectionPoint, _vA$1, _vB$1, _vC$1, _uvA$1, _uvB$1, _uvC$1, new Vector2() );
  6627. }
  6628. const face = {
  6629. a: a,
  6630. b: b,
  6631. c: c,
  6632. normal: new Vector3(),
  6633. materialIndex: 0
  6634. };
  6635. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  6636. intersection.face = face;
  6637. }
  6638. return intersection;
  6639. }
  6640. class BoxGeometry extends BufferGeometry {
  6641. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  6642. super();
  6643. this.type = 'BoxGeometry';
  6644. this.parameters = {
  6645. width: width,
  6646. height: height,
  6647. depth: depth,
  6648. widthSegments: widthSegments,
  6649. heightSegments: heightSegments,
  6650. depthSegments: depthSegments
  6651. };
  6652. const scope = this;
  6653. // segments
  6654. widthSegments = Math.floor( widthSegments );
  6655. heightSegments = Math.floor( heightSegments );
  6656. depthSegments = Math.floor( depthSegments );
  6657. // buffers
  6658. const indices = [];
  6659. const vertices = [];
  6660. const normals = [];
  6661. const uvs = [];
  6662. // helper variables
  6663. let numberOfVertices = 0;
  6664. let groupStart = 0;
  6665. // build each side of the box geometry
  6666. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  6667. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  6668. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  6669. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  6670. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  6671. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  6672. // build geometry
  6673. this.setIndex( indices );
  6674. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  6675. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  6676. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  6677. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  6678. const segmentWidth = width / gridX;
  6679. const segmentHeight = height / gridY;
  6680. const widthHalf = width / 2;
  6681. const heightHalf = height / 2;
  6682. const depthHalf = depth / 2;
  6683. const gridX1 = gridX + 1;
  6684. const gridY1 = gridY + 1;
  6685. let vertexCounter = 0;
  6686. let groupCount = 0;
  6687. const vector = new Vector3();
  6688. // generate vertices, normals and uvs
  6689. for ( let iy = 0; iy < gridY1; iy ++ ) {
  6690. const y = iy * segmentHeight - heightHalf;
  6691. for ( let ix = 0; ix < gridX1; ix ++ ) {
  6692. const x = ix * segmentWidth - widthHalf;
  6693. // set values to correct vector component
  6694. vector[ u ] = x * udir;
  6695. vector[ v ] = y * vdir;
  6696. vector[ w ] = depthHalf;
  6697. // now apply vector to vertex buffer
  6698. vertices.push( vector.x, vector.y, vector.z );
  6699. // set values to correct vector component
  6700. vector[ u ] = 0;
  6701. vector[ v ] = 0;
  6702. vector[ w ] = depth > 0 ? 1 : - 1;
  6703. // now apply vector to normal buffer
  6704. normals.push( vector.x, vector.y, vector.z );
  6705. // uvs
  6706. uvs.push( ix / gridX );
  6707. uvs.push( 1 - ( iy / gridY ) );
  6708. // counters
  6709. vertexCounter += 1;
  6710. }
  6711. }
  6712. // indices
  6713. // 1. you need three indices to draw a single face
  6714. // 2. a single segment consists of two faces
  6715. // 3. so we need to generate six (2*3) indices per segment
  6716. for ( let iy = 0; iy < gridY; iy ++ ) {
  6717. for ( let ix = 0; ix < gridX; ix ++ ) {
  6718. const a = numberOfVertices + ix + gridX1 * iy;
  6719. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  6720. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  6721. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  6722. // faces
  6723. indices.push( a, b, d );
  6724. indices.push( b, c, d );
  6725. // increase counter
  6726. groupCount += 6;
  6727. }
  6728. }
  6729. // add a group to the geometry. this will ensure multi material support
  6730. scope.addGroup( groupStart, groupCount, materialIndex );
  6731. // calculate new start value for groups
  6732. groupStart += groupCount;
  6733. // update total number of vertices
  6734. numberOfVertices += vertexCounter;
  6735. }
  6736. }
  6737. static fromJSON( data ) {
  6738. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  6739. }
  6740. }
  6741. /**
  6742. * Uniform Utilities
  6743. */
  6744. function cloneUniforms( src ) {
  6745. const dst = {};
  6746. for ( const u in src ) {
  6747. dst[ u ] = {};
  6748. for ( const p in src[ u ] ) {
  6749. const property = src[ u ][ p ];
  6750. if ( property && ( property.isColor ||
  6751. property.isMatrix3 || property.isMatrix4 ||
  6752. property.isVector2 || property.isVector3 || property.isVector4 ||
  6753. property.isTexture || property.isQuaternion ) ) {
  6754. dst[ u ][ p ] = property.clone();
  6755. } else if ( Array.isArray( property ) ) {
  6756. dst[ u ][ p ] = property.slice();
  6757. } else {
  6758. dst[ u ][ p ] = property;
  6759. }
  6760. }
  6761. }
  6762. return dst;
  6763. }
  6764. function mergeUniforms( uniforms ) {
  6765. const merged = {};
  6766. for ( let u = 0; u < uniforms.length; u ++ ) {
  6767. const tmp = cloneUniforms( uniforms[ u ] );
  6768. for ( const p in tmp ) {
  6769. merged[ p ] = tmp[ p ];
  6770. }
  6771. }
  6772. return merged;
  6773. }
  6774. function cloneUniformsGroups( src ) {
  6775. const dst = [];
  6776. for ( let u = 0; u < src.length; u ++ ) {
  6777. dst.push( src[ u ].clone() );
  6778. }
  6779. return dst;
  6780. }
  6781. // Legacy
  6782. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  6783. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  6784. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  6785. class ShaderMaterial extends Material {
  6786. constructor( parameters ) {
  6787. super();
  6788. this.isShaderMaterial = true;
  6789. this.type = 'ShaderMaterial';
  6790. this.defines = {};
  6791. this.uniforms = {};
  6792. this.uniformsGroups = [];
  6793. this.vertexShader = default_vertex;
  6794. this.fragmentShader = default_fragment;
  6795. this.linewidth = 1;
  6796. this.wireframe = false;
  6797. this.wireframeLinewidth = 1;
  6798. this.fog = false; // set to use scene fog
  6799. this.lights = false; // set to use scene lights
  6800. this.clipping = false; // set to use user-defined clipping planes
  6801. this.extensions = {
  6802. derivatives: false, // set to use derivatives
  6803. fragDepth: false, // set to use fragment depth values
  6804. drawBuffers: false, // set to use draw buffers
  6805. shaderTextureLOD: false // set to use shader texture LOD
  6806. };
  6807. // When rendered geometry doesn't include these attributes but the material does,
  6808. // use these default values in WebGL. This avoids errors when buffer data is missing.
  6809. this.defaultAttributeValues = {
  6810. 'color': [ 1, 1, 1 ],
  6811. 'uv': [ 0, 0 ],
  6812. 'uv2': [ 0, 0 ]
  6813. };
  6814. this.index0AttributeName = undefined;
  6815. this.uniformsNeedUpdate = false;
  6816. this.glslVersion = null;
  6817. if ( parameters !== undefined ) {
  6818. this.setValues( parameters );
  6819. }
  6820. }
  6821. copy( source ) {
  6822. super.copy( source );
  6823. this.fragmentShader = source.fragmentShader;
  6824. this.vertexShader = source.vertexShader;
  6825. this.uniforms = cloneUniforms( source.uniforms );
  6826. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  6827. this.defines = Object.assign( {}, source.defines );
  6828. this.wireframe = source.wireframe;
  6829. this.wireframeLinewidth = source.wireframeLinewidth;
  6830. this.fog = source.fog;
  6831. this.lights = source.lights;
  6832. this.clipping = source.clipping;
  6833. this.extensions = Object.assign( {}, source.extensions );
  6834. this.glslVersion = source.glslVersion;
  6835. return this;
  6836. }
  6837. toJSON( meta ) {
  6838. const data = super.toJSON( meta );
  6839. data.glslVersion = this.glslVersion;
  6840. data.uniforms = {};
  6841. for ( const name in this.uniforms ) {
  6842. const uniform = this.uniforms[ name ];
  6843. const value = uniform.value;
  6844. if ( value && value.isTexture ) {
  6845. data.uniforms[ name ] = {
  6846. type: 't',
  6847. value: value.toJSON( meta ).uuid
  6848. };
  6849. } else if ( value && value.isColor ) {
  6850. data.uniforms[ name ] = {
  6851. type: 'c',
  6852. value: value.getHex()
  6853. };
  6854. } else if ( value && value.isVector2 ) {
  6855. data.uniforms[ name ] = {
  6856. type: 'v2',
  6857. value: value.toArray()
  6858. };
  6859. } else if ( value && value.isVector3 ) {
  6860. data.uniforms[ name ] = {
  6861. type: 'v3',
  6862. value: value.toArray()
  6863. };
  6864. } else if ( value && value.isVector4 ) {
  6865. data.uniforms[ name ] = {
  6866. type: 'v4',
  6867. value: value.toArray()
  6868. };
  6869. } else if ( value && value.isMatrix3 ) {
  6870. data.uniforms[ name ] = {
  6871. type: 'm3',
  6872. value: value.toArray()
  6873. };
  6874. } else if ( value && value.isMatrix4 ) {
  6875. data.uniforms[ name ] = {
  6876. type: 'm4',
  6877. value: value.toArray()
  6878. };
  6879. } else {
  6880. data.uniforms[ name ] = {
  6881. value: value
  6882. };
  6883. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  6884. }
  6885. }
  6886. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  6887. data.vertexShader = this.vertexShader;
  6888. data.fragmentShader = this.fragmentShader;
  6889. const extensions = {};
  6890. for ( const key in this.extensions ) {
  6891. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  6892. }
  6893. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  6894. return data;
  6895. }
  6896. }
  6897. class Camera extends Object3D {
  6898. constructor() {
  6899. super();
  6900. this.isCamera = true;
  6901. this.type = 'Camera';
  6902. this.matrixWorldInverse = new Matrix4();
  6903. this.projectionMatrix = new Matrix4();
  6904. this.projectionMatrixInverse = new Matrix4();
  6905. }
  6906. copy( source, recursive ) {
  6907. super.copy( source, recursive );
  6908. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  6909. this.projectionMatrix.copy( source.projectionMatrix );
  6910. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  6911. return this;
  6912. }
  6913. getWorldDirection( target ) {
  6914. this.updateWorldMatrix( true, false );
  6915. const e = this.matrixWorld.elements;
  6916. return target.set( - e[ 8 ], - e[ 9 ], - e[ 10 ] ).normalize();
  6917. }
  6918. updateMatrixWorld( force ) {
  6919. super.updateMatrixWorld( force );
  6920. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  6921. }
  6922. updateWorldMatrix( updateParents, updateChildren ) {
  6923. super.updateWorldMatrix( updateParents, updateChildren );
  6924. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  6925. }
  6926. clone() {
  6927. return new this.constructor().copy( this );
  6928. }
  6929. }
  6930. class PerspectiveCamera extends Camera {
  6931. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  6932. super();
  6933. this.isPerspectiveCamera = true;
  6934. this.type = 'PerspectiveCamera';
  6935. this.fov = fov;
  6936. this.zoom = 1;
  6937. this.near = near;
  6938. this.far = far;
  6939. this.focus = 10;
  6940. this.aspect = aspect;
  6941. this.view = null;
  6942. this.filmGauge = 35; // width of the film (default in millimeters)
  6943. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  6944. this.updateProjectionMatrix();
  6945. }
  6946. copy( source, recursive ) {
  6947. super.copy( source, recursive );
  6948. this.fov = source.fov;
  6949. this.zoom = source.zoom;
  6950. this.near = source.near;
  6951. this.far = source.far;
  6952. this.focus = source.focus;
  6953. this.aspect = source.aspect;
  6954. this.view = source.view === null ? null : Object.assign( {}, source.view );
  6955. this.filmGauge = source.filmGauge;
  6956. this.filmOffset = source.filmOffset;
  6957. return this;
  6958. }
  6959. /**
  6960. * Sets the FOV by focal length in respect to the current .filmGauge.
  6961. *
  6962. * The default film gauge is 35, so that the focal length can be specified for
  6963. * a 35mm (full frame) camera.
  6964. *
  6965. * Values for focal length and film gauge must have the same unit.
  6966. */
  6967. setFocalLength( focalLength ) {
  6968. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  6969. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  6970. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  6971. this.updateProjectionMatrix();
  6972. }
  6973. /**
  6974. * Calculates the focal length from the current .fov and .filmGauge.
  6975. */
  6976. getFocalLength() {
  6977. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  6978. return 0.5 * this.getFilmHeight() / vExtentSlope;
  6979. }
  6980. getEffectiveFOV() {
  6981. return RAD2DEG * 2 * Math.atan(
  6982. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  6983. }
  6984. getFilmWidth() {
  6985. // film not completely covered in portrait format (aspect < 1)
  6986. return this.filmGauge * Math.min( this.aspect, 1 );
  6987. }
  6988. getFilmHeight() {
  6989. // film not completely covered in landscape format (aspect > 1)
  6990. return this.filmGauge / Math.max( this.aspect, 1 );
  6991. }
  6992. /**
  6993. * Sets an offset in a larger frustum. This is useful for multi-window or
  6994. * multi-monitor/multi-machine setups.
  6995. *
  6996. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6997. * the monitors are in grid like this
  6998. *
  6999. * +---+---+---+
  7000. * | A | B | C |
  7001. * +---+---+---+
  7002. * | D | E | F |
  7003. * +---+---+---+
  7004. *
  7005. * then for each monitor you would call it like this
  7006. *
  7007. * const w = 1920;
  7008. * const h = 1080;
  7009. * const fullWidth = w * 3;
  7010. * const fullHeight = h * 2;
  7011. *
  7012. * --A--
  7013. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  7014. * --B--
  7015. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  7016. * --C--
  7017. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  7018. * --D--
  7019. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  7020. * --E--
  7021. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  7022. * --F--
  7023. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  7024. *
  7025. * Note there is no reason monitors have to be the same size or in a grid.
  7026. */
  7027. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  7028. this.aspect = fullWidth / fullHeight;
  7029. if ( this.view === null ) {
  7030. this.view = {
  7031. enabled: true,
  7032. fullWidth: 1,
  7033. fullHeight: 1,
  7034. offsetX: 0,
  7035. offsetY: 0,
  7036. width: 1,
  7037. height: 1
  7038. };
  7039. }
  7040. this.view.enabled = true;
  7041. this.view.fullWidth = fullWidth;
  7042. this.view.fullHeight = fullHeight;
  7043. this.view.offsetX = x;
  7044. this.view.offsetY = y;
  7045. this.view.width = width;
  7046. this.view.height = height;
  7047. this.updateProjectionMatrix();
  7048. }
  7049. clearViewOffset() {
  7050. if ( this.view !== null ) {
  7051. this.view.enabled = false;
  7052. }
  7053. this.updateProjectionMatrix();
  7054. }
  7055. updateProjectionMatrix() {
  7056. const near = this.near;
  7057. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  7058. let height = 2 * top;
  7059. let width = this.aspect * height;
  7060. let left = - 0.5 * width;
  7061. const view = this.view;
  7062. if ( this.view !== null && this.view.enabled ) {
  7063. const fullWidth = view.fullWidth,
  7064. fullHeight = view.fullHeight;
  7065. left += view.offsetX * width / fullWidth;
  7066. top -= view.offsetY * height / fullHeight;
  7067. width *= view.width / fullWidth;
  7068. height *= view.height / fullHeight;
  7069. }
  7070. const skew = this.filmOffset;
  7071. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  7072. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  7073. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  7074. }
  7075. toJSON( meta ) {
  7076. const data = super.toJSON( meta );
  7077. data.object.fov = this.fov;
  7078. data.object.zoom = this.zoom;
  7079. data.object.near = this.near;
  7080. data.object.far = this.far;
  7081. data.object.focus = this.focus;
  7082. data.object.aspect = this.aspect;
  7083. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  7084. data.object.filmGauge = this.filmGauge;
  7085. data.object.filmOffset = this.filmOffset;
  7086. return data;
  7087. }
  7088. }
  7089. const fov = 90, aspect = 1;
  7090. class CubeCamera extends Object3D {
  7091. constructor( near, far, renderTarget ) {
  7092. super();
  7093. this.type = 'CubeCamera';
  7094. this.renderTarget = renderTarget;
  7095. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  7096. cameraPX.layers = this.layers;
  7097. cameraPX.up.set( 0, - 1, 0 );
  7098. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  7099. this.add( cameraPX );
  7100. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  7101. cameraNX.layers = this.layers;
  7102. cameraNX.up.set( 0, - 1, 0 );
  7103. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  7104. this.add( cameraNX );
  7105. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  7106. cameraPY.layers = this.layers;
  7107. cameraPY.up.set( 0, 0, 1 );
  7108. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  7109. this.add( cameraPY );
  7110. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  7111. cameraNY.layers = this.layers;
  7112. cameraNY.up.set( 0, 0, - 1 );
  7113. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  7114. this.add( cameraNY );
  7115. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  7116. cameraPZ.layers = this.layers;
  7117. cameraPZ.up.set( 0, - 1, 0 );
  7118. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  7119. this.add( cameraPZ );
  7120. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  7121. cameraNZ.layers = this.layers;
  7122. cameraNZ.up.set( 0, - 1, 0 );
  7123. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  7124. this.add( cameraNZ );
  7125. }
  7126. update( renderer, scene ) {
  7127. if ( this.parent === null ) this.updateMatrixWorld();
  7128. const renderTarget = this.renderTarget;
  7129. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  7130. const currentRenderTarget = renderer.getRenderTarget();
  7131. const currentToneMapping = renderer.toneMapping;
  7132. const currentXrEnabled = renderer.xr.enabled;
  7133. renderer.toneMapping = NoToneMapping;
  7134. renderer.xr.enabled = false;
  7135. const generateMipmaps = renderTarget.texture.generateMipmaps;
  7136. renderTarget.texture.generateMipmaps = false;
  7137. renderer.setRenderTarget( renderTarget, 0 );
  7138. renderer.render( scene, cameraPX );
  7139. renderer.setRenderTarget( renderTarget, 1 );
  7140. renderer.render( scene, cameraNX );
  7141. renderer.setRenderTarget( renderTarget, 2 );
  7142. renderer.render( scene, cameraPY );
  7143. renderer.setRenderTarget( renderTarget, 3 );
  7144. renderer.render( scene, cameraNY );
  7145. renderer.setRenderTarget( renderTarget, 4 );
  7146. renderer.render( scene, cameraPZ );
  7147. renderTarget.texture.generateMipmaps = generateMipmaps;
  7148. renderer.setRenderTarget( renderTarget, 5 );
  7149. renderer.render( scene, cameraNZ );
  7150. renderer.setRenderTarget( currentRenderTarget );
  7151. renderer.toneMapping = currentToneMapping;
  7152. renderer.xr.enabled = currentXrEnabled;
  7153. renderTarget.texture.needsPMREMUpdate = true;
  7154. }
  7155. }
  7156. class CubeTexture extends Texture {
  7157. constructor( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  7158. images = images !== undefined ? images : [];
  7159. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7160. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7161. this.isCubeTexture = true;
  7162. this.flipY = false;
  7163. }
  7164. get images() {
  7165. return this.image;
  7166. }
  7167. set images( value ) {
  7168. this.image = value;
  7169. }
  7170. }
  7171. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  7172. constructor( size, options = {} ) {
  7173. super( size, size, options );
  7174. this.isWebGLCubeRenderTarget = true;
  7175. const image = { width: size, height: size, depth: 1 };
  7176. const images = [ image, image, image, image, image, image ];
  7177. this.texture = new CubeTexture( images, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  7178. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  7179. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  7180. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  7181. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  7182. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  7183. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  7184. this.texture.isRenderTargetTexture = true;
  7185. this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
  7186. this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
  7187. }
  7188. fromEquirectangularTexture( renderer, texture ) {
  7189. this.texture.type = texture.type;
  7190. this.texture.encoding = texture.encoding;
  7191. this.texture.generateMipmaps = texture.generateMipmaps;
  7192. this.texture.minFilter = texture.minFilter;
  7193. this.texture.magFilter = texture.magFilter;
  7194. const shader = {
  7195. uniforms: {
  7196. tEquirect: { value: null },
  7197. },
  7198. vertexShader: /* glsl */`
  7199. varying vec3 vWorldDirection;
  7200. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  7201. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  7202. }
  7203. void main() {
  7204. vWorldDirection = transformDirection( position, modelMatrix );
  7205. #include <begin_vertex>
  7206. #include <project_vertex>
  7207. }
  7208. `,
  7209. fragmentShader: /* glsl */`
  7210. uniform sampler2D tEquirect;
  7211. varying vec3 vWorldDirection;
  7212. #include <common>
  7213. void main() {
  7214. vec3 direction = normalize( vWorldDirection );
  7215. vec2 sampleUV = equirectUv( direction );
  7216. gl_FragColor = texture2D( tEquirect, sampleUV );
  7217. }
  7218. `
  7219. };
  7220. const geometry = new BoxGeometry( 5, 5, 5 );
  7221. const material = new ShaderMaterial( {
  7222. name: 'CubemapFromEquirect',
  7223. uniforms: cloneUniforms( shader.uniforms ),
  7224. vertexShader: shader.vertexShader,
  7225. fragmentShader: shader.fragmentShader,
  7226. side: BackSide,
  7227. blending: NoBlending
  7228. } );
  7229. material.uniforms.tEquirect.value = texture;
  7230. const mesh = new Mesh( geometry, material );
  7231. const currentMinFilter = texture.minFilter;
  7232. // Avoid blurred poles
  7233. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  7234. const camera = new CubeCamera( 1, 10, this );
  7235. camera.update( renderer, mesh );
  7236. texture.minFilter = currentMinFilter;
  7237. mesh.geometry.dispose();
  7238. mesh.material.dispose();
  7239. return this;
  7240. }
  7241. clear( renderer, color, depth, stencil ) {
  7242. const currentRenderTarget = renderer.getRenderTarget();
  7243. for ( let i = 0; i < 6; i ++ ) {
  7244. renderer.setRenderTarget( this, i );
  7245. renderer.clear( color, depth, stencil );
  7246. }
  7247. renderer.setRenderTarget( currentRenderTarget );
  7248. }
  7249. }
  7250. const _vector1 = /*@__PURE__*/ new Vector3();
  7251. const _vector2 = /*@__PURE__*/ new Vector3();
  7252. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  7253. class Plane {
  7254. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  7255. this.isPlane = true;
  7256. // normal is assumed to be normalized
  7257. this.normal = normal;
  7258. this.constant = constant;
  7259. }
  7260. set( normal, constant ) {
  7261. this.normal.copy( normal );
  7262. this.constant = constant;
  7263. return this;
  7264. }
  7265. setComponents( x, y, z, w ) {
  7266. this.normal.set( x, y, z );
  7267. this.constant = w;
  7268. return this;
  7269. }
  7270. setFromNormalAndCoplanarPoint( normal, point ) {
  7271. this.normal.copy( normal );
  7272. this.constant = - point.dot( this.normal );
  7273. return this;
  7274. }
  7275. setFromCoplanarPoints( a, b, c ) {
  7276. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  7277. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  7278. this.setFromNormalAndCoplanarPoint( normal, a );
  7279. return this;
  7280. }
  7281. copy( plane ) {
  7282. this.normal.copy( plane.normal );
  7283. this.constant = plane.constant;
  7284. return this;
  7285. }
  7286. normalize() {
  7287. // Note: will lead to a divide by zero if the plane is invalid.
  7288. const inverseNormalLength = 1.0 / this.normal.length();
  7289. this.normal.multiplyScalar( inverseNormalLength );
  7290. this.constant *= inverseNormalLength;
  7291. return this;
  7292. }
  7293. negate() {
  7294. this.constant *= - 1;
  7295. this.normal.negate();
  7296. return this;
  7297. }
  7298. distanceToPoint( point ) {
  7299. return this.normal.dot( point ) + this.constant;
  7300. }
  7301. distanceToSphere( sphere ) {
  7302. return this.distanceToPoint( sphere.center ) - sphere.radius;
  7303. }
  7304. projectPoint( point, target ) {
  7305. return target.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  7306. }
  7307. intersectLine( line, target ) {
  7308. const direction = line.delta( _vector1 );
  7309. const denominator = this.normal.dot( direction );
  7310. if ( denominator === 0 ) {
  7311. // line is coplanar, return origin
  7312. if ( this.distanceToPoint( line.start ) === 0 ) {
  7313. return target.copy( line.start );
  7314. }
  7315. // Unsure if this is the correct method to handle this case.
  7316. return null;
  7317. }
  7318. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  7319. if ( t < 0 || t > 1 ) {
  7320. return null;
  7321. }
  7322. return target.copy( direction ).multiplyScalar( t ).add( line.start );
  7323. }
  7324. intersectsLine( line ) {
  7325. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  7326. const startSign = this.distanceToPoint( line.start );
  7327. const endSign = this.distanceToPoint( line.end );
  7328. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  7329. }
  7330. intersectsBox( box ) {
  7331. return box.intersectsPlane( this );
  7332. }
  7333. intersectsSphere( sphere ) {
  7334. return sphere.intersectsPlane( this );
  7335. }
  7336. coplanarPoint( target ) {
  7337. return target.copy( this.normal ).multiplyScalar( - this.constant );
  7338. }
  7339. applyMatrix4( matrix, optionalNormalMatrix ) {
  7340. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  7341. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  7342. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  7343. this.constant = - referencePoint.dot( normal );
  7344. return this;
  7345. }
  7346. translate( offset ) {
  7347. this.constant -= offset.dot( this.normal );
  7348. return this;
  7349. }
  7350. equals( plane ) {
  7351. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  7352. }
  7353. clone() {
  7354. return new this.constructor().copy( this );
  7355. }
  7356. }
  7357. const _sphere$2 = /*@__PURE__*/ new Sphere();
  7358. const _vector$7 = /*@__PURE__*/ new Vector3();
  7359. class Frustum {
  7360. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  7361. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  7362. }
  7363. set( p0, p1, p2, p3, p4, p5 ) {
  7364. const planes = this.planes;
  7365. planes[ 0 ].copy( p0 );
  7366. planes[ 1 ].copy( p1 );
  7367. planes[ 2 ].copy( p2 );
  7368. planes[ 3 ].copy( p3 );
  7369. planes[ 4 ].copy( p4 );
  7370. planes[ 5 ].copy( p5 );
  7371. return this;
  7372. }
  7373. copy( frustum ) {
  7374. const planes = this.planes;
  7375. for ( let i = 0; i < 6; i ++ ) {
  7376. planes[ i ].copy( frustum.planes[ i ] );
  7377. }
  7378. return this;
  7379. }
  7380. setFromProjectionMatrix( m ) {
  7381. const planes = this.planes;
  7382. const me = m.elements;
  7383. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  7384. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  7385. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  7386. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  7387. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  7388. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  7389. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  7390. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  7391. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  7392. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  7393. return this;
  7394. }
  7395. intersectsObject( object ) {
  7396. const geometry = object.geometry;
  7397. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  7398. _sphere$2.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  7399. return this.intersectsSphere( _sphere$2 );
  7400. }
  7401. intersectsSprite( sprite ) {
  7402. _sphere$2.center.set( 0, 0, 0 );
  7403. _sphere$2.radius = 0.7071067811865476;
  7404. _sphere$2.applyMatrix4( sprite.matrixWorld );
  7405. return this.intersectsSphere( _sphere$2 );
  7406. }
  7407. intersectsSphere( sphere ) {
  7408. const planes = this.planes;
  7409. const center = sphere.center;
  7410. const negRadius = - sphere.radius;
  7411. for ( let i = 0; i < 6; i ++ ) {
  7412. const distance = planes[ i ].distanceToPoint( center );
  7413. if ( distance < negRadius ) {
  7414. return false;
  7415. }
  7416. }
  7417. return true;
  7418. }
  7419. intersectsBox( box ) {
  7420. const planes = this.planes;
  7421. for ( let i = 0; i < 6; i ++ ) {
  7422. const plane = planes[ i ];
  7423. // corner at max distance
  7424. _vector$7.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  7425. _vector$7.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  7426. _vector$7.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  7427. if ( plane.distanceToPoint( _vector$7 ) < 0 ) {
  7428. return false;
  7429. }
  7430. }
  7431. return true;
  7432. }
  7433. containsPoint( point ) {
  7434. const planes = this.planes;
  7435. for ( let i = 0; i < 6; i ++ ) {
  7436. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  7437. return false;
  7438. }
  7439. }
  7440. return true;
  7441. }
  7442. clone() {
  7443. return new this.constructor().copy( this );
  7444. }
  7445. }
  7446. function WebGLAnimation() {
  7447. let context = null;
  7448. let isAnimating = false;
  7449. let animationLoop = null;
  7450. let requestId = null;
  7451. function onAnimationFrame( time, frame ) {
  7452. animationLoop( time, frame );
  7453. requestId = context.requestAnimationFrame( onAnimationFrame );
  7454. }
  7455. return {
  7456. start: function () {
  7457. if ( isAnimating === true ) return;
  7458. if ( animationLoop === null ) return;
  7459. requestId = context.requestAnimationFrame( onAnimationFrame );
  7460. isAnimating = true;
  7461. },
  7462. stop: function () {
  7463. context.cancelAnimationFrame( requestId );
  7464. isAnimating = false;
  7465. },
  7466. setAnimationLoop: function ( callback ) {
  7467. animationLoop = callback;
  7468. },
  7469. setContext: function ( value ) {
  7470. context = value;
  7471. }
  7472. };
  7473. }
  7474. function WebGLAttributes( gl, capabilities ) {
  7475. const isWebGL2 = capabilities.isWebGL2;
  7476. const buffers = new WeakMap();
  7477. function createBuffer( attribute, bufferType ) {
  7478. const array = attribute.array;
  7479. const usage = attribute.usage;
  7480. const buffer = gl.createBuffer();
  7481. gl.bindBuffer( bufferType, buffer );
  7482. gl.bufferData( bufferType, array, usage );
  7483. attribute.onUploadCallback();
  7484. let type;
  7485. if ( array instanceof Float32Array ) {
  7486. type = 5126;
  7487. } else if ( array instanceof Uint16Array ) {
  7488. if ( attribute.isFloat16BufferAttribute ) {
  7489. if ( isWebGL2 ) {
  7490. type = 5131;
  7491. } else {
  7492. throw new Error( 'THREE.WebGLAttributes: Usage of Float16BufferAttribute requires WebGL2.' );
  7493. }
  7494. } else {
  7495. type = 5123;
  7496. }
  7497. } else if ( array instanceof Int16Array ) {
  7498. type = 5122;
  7499. } else if ( array instanceof Uint32Array ) {
  7500. type = 5125;
  7501. } else if ( array instanceof Int32Array ) {
  7502. type = 5124;
  7503. } else if ( array instanceof Int8Array ) {
  7504. type = 5120;
  7505. } else if ( array instanceof Uint8Array ) {
  7506. type = 5121;
  7507. } else if ( array instanceof Uint8ClampedArray ) {
  7508. type = 5121;
  7509. } else {
  7510. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  7511. }
  7512. return {
  7513. buffer: buffer,
  7514. type: type,
  7515. bytesPerElement: array.BYTES_PER_ELEMENT,
  7516. version: attribute.version
  7517. };
  7518. }
  7519. function updateBuffer( buffer, attribute, bufferType ) {
  7520. const array = attribute.array;
  7521. const updateRange = attribute.updateRange;
  7522. gl.bindBuffer( bufferType, buffer );
  7523. if ( updateRange.count === - 1 ) {
  7524. // Not using update ranges
  7525. gl.bufferSubData( bufferType, 0, array );
  7526. } else {
  7527. if ( isWebGL2 ) {
  7528. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7529. array, updateRange.offset, updateRange.count );
  7530. } else {
  7531. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  7532. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  7533. }
  7534. updateRange.count = - 1; // reset range
  7535. }
  7536. }
  7537. //
  7538. function get( attribute ) {
  7539. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7540. return buffers.get( attribute );
  7541. }
  7542. function remove( attribute ) {
  7543. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7544. const data = buffers.get( attribute );
  7545. if ( data ) {
  7546. gl.deleteBuffer( data.buffer );
  7547. buffers.delete( attribute );
  7548. }
  7549. }
  7550. function update( attribute, bufferType ) {
  7551. if ( attribute.isGLBufferAttribute ) {
  7552. const cached = buffers.get( attribute );
  7553. if ( ! cached || cached.version < attribute.version ) {
  7554. buffers.set( attribute, {
  7555. buffer: attribute.buffer,
  7556. type: attribute.type,
  7557. bytesPerElement: attribute.elementSize,
  7558. version: attribute.version
  7559. } );
  7560. }
  7561. return;
  7562. }
  7563. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  7564. const data = buffers.get( attribute );
  7565. if ( data === undefined ) {
  7566. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  7567. } else if ( data.version < attribute.version ) {
  7568. updateBuffer( data.buffer, attribute, bufferType );
  7569. data.version = attribute.version;
  7570. }
  7571. }
  7572. return {
  7573. get: get,
  7574. remove: remove,
  7575. update: update
  7576. };
  7577. }
  7578. class PlaneGeometry extends BufferGeometry {
  7579. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  7580. super();
  7581. this.type = 'PlaneGeometry';
  7582. this.parameters = {
  7583. width: width,
  7584. height: height,
  7585. widthSegments: widthSegments,
  7586. heightSegments: heightSegments
  7587. };
  7588. const width_half = width / 2;
  7589. const height_half = height / 2;
  7590. const gridX = Math.floor( widthSegments );
  7591. const gridY = Math.floor( heightSegments );
  7592. const gridX1 = gridX + 1;
  7593. const gridY1 = gridY + 1;
  7594. const segment_width = width / gridX;
  7595. const segment_height = height / gridY;
  7596. //
  7597. const indices = [];
  7598. const vertices = [];
  7599. const normals = [];
  7600. const uvs = [];
  7601. for ( let iy = 0; iy < gridY1; iy ++ ) {
  7602. const y = iy * segment_height - height_half;
  7603. for ( let ix = 0; ix < gridX1; ix ++ ) {
  7604. const x = ix * segment_width - width_half;
  7605. vertices.push( x, - y, 0 );
  7606. normals.push( 0, 0, 1 );
  7607. uvs.push( ix / gridX );
  7608. uvs.push( 1 - ( iy / gridY ) );
  7609. }
  7610. }
  7611. for ( let iy = 0; iy < gridY; iy ++ ) {
  7612. for ( let ix = 0; ix < gridX; ix ++ ) {
  7613. const a = ix + gridX1 * iy;
  7614. const b = ix + gridX1 * ( iy + 1 );
  7615. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  7616. const d = ( ix + 1 ) + gridX1 * iy;
  7617. indices.push( a, b, d );
  7618. indices.push( b, c, d );
  7619. }
  7620. }
  7621. this.setIndex( indices );
  7622. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  7623. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  7624. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  7625. }
  7626. static fromJSON( data ) {
  7627. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  7628. }
  7629. }
  7630. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif";
  7631. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  7632. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\tif ( diffuseColor.a < alphaTest ) discard;\n#endif";
  7633. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  7634. 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";
  7635. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7636. var begin_vertex = "vec3 transformed = vec3( position );";
  7637. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  7638. 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";
  7639. 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";
  7640. 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";
  7641. 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";
  7642. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  7643. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  7644. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  7645. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7646. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  7647. 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";
  7648. 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";
  7649. 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}";
  7650. 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\tvec2 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";
  7651. 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";
  7652. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  7653. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vUv ).x * displacementScale + displacementBias );\n#endif";
  7654. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  7655. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  7656. var encodings_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  7657. 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}";
  7658. 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#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 );\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";
  7659. 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";
  7660. 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";
  7661. 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";
  7662. 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";
  7663. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  7664. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  7665. 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";
  7666. 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";
  7667. 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}";
  7668. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\tvec4 lightMapTexel = texture2D( lightMap, vUv2 );\n\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\treflectedLight.indirectDiffuse += lightMapIrradiance;\n#endif";
  7669. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7670. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  7671. 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\n#define Material_LightProbeLOD( material )\t(0)";
  7672. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\nuniform vec3 lightProbe[ 9 ];\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\tif ( cutoffDistance > 0.0 ) {\n\t\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t}\n\t\treturn distanceFalloff;\n\t#else\n\t\tif ( cutoffDistance > 0.0 && decayExponent > 0.0 ) {\n\t\t\treturn pow( saturate( - lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\t\t}\n\t\treturn 1.0;\n\t#endif\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif";
  7673. 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";
  7674. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  7675. 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\n#define Material_LightProbeLOD( material )\t(0)";
  7676. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  7677. 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\n#define Material_LightProbeLOD( material )\t(0)";
  7678. 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";
  7679. 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}";
  7680. 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 *= all( bvec2( 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\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 defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotShadowCoord[ 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 *= all( bvec2( 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";
  7681. 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";
  7682. 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";
  7683. 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";
  7684. 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";
  7685. 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";
  7686. 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";
  7687. 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";
  7688. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  7689. 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";
  7690. 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";
  7691. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  7692. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7693. 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";
  7694. 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";
  7695. 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";
  7696. 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";
  7697. var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\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;";
  7698. 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";
  7699. 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";
  7700. 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";
  7701. 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";
  7702. 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";
  7703. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = geometryNormal;\n#endif";
  7704. 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";
  7705. 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";
  7706. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  7707. 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 );";
  7708. 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}\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}";
  7709. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  7710. 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;";
  7711. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  7712. 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";
  7713. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  7714. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7715. var shadowmap_pars_fragment = "#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\tvarying vec4 vSpotShadowCoord[ 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\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\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";
  7716. var shadowmap_pars_vertex = "#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\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vSpotShadowCoord[ 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 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";
  7717. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0 || NUM_SPOT_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0\n\t\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\tvec4 shadowWorldPosition;\n\t#endif\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n#endif";
  7718. 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, vSpotShadowCoord[ 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}";
  7719. 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";
  7720. 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";
  7721. 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";
  7722. 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";
  7723. 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";
  7724. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7725. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  7726. 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; }";
  7727. 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";
  7728. var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\t#ifdef texture2DLodEXT\n\t\t\treturn texture2DLodEXT( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#else\n\t\t\treturn texture2D( transmissionSamplerMap, fragCoord.xy, framebufferLod );\n\t\t#endif\n\t}\n\tvec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( attenuationDistance == 0.0 ) {\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";
  7729. var uv_pars_fragment = "#if ( defined( USE_UV ) && ! defined( UVS_VERTEX_ONLY ) )\n\tvarying vec2 vUv;\n#endif";
  7730. 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";
  7731. var uv_vertex = "#ifdef USE_UV\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n#endif";
  7732. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7733. 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";
  7734. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = ( uv2Transform * vec3( uv2, 1 ) ).xy;\n#endif";
  7735. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION )\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";
  7736. const vertex$g = "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}";
  7737. const fragment$g = "uniform sampler2D t2D;\nvarying vec2 vUv;\nvoid main() {\n\tgl_FragColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tgl_FragColor = vec4( mix( pow( gl_FragColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), gl_FragColor.rgb * 0.0773993808, vec3( lessThanEqual( gl_FragColor.rgb, vec3( 0.04045 ) ) ) ), gl_FragColor.w );\n\t#endif\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7738. 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}";
  7739. const fragment$f = "#include <envmap_common_pars_fragment>\nuniform float opacity;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\tvec3 vReflect = vWorldDirection;\n\t#include <envmap_fragment>\n\tgl_FragColor = envColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n}";
  7740. 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}";
  7741. 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}";
  7742. 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}";
  7743. 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}";
  7744. 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}";
  7745. 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}";
  7746. 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}";
  7747. 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}";
  7748. 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}";
  7749. 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}";
  7750. 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}";
  7751. 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}";
  7752. 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}";
  7753. 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}";
  7754. 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}";
  7755. 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}";
  7756. 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}";
  7757. 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}";
  7758. 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}";
  7759. 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}";
  7760. 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}";
  7761. 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}";
  7762. 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}";
  7763. 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}";
  7764. const vertex$2 = "#include <common>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  7765. const fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}";
  7766. 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}";
  7767. 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}";
  7768. const ShaderChunk = {
  7769. alphamap_fragment: alphamap_fragment,
  7770. alphamap_pars_fragment: alphamap_pars_fragment,
  7771. alphatest_fragment: alphatest_fragment,
  7772. alphatest_pars_fragment: alphatest_pars_fragment,
  7773. aomap_fragment: aomap_fragment,
  7774. aomap_pars_fragment: aomap_pars_fragment,
  7775. begin_vertex: begin_vertex,
  7776. beginnormal_vertex: beginnormal_vertex,
  7777. bsdfs: bsdfs,
  7778. iridescence_fragment: iridescence_fragment,
  7779. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7780. clipping_planes_fragment: clipping_planes_fragment,
  7781. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7782. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7783. clipping_planes_vertex: clipping_planes_vertex,
  7784. color_fragment: color_fragment,
  7785. color_pars_fragment: color_pars_fragment,
  7786. color_pars_vertex: color_pars_vertex,
  7787. color_vertex: color_vertex,
  7788. common: common,
  7789. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7790. defaultnormal_vertex: defaultnormal_vertex,
  7791. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7792. displacementmap_vertex: displacementmap_vertex,
  7793. emissivemap_fragment: emissivemap_fragment,
  7794. emissivemap_pars_fragment: emissivemap_pars_fragment,
  7795. encodings_fragment: encodings_fragment,
  7796. encodings_pars_fragment: encodings_pars_fragment,
  7797. envmap_fragment: envmap_fragment,
  7798. envmap_common_pars_fragment: envmap_common_pars_fragment,
  7799. envmap_pars_fragment: envmap_pars_fragment,
  7800. envmap_pars_vertex: envmap_pars_vertex,
  7801. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  7802. envmap_vertex: envmap_vertex,
  7803. fog_vertex: fog_vertex,
  7804. fog_pars_vertex: fog_pars_vertex,
  7805. fog_fragment: fog_fragment,
  7806. fog_pars_fragment: fog_pars_fragment,
  7807. gradientmap_pars_fragment: gradientmap_pars_fragment,
  7808. lightmap_fragment: lightmap_fragment,
  7809. lightmap_pars_fragment: lightmap_pars_fragment,
  7810. lights_lambert_fragment: lights_lambert_fragment,
  7811. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  7812. lights_pars_begin: lights_pars_begin,
  7813. lights_toon_fragment: lights_toon_fragment,
  7814. lights_toon_pars_fragment: lights_toon_pars_fragment,
  7815. lights_phong_fragment: lights_phong_fragment,
  7816. lights_phong_pars_fragment: lights_phong_pars_fragment,
  7817. lights_physical_fragment: lights_physical_fragment,
  7818. lights_physical_pars_fragment: lights_physical_pars_fragment,
  7819. lights_fragment_begin: lights_fragment_begin,
  7820. lights_fragment_maps: lights_fragment_maps,
  7821. lights_fragment_end: lights_fragment_end,
  7822. logdepthbuf_fragment: logdepthbuf_fragment,
  7823. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  7824. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  7825. logdepthbuf_vertex: logdepthbuf_vertex,
  7826. map_fragment: map_fragment,
  7827. map_pars_fragment: map_pars_fragment,
  7828. map_particle_fragment: map_particle_fragment,
  7829. map_particle_pars_fragment: map_particle_pars_fragment,
  7830. metalnessmap_fragment: metalnessmap_fragment,
  7831. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  7832. morphcolor_vertex: morphcolor_vertex,
  7833. morphnormal_vertex: morphnormal_vertex,
  7834. morphtarget_pars_vertex: morphtarget_pars_vertex,
  7835. morphtarget_vertex: morphtarget_vertex,
  7836. normal_fragment_begin: normal_fragment_begin,
  7837. normal_fragment_maps: normal_fragment_maps,
  7838. normal_pars_fragment: normal_pars_fragment,
  7839. normal_pars_vertex: normal_pars_vertex,
  7840. normal_vertex: normal_vertex,
  7841. normalmap_pars_fragment: normalmap_pars_fragment,
  7842. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  7843. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  7844. clearcoat_pars_fragment: clearcoat_pars_fragment,
  7845. iridescence_pars_fragment: iridescence_pars_fragment,
  7846. output_fragment: output_fragment,
  7847. packing: packing,
  7848. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  7849. project_vertex: project_vertex,
  7850. dithering_fragment: dithering_fragment,
  7851. dithering_pars_fragment: dithering_pars_fragment,
  7852. roughnessmap_fragment: roughnessmap_fragment,
  7853. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  7854. shadowmap_pars_fragment: shadowmap_pars_fragment,
  7855. shadowmap_pars_vertex: shadowmap_pars_vertex,
  7856. shadowmap_vertex: shadowmap_vertex,
  7857. shadowmask_pars_fragment: shadowmask_pars_fragment,
  7858. skinbase_vertex: skinbase_vertex,
  7859. skinning_pars_vertex: skinning_pars_vertex,
  7860. skinning_vertex: skinning_vertex,
  7861. skinnormal_vertex: skinnormal_vertex,
  7862. specularmap_fragment: specularmap_fragment,
  7863. specularmap_pars_fragment: specularmap_pars_fragment,
  7864. tonemapping_fragment: tonemapping_fragment,
  7865. tonemapping_pars_fragment: tonemapping_pars_fragment,
  7866. transmission_fragment: transmission_fragment,
  7867. transmission_pars_fragment: transmission_pars_fragment,
  7868. uv_pars_fragment: uv_pars_fragment,
  7869. uv_pars_vertex: uv_pars_vertex,
  7870. uv_vertex: uv_vertex,
  7871. uv2_pars_fragment: uv2_pars_fragment,
  7872. uv2_pars_vertex: uv2_pars_vertex,
  7873. uv2_vertex: uv2_vertex,
  7874. worldpos_vertex: worldpos_vertex,
  7875. background_vert: vertex$g,
  7876. background_frag: fragment$g,
  7877. cube_vert: vertex$f,
  7878. cube_frag: fragment$f,
  7879. depth_vert: vertex$e,
  7880. depth_frag: fragment$e,
  7881. distanceRGBA_vert: vertex$d,
  7882. distanceRGBA_frag: fragment$d,
  7883. equirect_vert: vertex$c,
  7884. equirect_frag: fragment$c,
  7885. linedashed_vert: vertex$b,
  7886. linedashed_frag: fragment$b,
  7887. meshbasic_vert: vertex$a,
  7888. meshbasic_frag: fragment$a,
  7889. meshlambert_vert: vertex$9,
  7890. meshlambert_frag: fragment$9,
  7891. meshmatcap_vert: vertex$8,
  7892. meshmatcap_frag: fragment$8,
  7893. meshnormal_vert: vertex$7,
  7894. meshnormal_frag: fragment$7,
  7895. meshphong_vert: vertex$6,
  7896. meshphong_frag: fragment$6,
  7897. meshphysical_vert: vertex$5,
  7898. meshphysical_frag: fragment$5,
  7899. meshtoon_vert: vertex$4,
  7900. meshtoon_frag: fragment$4,
  7901. points_vert: vertex$3,
  7902. points_frag: fragment$3,
  7903. shadow_vert: vertex$2,
  7904. shadow_frag: fragment$2,
  7905. sprite_vert: vertex$1,
  7906. sprite_frag: fragment$1
  7907. };
  7908. /**
  7909. * Uniforms library for shared webgl shaders
  7910. */
  7911. const UniformsLib = {
  7912. common: {
  7913. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  7914. opacity: { value: 1.0 },
  7915. map: { value: null },
  7916. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  7917. uv2Transform: { value: /*@__PURE__*/ new Matrix3() },
  7918. alphaMap: { value: null },
  7919. alphaTest: { value: 0 }
  7920. },
  7921. specularmap: {
  7922. specularMap: { value: null },
  7923. },
  7924. envmap: {
  7925. envMap: { value: null },
  7926. flipEnvMap: { value: - 1 },
  7927. reflectivity: { value: 1.0 }, // basic, lambert, phong
  7928. ior: { value: 1.5 }, // physical
  7929. refractionRatio: { value: 0.98 } // basic, lambert, phong
  7930. },
  7931. aomap: {
  7932. aoMap: { value: null },
  7933. aoMapIntensity: { value: 1 }
  7934. },
  7935. lightmap: {
  7936. lightMap: { value: null },
  7937. lightMapIntensity: { value: 1 }
  7938. },
  7939. emissivemap: {
  7940. emissiveMap: { value: null }
  7941. },
  7942. bumpmap: {
  7943. bumpMap: { value: null },
  7944. bumpScale: { value: 1 }
  7945. },
  7946. normalmap: {
  7947. normalMap: { value: null },
  7948. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  7949. },
  7950. displacementmap: {
  7951. displacementMap: { value: null },
  7952. displacementScale: { value: 1 },
  7953. displacementBias: { value: 0 }
  7954. },
  7955. roughnessmap: {
  7956. roughnessMap: { value: null }
  7957. },
  7958. metalnessmap: {
  7959. metalnessMap: { value: null }
  7960. },
  7961. gradientmap: {
  7962. gradientMap: { value: null }
  7963. },
  7964. fog: {
  7965. fogDensity: { value: 0.00025 },
  7966. fogNear: { value: 1 },
  7967. fogFar: { value: 2000 },
  7968. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  7969. },
  7970. lights: {
  7971. ambientLightColor: { value: [] },
  7972. lightProbe: { value: [] },
  7973. directionalLights: { value: [], properties: {
  7974. direction: {},
  7975. color: {}
  7976. } },
  7977. directionalLightShadows: { value: [], properties: {
  7978. shadowBias: {},
  7979. shadowNormalBias: {},
  7980. shadowRadius: {},
  7981. shadowMapSize: {}
  7982. } },
  7983. directionalShadowMap: { value: [] },
  7984. directionalShadowMatrix: { value: [] },
  7985. spotLights: { value: [], properties: {
  7986. color: {},
  7987. position: {},
  7988. direction: {},
  7989. distance: {},
  7990. coneCos: {},
  7991. penumbraCos: {},
  7992. decay: {}
  7993. } },
  7994. spotLightShadows: { value: [], properties: {
  7995. shadowBias: {},
  7996. shadowNormalBias: {},
  7997. shadowRadius: {},
  7998. shadowMapSize: {}
  7999. } },
  8000. spotShadowMap: { value: [] },
  8001. spotShadowMatrix: { value: [] },
  8002. pointLights: { value: [], properties: {
  8003. color: {},
  8004. position: {},
  8005. decay: {},
  8006. distance: {}
  8007. } },
  8008. pointLightShadows: { value: [], properties: {
  8009. shadowBias: {},
  8010. shadowNormalBias: {},
  8011. shadowRadius: {},
  8012. shadowMapSize: {},
  8013. shadowCameraNear: {},
  8014. shadowCameraFar: {}
  8015. } },
  8016. pointShadowMap: { value: [] },
  8017. pointShadowMatrix: { value: [] },
  8018. hemisphereLights: { value: [], properties: {
  8019. direction: {},
  8020. skyColor: {},
  8021. groundColor: {}
  8022. } },
  8023. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8024. rectAreaLights: { value: [], properties: {
  8025. color: {},
  8026. position: {},
  8027. width: {},
  8028. height: {}
  8029. } },
  8030. ltc_1: { value: null },
  8031. ltc_2: { value: null }
  8032. },
  8033. points: {
  8034. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8035. opacity: { value: 1.0 },
  8036. size: { value: 1.0 },
  8037. scale: { value: 1.0 },
  8038. map: { value: null },
  8039. alphaMap: { value: null },
  8040. alphaTest: { value: 0 },
  8041. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8042. },
  8043. sprite: {
  8044. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  8045. opacity: { value: 1.0 },
  8046. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  8047. rotation: { value: 0.0 },
  8048. map: { value: null },
  8049. alphaMap: { value: null },
  8050. alphaTest: { value: 0 },
  8051. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  8052. }
  8053. };
  8054. const ShaderLib = {
  8055. basic: {
  8056. uniforms: /*@__PURE__*/ mergeUniforms( [
  8057. UniformsLib.common,
  8058. UniformsLib.specularmap,
  8059. UniformsLib.envmap,
  8060. UniformsLib.aomap,
  8061. UniformsLib.lightmap,
  8062. UniformsLib.fog
  8063. ] ),
  8064. vertexShader: ShaderChunk.meshbasic_vert,
  8065. fragmentShader: ShaderChunk.meshbasic_frag
  8066. },
  8067. lambert: {
  8068. uniforms: /*@__PURE__*/ mergeUniforms( [
  8069. UniformsLib.common,
  8070. UniformsLib.specularmap,
  8071. UniformsLib.envmap,
  8072. UniformsLib.aomap,
  8073. UniformsLib.lightmap,
  8074. UniformsLib.emissivemap,
  8075. UniformsLib.bumpmap,
  8076. UniformsLib.normalmap,
  8077. UniformsLib.displacementmap,
  8078. UniformsLib.fog,
  8079. UniformsLib.lights,
  8080. {
  8081. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8082. }
  8083. ] ),
  8084. vertexShader: ShaderChunk.meshlambert_vert,
  8085. fragmentShader: ShaderChunk.meshlambert_frag
  8086. },
  8087. phong: {
  8088. uniforms: /*@__PURE__*/ mergeUniforms( [
  8089. UniformsLib.common,
  8090. UniformsLib.specularmap,
  8091. UniformsLib.envmap,
  8092. UniformsLib.aomap,
  8093. UniformsLib.lightmap,
  8094. UniformsLib.emissivemap,
  8095. UniformsLib.bumpmap,
  8096. UniformsLib.normalmap,
  8097. UniformsLib.displacementmap,
  8098. UniformsLib.fog,
  8099. UniformsLib.lights,
  8100. {
  8101. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8102. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  8103. shininess: { value: 30 }
  8104. }
  8105. ] ),
  8106. vertexShader: ShaderChunk.meshphong_vert,
  8107. fragmentShader: ShaderChunk.meshphong_frag
  8108. },
  8109. standard: {
  8110. uniforms: /*@__PURE__*/ mergeUniforms( [
  8111. UniformsLib.common,
  8112. UniformsLib.envmap,
  8113. UniformsLib.aomap,
  8114. UniformsLib.lightmap,
  8115. UniformsLib.emissivemap,
  8116. UniformsLib.bumpmap,
  8117. UniformsLib.normalmap,
  8118. UniformsLib.displacementmap,
  8119. UniformsLib.roughnessmap,
  8120. UniformsLib.metalnessmap,
  8121. UniformsLib.fog,
  8122. UniformsLib.lights,
  8123. {
  8124. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8125. roughness: { value: 1.0 },
  8126. metalness: { value: 0.0 },
  8127. envMapIntensity: { value: 1 } // temporary
  8128. }
  8129. ] ),
  8130. vertexShader: ShaderChunk.meshphysical_vert,
  8131. fragmentShader: ShaderChunk.meshphysical_frag
  8132. },
  8133. toon: {
  8134. uniforms: /*@__PURE__*/ mergeUniforms( [
  8135. UniformsLib.common,
  8136. UniformsLib.aomap,
  8137. UniformsLib.lightmap,
  8138. UniformsLib.emissivemap,
  8139. UniformsLib.bumpmap,
  8140. UniformsLib.normalmap,
  8141. UniformsLib.displacementmap,
  8142. UniformsLib.gradientmap,
  8143. UniformsLib.fog,
  8144. UniformsLib.lights,
  8145. {
  8146. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  8147. }
  8148. ] ),
  8149. vertexShader: ShaderChunk.meshtoon_vert,
  8150. fragmentShader: ShaderChunk.meshtoon_frag
  8151. },
  8152. matcap: {
  8153. uniforms: /*@__PURE__*/ mergeUniforms( [
  8154. UniformsLib.common,
  8155. UniformsLib.bumpmap,
  8156. UniformsLib.normalmap,
  8157. UniformsLib.displacementmap,
  8158. UniformsLib.fog,
  8159. {
  8160. matcap: { value: null }
  8161. }
  8162. ] ),
  8163. vertexShader: ShaderChunk.meshmatcap_vert,
  8164. fragmentShader: ShaderChunk.meshmatcap_frag
  8165. },
  8166. points: {
  8167. uniforms: /*@__PURE__*/ mergeUniforms( [
  8168. UniformsLib.points,
  8169. UniformsLib.fog
  8170. ] ),
  8171. vertexShader: ShaderChunk.points_vert,
  8172. fragmentShader: ShaderChunk.points_frag
  8173. },
  8174. dashed: {
  8175. uniforms: /*@__PURE__*/ mergeUniforms( [
  8176. UniformsLib.common,
  8177. UniformsLib.fog,
  8178. {
  8179. scale: { value: 1 },
  8180. dashSize: { value: 1 },
  8181. totalSize: { value: 2 }
  8182. }
  8183. ] ),
  8184. vertexShader: ShaderChunk.linedashed_vert,
  8185. fragmentShader: ShaderChunk.linedashed_frag
  8186. },
  8187. depth: {
  8188. uniforms: /*@__PURE__*/ mergeUniforms( [
  8189. UniformsLib.common,
  8190. UniformsLib.displacementmap
  8191. ] ),
  8192. vertexShader: ShaderChunk.depth_vert,
  8193. fragmentShader: ShaderChunk.depth_frag
  8194. },
  8195. normal: {
  8196. uniforms: /*@__PURE__*/ mergeUniforms( [
  8197. UniformsLib.common,
  8198. UniformsLib.bumpmap,
  8199. UniformsLib.normalmap,
  8200. UniformsLib.displacementmap,
  8201. {
  8202. opacity: { value: 1.0 }
  8203. }
  8204. ] ),
  8205. vertexShader: ShaderChunk.meshnormal_vert,
  8206. fragmentShader: ShaderChunk.meshnormal_frag
  8207. },
  8208. sprite: {
  8209. uniforms: /*@__PURE__*/ mergeUniforms( [
  8210. UniformsLib.sprite,
  8211. UniformsLib.fog
  8212. ] ),
  8213. vertexShader: ShaderChunk.sprite_vert,
  8214. fragmentShader: ShaderChunk.sprite_frag
  8215. },
  8216. background: {
  8217. uniforms: {
  8218. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  8219. t2D: { value: null },
  8220. },
  8221. vertexShader: ShaderChunk.background_vert,
  8222. fragmentShader: ShaderChunk.background_frag
  8223. },
  8224. cube: {
  8225. uniforms: /*@__PURE__*/ mergeUniforms( [
  8226. UniformsLib.envmap,
  8227. {
  8228. opacity: { value: 1.0 }
  8229. }
  8230. ] ),
  8231. vertexShader: ShaderChunk.cube_vert,
  8232. fragmentShader: ShaderChunk.cube_frag
  8233. },
  8234. equirect: {
  8235. uniforms: {
  8236. tEquirect: { value: null },
  8237. },
  8238. vertexShader: ShaderChunk.equirect_vert,
  8239. fragmentShader: ShaderChunk.equirect_frag
  8240. },
  8241. distanceRGBA: {
  8242. uniforms: /*@__PURE__*/ mergeUniforms( [
  8243. UniformsLib.common,
  8244. UniformsLib.displacementmap,
  8245. {
  8246. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  8247. nearDistance: { value: 1 },
  8248. farDistance: { value: 1000 }
  8249. }
  8250. ] ),
  8251. vertexShader: ShaderChunk.distanceRGBA_vert,
  8252. fragmentShader: ShaderChunk.distanceRGBA_frag
  8253. },
  8254. shadow: {
  8255. uniforms: /*@__PURE__*/ mergeUniforms( [
  8256. UniformsLib.lights,
  8257. UniformsLib.fog,
  8258. {
  8259. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  8260. opacity: { value: 1.0 }
  8261. },
  8262. ] ),
  8263. vertexShader: ShaderChunk.shadow_vert,
  8264. fragmentShader: ShaderChunk.shadow_frag
  8265. }
  8266. };
  8267. ShaderLib.physical = {
  8268. uniforms: /*@__PURE__*/ mergeUniforms( [
  8269. ShaderLib.standard.uniforms,
  8270. {
  8271. clearcoat: { value: 0 },
  8272. clearcoatMap: { value: null },
  8273. clearcoatRoughness: { value: 0 },
  8274. clearcoatRoughnessMap: { value: null },
  8275. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  8276. clearcoatNormalMap: { value: null },
  8277. iridescence: { value: 0 },
  8278. iridescenceMap: { value: null },
  8279. iridescenceIOR: { value: 1.3 },
  8280. iridescenceThicknessMinimum: { value: 100 },
  8281. iridescenceThicknessMaximum: { value: 400 },
  8282. iridescenceThicknessMap: { value: null },
  8283. sheen: { value: 0 },
  8284. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8285. sheenColorMap: { value: null },
  8286. sheenRoughness: { value: 1 },
  8287. sheenRoughnessMap: { value: null },
  8288. transmission: { value: 0 },
  8289. transmissionMap: { value: null },
  8290. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  8291. transmissionSamplerMap: { value: null },
  8292. thickness: { value: 0 },
  8293. thicknessMap: { value: null },
  8294. attenuationDistance: { value: 0 },
  8295. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  8296. specularIntensity: { value: 1 },
  8297. specularIntensityMap: { value: null },
  8298. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  8299. specularColorMap: { value: null },
  8300. }
  8301. ] ),
  8302. vertexShader: ShaderChunk.meshphysical_vert,
  8303. fragmentShader: ShaderChunk.meshphysical_frag
  8304. };
  8305. function WebGLBackground( renderer, cubemaps, state, objects, alpha, premultipliedAlpha ) {
  8306. const clearColor = new Color( 0x000000 );
  8307. let clearAlpha = alpha === true ? 0 : 1;
  8308. let planeMesh;
  8309. let boxMesh;
  8310. let currentBackground = null;
  8311. let currentBackgroundVersion = 0;
  8312. let currentTonemapping = null;
  8313. function render( renderList, scene ) {
  8314. let forceClear = false;
  8315. let background = scene.isScene === true ? scene.background : null;
  8316. if ( background && background.isTexture ) {
  8317. background = cubemaps.get( background );
  8318. }
  8319. // Ignore background in AR
  8320. // TODO: Reconsider this.
  8321. const xr = renderer.xr;
  8322. const session = xr.getSession && xr.getSession();
  8323. if ( session && session.environmentBlendMode === 'additive' ) {
  8324. background = null;
  8325. }
  8326. if ( background === null ) {
  8327. setClear( clearColor, clearAlpha );
  8328. } else if ( background && background.isColor ) {
  8329. setClear( background, 1 );
  8330. forceClear = true;
  8331. }
  8332. if ( renderer.autoClear || forceClear ) {
  8333. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  8334. }
  8335. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  8336. if ( boxMesh === undefined ) {
  8337. boxMesh = new Mesh(
  8338. new BoxGeometry( 1, 1, 1 ),
  8339. new ShaderMaterial( {
  8340. name: 'BackgroundCubeMaterial',
  8341. uniforms: cloneUniforms( ShaderLib.cube.uniforms ),
  8342. vertexShader: ShaderLib.cube.vertexShader,
  8343. fragmentShader: ShaderLib.cube.fragmentShader,
  8344. side: BackSide,
  8345. depthTest: false,
  8346. depthWrite: false,
  8347. fog: false
  8348. } )
  8349. );
  8350. boxMesh.geometry.deleteAttribute( 'normal' );
  8351. boxMesh.geometry.deleteAttribute( 'uv' );
  8352. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  8353. this.matrixWorld.copyPosition( camera.matrixWorld );
  8354. };
  8355. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  8356. Object.defineProperty( boxMesh.material, 'envMap', {
  8357. get: function () {
  8358. return this.uniforms.envMap.value;
  8359. }
  8360. } );
  8361. objects.update( boxMesh );
  8362. }
  8363. boxMesh.material.uniforms.envMap.value = background;
  8364. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? - 1 : 1;
  8365. if ( currentBackground !== background ||
  8366. currentBackgroundVersion !== background.version ||
  8367. currentTonemapping !== renderer.toneMapping ) {
  8368. boxMesh.material.needsUpdate = true;
  8369. currentBackground = background;
  8370. currentBackgroundVersion = background.version;
  8371. currentTonemapping = renderer.toneMapping;
  8372. }
  8373. boxMesh.layers.enableAll();
  8374. // push to the pre-sorted opaque render list
  8375. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  8376. } else if ( background && background.isTexture ) {
  8377. if ( planeMesh === undefined ) {
  8378. planeMesh = new Mesh(
  8379. new PlaneGeometry( 2, 2 ),
  8380. new ShaderMaterial( {
  8381. name: 'BackgroundMaterial',
  8382. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  8383. vertexShader: ShaderLib.background.vertexShader,
  8384. fragmentShader: ShaderLib.background.fragmentShader,
  8385. side: FrontSide,
  8386. depthTest: false,
  8387. depthWrite: false,
  8388. fog: false
  8389. } )
  8390. );
  8391. planeMesh.geometry.deleteAttribute( 'normal' );
  8392. // add "map" material property so the renderer can evaluate it like for built-in materials
  8393. Object.defineProperty( planeMesh.material, 'map', {
  8394. get: function () {
  8395. return this.uniforms.t2D.value;
  8396. }
  8397. } );
  8398. objects.update( planeMesh );
  8399. }
  8400. planeMesh.material.uniforms.t2D.value = background;
  8401. if ( background.matrixAutoUpdate === true ) {
  8402. background.updateMatrix();
  8403. }
  8404. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  8405. if ( currentBackground !== background ||
  8406. currentBackgroundVersion !== background.version ||
  8407. currentTonemapping !== renderer.toneMapping ) {
  8408. planeMesh.material.needsUpdate = true;
  8409. currentBackground = background;
  8410. currentBackgroundVersion = background.version;
  8411. currentTonemapping = renderer.toneMapping;
  8412. }
  8413. planeMesh.layers.enableAll();
  8414. // push to the pre-sorted opaque render list
  8415. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  8416. }
  8417. }
  8418. function setClear( color, alpha ) {
  8419. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  8420. }
  8421. return {
  8422. getClearColor: function () {
  8423. return clearColor;
  8424. },
  8425. setClearColor: function ( color, alpha = 1 ) {
  8426. clearColor.set( color );
  8427. clearAlpha = alpha;
  8428. setClear( clearColor, clearAlpha );
  8429. },
  8430. getClearAlpha: function () {
  8431. return clearAlpha;
  8432. },
  8433. setClearAlpha: function ( alpha ) {
  8434. clearAlpha = alpha;
  8435. setClear( clearColor, clearAlpha );
  8436. },
  8437. render: render
  8438. };
  8439. }
  8440. function WebGLBindingStates( gl, extensions, attributes, capabilities ) {
  8441. const maxVertexAttributes = gl.getParameter( 34921 );
  8442. const extension = capabilities.isWebGL2 ? null : extensions.get( 'OES_vertex_array_object' );
  8443. const vaoAvailable = capabilities.isWebGL2 || extension !== null;
  8444. const bindingStates = {};
  8445. const defaultState = createBindingState( null );
  8446. let currentState = defaultState;
  8447. let forceUpdate = false;
  8448. function setup( object, material, program, geometry, index ) {
  8449. let updateBuffers = false;
  8450. if ( vaoAvailable ) {
  8451. const state = getBindingState( geometry, program, material );
  8452. if ( currentState !== state ) {
  8453. currentState = state;
  8454. bindVertexArrayObject( currentState.object );
  8455. }
  8456. updateBuffers = needsUpdate( object, geometry, program, index );
  8457. if ( updateBuffers ) saveCache( object, geometry, program, index );
  8458. } else {
  8459. const wireframe = ( material.wireframe === true );
  8460. if ( currentState.geometry !== geometry.id ||
  8461. currentState.program !== program.id ||
  8462. currentState.wireframe !== wireframe ) {
  8463. currentState.geometry = geometry.id;
  8464. currentState.program = program.id;
  8465. currentState.wireframe = wireframe;
  8466. updateBuffers = true;
  8467. }
  8468. }
  8469. if ( index !== null ) {
  8470. attributes.update( index, 34963 );
  8471. }
  8472. if ( updateBuffers || forceUpdate ) {
  8473. forceUpdate = false;
  8474. setupVertexAttributes( object, material, program, geometry );
  8475. if ( index !== null ) {
  8476. gl.bindBuffer( 34963, attributes.get( index ).buffer );
  8477. }
  8478. }
  8479. }
  8480. function createVertexArrayObject() {
  8481. if ( capabilities.isWebGL2 ) return gl.createVertexArray();
  8482. return extension.createVertexArrayOES();
  8483. }
  8484. function bindVertexArrayObject( vao ) {
  8485. if ( capabilities.isWebGL2 ) return gl.bindVertexArray( vao );
  8486. return extension.bindVertexArrayOES( vao );
  8487. }
  8488. function deleteVertexArrayObject( vao ) {
  8489. if ( capabilities.isWebGL2 ) return gl.deleteVertexArray( vao );
  8490. return extension.deleteVertexArrayOES( vao );
  8491. }
  8492. function getBindingState( geometry, program, material ) {
  8493. const wireframe = ( material.wireframe === true );
  8494. let programMap = bindingStates[ geometry.id ];
  8495. if ( programMap === undefined ) {
  8496. programMap = {};
  8497. bindingStates[ geometry.id ] = programMap;
  8498. }
  8499. let stateMap = programMap[ program.id ];
  8500. if ( stateMap === undefined ) {
  8501. stateMap = {};
  8502. programMap[ program.id ] = stateMap;
  8503. }
  8504. let state = stateMap[ wireframe ];
  8505. if ( state === undefined ) {
  8506. state = createBindingState( createVertexArrayObject() );
  8507. stateMap[ wireframe ] = state;
  8508. }
  8509. return state;
  8510. }
  8511. function createBindingState( vao ) {
  8512. const newAttributes = [];
  8513. const enabledAttributes = [];
  8514. const attributeDivisors = [];
  8515. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  8516. newAttributes[ i ] = 0;
  8517. enabledAttributes[ i ] = 0;
  8518. attributeDivisors[ i ] = 0;
  8519. }
  8520. return {
  8521. // for backward compatibility on non-VAO support browser
  8522. geometry: null,
  8523. program: null,
  8524. wireframe: false,
  8525. newAttributes: newAttributes,
  8526. enabledAttributes: enabledAttributes,
  8527. attributeDivisors: attributeDivisors,
  8528. object: vao,
  8529. attributes: {},
  8530. index: null
  8531. };
  8532. }
  8533. function needsUpdate( object, geometry, program, index ) {
  8534. const cachedAttributes = currentState.attributes;
  8535. const geometryAttributes = geometry.attributes;
  8536. let attributesNum = 0;
  8537. const programAttributes = program.getAttributes();
  8538. for ( const name in programAttributes ) {
  8539. const programAttribute = programAttributes[ name ];
  8540. if ( programAttribute.location >= 0 ) {
  8541. const cachedAttribute = cachedAttributes[ name ];
  8542. let geometryAttribute = geometryAttributes[ name ];
  8543. if ( geometryAttribute === undefined ) {
  8544. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8545. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8546. }
  8547. if ( cachedAttribute === undefined ) return true;
  8548. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  8549. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  8550. attributesNum ++;
  8551. }
  8552. }
  8553. if ( currentState.attributesNum !== attributesNum ) return true;
  8554. if ( currentState.index !== index ) return true;
  8555. return false;
  8556. }
  8557. function saveCache( object, geometry, program, index ) {
  8558. const cache = {};
  8559. const attributes = geometry.attributes;
  8560. let attributesNum = 0;
  8561. const programAttributes = program.getAttributes();
  8562. for ( const name in programAttributes ) {
  8563. const programAttribute = programAttributes[ name ];
  8564. if ( programAttribute.location >= 0 ) {
  8565. let attribute = attributes[ name ];
  8566. if ( attribute === undefined ) {
  8567. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  8568. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  8569. }
  8570. const data = {};
  8571. data.attribute = attribute;
  8572. if ( attribute && attribute.data ) {
  8573. data.data = attribute.data;
  8574. }
  8575. cache[ name ] = data;
  8576. attributesNum ++;
  8577. }
  8578. }
  8579. currentState.attributes = cache;
  8580. currentState.attributesNum = attributesNum;
  8581. currentState.index = index;
  8582. }
  8583. function initAttributes() {
  8584. const newAttributes = currentState.newAttributes;
  8585. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  8586. newAttributes[ i ] = 0;
  8587. }
  8588. }
  8589. function enableAttribute( attribute ) {
  8590. enableAttributeAndDivisor( attribute, 0 );
  8591. }
  8592. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  8593. const newAttributes = currentState.newAttributes;
  8594. const enabledAttributes = currentState.enabledAttributes;
  8595. const attributeDivisors = currentState.attributeDivisors;
  8596. newAttributes[ attribute ] = 1;
  8597. if ( enabledAttributes[ attribute ] === 0 ) {
  8598. gl.enableVertexAttribArray( attribute );
  8599. enabledAttributes[ attribute ] = 1;
  8600. }
  8601. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  8602. const extension = capabilities.isWebGL2 ? gl : extensions.get( 'ANGLE_instanced_arrays' );
  8603. extension[ capabilities.isWebGL2 ? 'vertexAttribDivisor' : 'vertexAttribDivisorANGLE' ]( attribute, meshPerAttribute );
  8604. attributeDivisors[ attribute ] = meshPerAttribute;
  8605. }
  8606. }
  8607. function disableUnusedAttributes() {
  8608. const newAttributes = currentState.newAttributes;
  8609. const enabledAttributes = currentState.enabledAttributes;
  8610. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  8611. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  8612. gl.disableVertexAttribArray( i );
  8613. enabledAttributes[ i ] = 0;
  8614. }
  8615. }
  8616. }
  8617. function vertexAttribPointer( index, size, type, normalized, stride, offset ) {
  8618. if ( capabilities.isWebGL2 === true && ( type === 5124 || type === 5125 ) ) {
  8619. gl.vertexAttribIPointer( index, size, type, stride, offset );
  8620. } else {
  8621. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  8622. }
  8623. }
  8624. function setupVertexAttributes( object, material, program, geometry ) {
  8625. if ( capabilities.isWebGL2 === false && ( object.isInstancedMesh || geometry.isInstancedBufferGeometry ) ) {
  8626. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) return;
  8627. }
  8628. initAttributes();
  8629. const geometryAttributes = geometry.attributes;
  8630. const programAttributes = program.getAttributes();
  8631. const materialDefaultAttributeValues = material.defaultAttributeValues;
  8632. for ( const name in programAttributes ) {
  8633. const programAttribute = programAttributes[ name ];
  8634. if ( programAttribute.location >= 0 ) {
  8635. let geometryAttribute = geometryAttributes[ name ];
  8636. if ( geometryAttribute === undefined ) {
  8637. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  8638. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  8639. }
  8640. if ( geometryAttribute !== undefined ) {
  8641. const normalized = geometryAttribute.normalized;
  8642. const size = geometryAttribute.itemSize;
  8643. const attribute = attributes.get( geometryAttribute );
  8644. // TODO Attribute may not be available on context restore
  8645. if ( attribute === undefined ) continue;
  8646. const buffer = attribute.buffer;
  8647. const type = attribute.type;
  8648. const bytesPerElement = attribute.bytesPerElement;
  8649. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  8650. const data = geometryAttribute.data;
  8651. const stride = data.stride;
  8652. const offset = geometryAttribute.offset;
  8653. if ( data.isInstancedInterleavedBuffer ) {
  8654. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8655. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  8656. }
  8657. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8658. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  8659. }
  8660. } else {
  8661. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8662. enableAttribute( programAttribute.location + i );
  8663. }
  8664. }
  8665. gl.bindBuffer( 34962, buffer );
  8666. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8667. vertexAttribPointer(
  8668. programAttribute.location + i,
  8669. size / programAttribute.locationSize,
  8670. type,
  8671. normalized,
  8672. stride * bytesPerElement,
  8673. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement
  8674. );
  8675. }
  8676. } else {
  8677. if ( geometryAttribute.isInstancedBufferAttribute ) {
  8678. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8679. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  8680. }
  8681. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  8682. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  8683. }
  8684. } else {
  8685. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8686. enableAttribute( programAttribute.location + i );
  8687. }
  8688. }
  8689. gl.bindBuffer( 34962, buffer );
  8690. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  8691. vertexAttribPointer(
  8692. programAttribute.location + i,
  8693. size / programAttribute.locationSize,
  8694. type,
  8695. normalized,
  8696. size * bytesPerElement,
  8697. ( size / programAttribute.locationSize ) * i * bytesPerElement
  8698. );
  8699. }
  8700. }
  8701. } else if ( materialDefaultAttributeValues !== undefined ) {
  8702. const value = materialDefaultAttributeValues[ name ];
  8703. if ( value !== undefined ) {
  8704. switch ( value.length ) {
  8705. case 2:
  8706. gl.vertexAttrib2fv( programAttribute.location, value );
  8707. break;
  8708. case 3:
  8709. gl.vertexAttrib3fv( programAttribute.location, value );
  8710. break;
  8711. case 4:
  8712. gl.vertexAttrib4fv( programAttribute.location, value );
  8713. break;
  8714. default:
  8715. gl.vertexAttrib1fv( programAttribute.location, value );
  8716. }
  8717. }
  8718. }
  8719. }
  8720. }
  8721. disableUnusedAttributes();
  8722. }
  8723. function dispose() {
  8724. reset();
  8725. for ( const geometryId in bindingStates ) {
  8726. const programMap = bindingStates[ geometryId ];
  8727. for ( const programId in programMap ) {
  8728. const stateMap = programMap[ programId ];
  8729. for ( const wireframe in stateMap ) {
  8730. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8731. delete stateMap[ wireframe ];
  8732. }
  8733. delete programMap[ programId ];
  8734. }
  8735. delete bindingStates[ geometryId ];
  8736. }
  8737. }
  8738. function releaseStatesOfGeometry( geometry ) {
  8739. if ( bindingStates[ geometry.id ] === undefined ) return;
  8740. const programMap = bindingStates[ geometry.id ];
  8741. for ( const programId in programMap ) {
  8742. const stateMap = programMap[ programId ];
  8743. for ( const wireframe in stateMap ) {
  8744. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8745. delete stateMap[ wireframe ];
  8746. }
  8747. delete programMap[ programId ];
  8748. }
  8749. delete bindingStates[ geometry.id ];
  8750. }
  8751. function releaseStatesOfProgram( program ) {
  8752. for ( const geometryId in bindingStates ) {
  8753. const programMap = bindingStates[ geometryId ];
  8754. if ( programMap[ program.id ] === undefined ) continue;
  8755. const stateMap = programMap[ program.id ];
  8756. for ( const wireframe in stateMap ) {
  8757. deleteVertexArrayObject( stateMap[ wireframe ].object );
  8758. delete stateMap[ wireframe ];
  8759. }
  8760. delete programMap[ program.id ];
  8761. }
  8762. }
  8763. function reset() {
  8764. resetDefaultState();
  8765. forceUpdate = true;
  8766. if ( currentState === defaultState ) return;
  8767. currentState = defaultState;
  8768. bindVertexArrayObject( currentState.object );
  8769. }
  8770. // for backward-compatibility
  8771. function resetDefaultState() {
  8772. defaultState.geometry = null;
  8773. defaultState.program = null;
  8774. defaultState.wireframe = false;
  8775. }
  8776. return {
  8777. setup: setup,
  8778. reset: reset,
  8779. resetDefaultState: resetDefaultState,
  8780. dispose: dispose,
  8781. releaseStatesOfGeometry: releaseStatesOfGeometry,
  8782. releaseStatesOfProgram: releaseStatesOfProgram,
  8783. initAttributes: initAttributes,
  8784. enableAttribute: enableAttribute,
  8785. disableUnusedAttributes: disableUnusedAttributes
  8786. };
  8787. }
  8788. function WebGLBufferRenderer( gl, extensions, info, capabilities ) {
  8789. const isWebGL2 = capabilities.isWebGL2;
  8790. let mode;
  8791. function setMode( value ) {
  8792. mode = value;
  8793. }
  8794. function render( start, count ) {
  8795. gl.drawArrays( mode, start, count );
  8796. info.update( count, mode, 1 );
  8797. }
  8798. function renderInstances( start, count, primcount ) {
  8799. if ( primcount === 0 ) return;
  8800. let extension, methodName;
  8801. if ( isWebGL2 ) {
  8802. extension = gl;
  8803. methodName = 'drawArraysInstanced';
  8804. } else {
  8805. extension = extensions.get( 'ANGLE_instanced_arrays' );
  8806. methodName = 'drawArraysInstancedANGLE';
  8807. if ( extension === null ) {
  8808. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  8809. return;
  8810. }
  8811. }
  8812. extension[ methodName ]( mode, start, count, primcount );
  8813. info.update( count, mode, primcount );
  8814. }
  8815. //
  8816. this.setMode = setMode;
  8817. this.render = render;
  8818. this.renderInstances = renderInstances;
  8819. }
  8820. function WebGLCapabilities( gl, extensions, parameters ) {
  8821. let maxAnisotropy;
  8822. function getMaxAnisotropy() {
  8823. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  8824. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  8825. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  8826. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  8827. } else {
  8828. maxAnisotropy = 0;
  8829. }
  8830. return maxAnisotropy;
  8831. }
  8832. function getMaxPrecision( precision ) {
  8833. if ( precision === 'highp' ) {
  8834. if ( gl.getShaderPrecisionFormat( 35633, 36338 ).precision > 0 &&
  8835. gl.getShaderPrecisionFormat( 35632, 36338 ).precision > 0 ) {
  8836. return 'highp';
  8837. }
  8838. precision = 'mediump';
  8839. }
  8840. if ( precision === 'mediump' ) {
  8841. if ( gl.getShaderPrecisionFormat( 35633, 36337 ).precision > 0 &&
  8842. gl.getShaderPrecisionFormat( 35632, 36337 ).precision > 0 ) {
  8843. return 'mediump';
  8844. }
  8845. }
  8846. return 'lowp';
  8847. }
  8848. const isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext ) ||
  8849. ( typeof WebGL2ComputeRenderingContext !== 'undefined' && gl instanceof WebGL2ComputeRenderingContext );
  8850. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  8851. const maxPrecision = getMaxPrecision( precision );
  8852. if ( maxPrecision !== precision ) {
  8853. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  8854. precision = maxPrecision;
  8855. }
  8856. const drawBuffers = isWebGL2 || extensions.has( 'WEBGL_draw_buffers' );
  8857. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  8858. const maxTextures = gl.getParameter( 34930 );
  8859. const maxVertexTextures = gl.getParameter( 35660 );
  8860. const maxTextureSize = gl.getParameter( 3379 );
  8861. const maxCubemapSize = gl.getParameter( 34076 );
  8862. const maxAttributes = gl.getParameter( 34921 );
  8863. const maxVertexUniforms = gl.getParameter( 36347 );
  8864. const maxVaryings = gl.getParameter( 36348 );
  8865. const maxFragmentUniforms = gl.getParameter( 36349 );
  8866. const vertexTextures = maxVertexTextures > 0;
  8867. const floatFragmentTextures = isWebGL2 || extensions.has( 'OES_texture_float' );
  8868. const floatVertexTextures = vertexTextures && floatFragmentTextures;
  8869. const maxSamples = isWebGL2 ? gl.getParameter( 36183 ) : 0;
  8870. return {
  8871. isWebGL2: isWebGL2,
  8872. drawBuffers: drawBuffers,
  8873. getMaxAnisotropy: getMaxAnisotropy,
  8874. getMaxPrecision: getMaxPrecision,
  8875. precision: precision,
  8876. logarithmicDepthBuffer: logarithmicDepthBuffer,
  8877. maxTextures: maxTextures,
  8878. maxVertexTextures: maxVertexTextures,
  8879. maxTextureSize: maxTextureSize,
  8880. maxCubemapSize: maxCubemapSize,
  8881. maxAttributes: maxAttributes,
  8882. maxVertexUniforms: maxVertexUniforms,
  8883. maxVaryings: maxVaryings,
  8884. maxFragmentUniforms: maxFragmentUniforms,
  8885. vertexTextures: vertexTextures,
  8886. floatFragmentTextures: floatFragmentTextures,
  8887. floatVertexTextures: floatVertexTextures,
  8888. maxSamples: maxSamples
  8889. };
  8890. }
  8891. function WebGLClipping( properties ) {
  8892. const scope = this;
  8893. let globalState = null,
  8894. numGlobalPlanes = 0,
  8895. localClippingEnabled = false,
  8896. renderingShadows = false;
  8897. const plane = new Plane(),
  8898. viewNormalMatrix = new Matrix3(),
  8899. uniform = { value: null, needsUpdate: false };
  8900. this.uniform = uniform;
  8901. this.numPlanes = 0;
  8902. this.numIntersection = 0;
  8903. this.init = function ( planes, enableLocalClipping, camera ) {
  8904. const enabled =
  8905. planes.length !== 0 ||
  8906. enableLocalClipping ||
  8907. // enable state of previous frame - the clipping code has to
  8908. // run another frame in order to reset the state:
  8909. numGlobalPlanes !== 0 ||
  8910. localClippingEnabled;
  8911. localClippingEnabled = enableLocalClipping;
  8912. globalState = projectPlanes( planes, camera, 0 );
  8913. numGlobalPlanes = planes.length;
  8914. return enabled;
  8915. };
  8916. this.beginShadows = function () {
  8917. renderingShadows = true;
  8918. projectPlanes( null );
  8919. };
  8920. this.endShadows = function () {
  8921. renderingShadows = false;
  8922. resetGlobalState();
  8923. };
  8924. this.setState = function ( material, camera, useCache ) {
  8925. const planes = material.clippingPlanes,
  8926. clipIntersection = material.clipIntersection,
  8927. clipShadows = material.clipShadows;
  8928. const materialProperties = properties.get( material );
  8929. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  8930. // there's no local clipping
  8931. if ( renderingShadows ) {
  8932. // there's no global clipping
  8933. projectPlanes( null );
  8934. } else {
  8935. resetGlobalState();
  8936. }
  8937. } else {
  8938. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  8939. lGlobal = nGlobal * 4;
  8940. let dstArray = materialProperties.clippingState || null;
  8941. uniform.value = dstArray; // ensure unique state
  8942. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  8943. for ( let i = 0; i !== lGlobal; ++ i ) {
  8944. dstArray[ i ] = globalState[ i ];
  8945. }
  8946. materialProperties.clippingState = dstArray;
  8947. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  8948. this.numPlanes += nGlobal;
  8949. }
  8950. };
  8951. function resetGlobalState() {
  8952. if ( uniform.value !== globalState ) {
  8953. uniform.value = globalState;
  8954. uniform.needsUpdate = numGlobalPlanes > 0;
  8955. }
  8956. scope.numPlanes = numGlobalPlanes;
  8957. scope.numIntersection = 0;
  8958. }
  8959. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  8960. const nPlanes = planes !== null ? planes.length : 0;
  8961. let dstArray = null;
  8962. if ( nPlanes !== 0 ) {
  8963. dstArray = uniform.value;
  8964. if ( skipTransform !== true || dstArray === null ) {
  8965. const flatSize = dstOffset + nPlanes * 4,
  8966. viewMatrix = camera.matrixWorldInverse;
  8967. viewNormalMatrix.getNormalMatrix( viewMatrix );
  8968. if ( dstArray === null || dstArray.length < flatSize ) {
  8969. dstArray = new Float32Array( flatSize );
  8970. }
  8971. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  8972. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  8973. plane.normal.toArray( dstArray, i4 );
  8974. dstArray[ i4 + 3 ] = plane.constant;
  8975. }
  8976. }
  8977. uniform.value = dstArray;
  8978. uniform.needsUpdate = true;
  8979. }
  8980. scope.numPlanes = nPlanes;
  8981. scope.numIntersection = 0;
  8982. return dstArray;
  8983. }
  8984. }
  8985. function WebGLCubeMaps( renderer ) {
  8986. let cubemaps = new WeakMap();
  8987. function mapTextureMapping( texture, mapping ) {
  8988. if ( mapping === EquirectangularReflectionMapping ) {
  8989. texture.mapping = CubeReflectionMapping;
  8990. } else if ( mapping === EquirectangularRefractionMapping ) {
  8991. texture.mapping = CubeRefractionMapping;
  8992. }
  8993. return texture;
  8994. }
  8995. function get( texture ) {
  8996. if ( texture && texture.isTexture && texture.isRenderTargetTexture === false ) {
  8997. const mapping = texture.mapping;
  8998. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  8999. if ( cubemaps.has( texture ) ) {
  9000. const cubemap = cubemaps.get( texture ).texture;
  9001. return mapTextureMapping( cubemap, texture.mapping );
  9002. } else {
  9003. const image = texture.image;
  9004. if ( image && image.height > 0 ) {
  9005. const renderTarget = new WebGLCubeRenderTarget( image.height / 2 );
  9006. renderTarget.fromEquirectangularTexture( renderer, texture );
  9007. cubemaps.set( texture, renderTarget );
  9008. texture.addEventListener( 'dispose', onTextureDispose );
  9009. return mapTextureMapping( renderTarget.texture, texture.mapping );
  9010. } else {
  9011. // image not yet ready. try the conversion next frame
  9012. return null;
  9013. }
  9014. }
  9015. }
  9016. }
  9017. return texture;
  9018. }
  9019. function onTextureDispose( event ) {
  9020. const texture = event.target;
  9021. texture.removeEventListener( 'dispose', onTextureDispose );
  9022. const cubemap = cubemaps.get( texture );
  9023. if ( cubemap !== undefined ) {
  9024. cubemaps.delete( texture );
  9025. cubemap.dispose();
  9026. }
  9027. }
  9028. function dispose() {
  9029. cubemaps = new WeakMap();
  9030. }
  9031. return {
  9032. get: get,
  9033. dispose: dispose
  9034. };
  9035. }
  9036. class OrthographicCamera extends Camera {
  9037. constructor( left = - 1, right = 1, top = 1, bottom = - 1, near = 0.1, far = 2000 ) {
  9038. super();
  9039. this.isOrthographicCamera = true;
  9040. this.type = 'OrthographicCamera';
  9041. this.zoom = 1;
  9042. this.view = null;
  9043. this.left = left;
  9044. this.right = right;
  9045. this.top = top;
  9046. this.bottom = bottom;
  9047. this.near = near;
  9048. this.far = far;
  9049. this.updateProjectionMatrix();
  9050. }
  9051. copy( source, recursive ) {
  9052. super.copy( source, recursive );
  9053. this.left = source.left;
  9054. this.right = source.right;
  9055. this.top = source.top;
  9056. this.bottom = source.bottom;
  9057. this.near = source.near;
  9058. this.far = source.far;
  9059. this.zoom = source.zoom;
  9060. this.view = source.view === null ? null : Object.assign( {}, source.view );
  9061. return this;
  9062. }
  9063. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  9064. if ( this.view === null ) {
  9065. this.view = {
  9066. enabled: true,
  9067. fullWidth: 1,
  9068. fullHeight: 1,
  9069. offsetX: 0,
  9070. offsetY: 0,
  9071. width: 1,
  9072. height: 1
  9073. };
  9074. }
  9075. this.view.enabled = true;
  9076. this.view.fullWidth = fullWidth;
  9077. this.view.fullHeight = fullHeight;
  9078. this.view.offsetX = x;
  9079. this.view.offsetY = y;
  9080. this.view.width = width;
  9081. this.view.height = height;
  9082. this.updateProjectionMatrix();
  9083. }
  9084. clearViewOffset() {
  9085. if ( this.view !== null ) {
  9086. this.view.enabled = false;
  9087. }
  9088. this.updateProjectionMatrix();
  9089. }
  9090. updateProjectionMatrix() {
  9091. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9092. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9093. const cx = ( this.right + this.left ) / 2;
  9094. const cy = ( this.top + this.bottom ) / 2;
  9095. let left = cx - dx;
  9096. let right = cx + dx;
  9097. let top = cy + dy;
  9098. let bottom = cy - dy;
  9099. if ( this.view !== null && this.view.enabled ) {
  9100. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  9101. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  9102. left += scaleW * this.view.offsetX;
  9103. right = left + scaleW * this.view.width;
  9104. top -= scaleH * this.view.offsetY;
  9105. bottom = top - scaleH * this.view.height;
  9106. }
  9107. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  9108. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  9109. }
  9110. toJSON( meta ) {
  9111. const data = super.toJSON( meta );
  9112. data.object.zoom = this.zoom;
  9113. data.object.left = this.left;
  9114. data.object.right = this.right;
  9115. data.object.top = this.top;
  9116. data.object.bottom = this.bottom;
  9117. data.object.near = this.near;
  9118. data.object.far = this.far;
  9119. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  9120. return data;
  9121. }
  9122. }
  9123. const LOD_MIN = 4;
  9124. // The standard deviations (radians) associated with the extra mips. These are
  9125. // chosen to approximate a Trowbridge-Reitz distribution function times the
  9126. // geometric shadowing function. These sigma values squared must match the
  9127. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  9128. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  9129. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  9130. // samples and exit early, but not recompile the shader.
  9131. const MAX_SAMPLES = 20;
  9132. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  9133. const _clearColor = /*@__PURE__*/ new Color();
  9134. let _oldTarget = null;
  9135. // Golden Ratio
  9136. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  9137. const INV_PHI = 1 / PHI;
  9138. // Vertices of a dodecahedron (except the opposites, which represent the
  9139. // same axis), used as axis directions evenly spread on a sphere.
  9140. const _axisDirections = [
  9141. /*@__PURE__*/ new Vector3( 1, 1, 1 ),
  9142. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  9143. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  9144. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  9145. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  9146. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  9147. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  9148. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  9149. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  9150. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ) ];
  9151. /**
  9152. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  9153. * (PMREM) from a cubeMap environment texture. This allows different levels of
  9154. * blur to be quickly accessed based on material roughness. It is packed into a
  9155. * special CubeUV format that allows us to perform custom interpolation so that
  9156. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  9157. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  9158. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  9159. * higher roughness levels. In this way we maintain resolution to smoothly
  9160. * interpolate diffuse lighting while limiting sampling computation.
  9161. *
  9162. * Paper: Fast, Accurate Image-Based Lighting
  9163. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  9164. */
  9165. class PMREMGenerator {
  9166. constructor( renderer ) {
  9167. this._renderer = renderer;
  9168. this._pingPongRenderTarget = null;
  9169. this._lodMax = 0;
  9170. this._cubeSize = 0;
  9171. this._lodPlanes = [];
  9172. this._sizeLods = [];
  9173. this._sigmas = [];
  9174. this._blurMaterial = null;
  9175. this._cubemapMaterial = null;
  9176. this._equirectMaterial = null;
  9177. this._compileMaterial( this._blurMaterial );
  9178. }
  9179. /**
  9180. * Generates a PMREM from a supplied Scene, which can be faster than using an
  9181. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  9182. * in radians to be applied to the scene before PMREM generation. Optional near
  9183. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  9184. * is placed at the origin).
  9185. */
  9186. fromScene( scene, sigma = 0, near = 0.1, far = 100 ) {
  9187. _oldTarget = this._renderer.getRenderTarget();
  9188. this._setSize( 256 );
  9189. const cubeUVRenderTarget = this._allocateTargets();
  9190. cubeUVRenderTarget.depthBuffer = true;
  9191. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  9192. if ( sigma > 0 ) {
  9193. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  9194. }
  9195. this._applyPMREM( cubeUVRenderTarget );
  9196. this._cleanup( cubeUVRenderTarget );
  9197. return cubeUVRenderTarget;
  9198. }
  9199. /**
  9200. * Generates a PMREM from an equirectangular texture, which can be either LDR
  9201. * or HDR. The ideal input image size is 1k (1024 x 512),
  9202. * as this matches best with the 256 x 256 cubemap output.
  9203. */
  9204. fromEquirectangular( equirectangular, renderTarget = null ) {
  9205. return this._fromTexture( equirectangular, renderTarget );
  9206. }
  9207. /**
  9208. * Generates a PMREM from an cubemap texture, which can be either LDR
  9209. * or HDR. The ideal input cube size is 256 x 256,
  9210. * as this matches best with the 256 x 256 cubemap output.
  9211. */
  9212. fromCubemap( cubemap, renderTarget = null ) {
  9213. return this._fromTexture( cubemap, renderTarget );
  9214. }
  9215. /**
  9216. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  9217. * your texture's network fetch for increased concurrency.
  9218. */
  9219. compileCubemapShader() {
  9220. if ( this._cubemapMaterial === null ) {
  9221. this._cubemapMaterial = _getCubemapMaterial();
  9222. this._compileMaterial( this._cubemapMaterial );
  9223. }
  9224. }
  9225. /**
  9226. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  9227. * your texture's network fetch for increased concurrency.
  9228. */
  9229. compileEquirectangularShader() {
  9230. if ( this._equirectMaterial === null ) {
  9231. this._equirectMaterial = _getEquirectMaterial();
  9232. this._compileMaterial( this._equirectMaterial );
  9233. }
  9234. }
  9235. /**
  9236. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  9237. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  9238. * one of them will cause any others to also become unusable.
  9239. */
  9240. dispose() {
  9241. this._dispose();
  9242. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  9243. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  9244. }
  9245. // private interface
  9246. _setSize( cubeSize ) {
  9247. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  9248. this._cubeSize = Math.pow( 2, this._lodMax );
  9249. }
  9250. _dispose() {
  9251. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  9252. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  9253. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  9254. this._lodPlanes[ i ].dispose();
  9255. }
  9256. }
  9257. _cleanup( outputTarget ) {
  9258. this._renderer.setRenderTarget( _oldTarget );
  9259. outputTarget.scissorTest = false;
  9260. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  9261. }
  9262. _fromTexture( texture, renderTarget ) {
  9263. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  9264. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  9265. } else { // Equirectangular
  9266. this._setSize( texture.image.width / 4 );
  9267. }
  9268. _oldTarget = this._renderer.getRenderTarget();
  9269. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  9270. this._textureToCubeUV( texture, cubeUVRenderTarget );
  9271. this._applyPMREM( cubeUVRenderTarget );
  9272. this._cleanup( cubeUVRenderTarget );
  9273. return cubeUVRenderTarget;
  9274. }
  9275. _allocateTargets() {
  9276. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  9277. const height = 4 * this._cubeSize;
  9278. const params = {
  9279. magFilter: LinearFilter,
  9280. minFilter: LinearFilter,
  9281. generateMipmaps: false,
  9282. type: HalfFloatType,
  9283. format: RGBAFormat,
  9284. encoding: LinearEncoding,
  9285. depthBuffer: false
  9286. };
  9287. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  9288. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width ) {
  9289. if ( this._pingPongRenderTarget !== null ) {
  9290. this._dispose();
  9291. }
  9292. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  9293. const { _lodMax } = this;
  9294. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  9295. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  9296. }
  9297. return cubeUVRenderTarget;
  9298. }
  9299. _compileMaterial( material ) {
  9300. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  9301. this._renderer.compile( tmpMesh, _flatCamera );
  9302. }
  9303. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  9304. const fov = 90;
  9305. const aspect = 1;
  9306. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  9307. const upSign = [ 1, - 1, 1, 1, 1, 1 ];
  9308. const forwardSign = [ 1, 1, 1, - 1, - 1, - 1 ];
  9309. const renderer = this._renderer;
  9310. const originalAutoClear = renderer.autoClear;
  9311. const toneMapping = renderer.toneMapping;
  9312. renderer.getClearColor( _clearColor );
  9313. renderer.toneMapping = NoToneMapping;
  9314. renderer.autoClear = false;
  9315. const backgroundMaterial = new MeshBasicMaterial( {
  9316. name: 'PMREM.Background',
  9317. side: BackSide,
  9318. depthWrite: false,
  9319. depthTest: false,
  9320. } );
  9321. const backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  9322. let useSolidColor = false;
  9323. const background = scene.background;
  9324. if ( background ) {
  9325. if ( background.isColor ) {
  9326. backgroundMaterial.color.copy( background );
  9327. scene.background = null;
  9328. useSolidColor = true;
  9329. }
  9330. } else {
  9331. backgroundMaterial.color.copy( _clearColor );
  9332. useSolidColor = true;
  9333. }
  9334. for ( let i = 0; i < 6; i ++ ) {
  9335. const col = i % 3;
  9336. if ( col === 0 ) {
  9337. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9338. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  9339. } else if ( col === 1 ) {
  9340. cubeCamera.up.set( 0, 0, upSign[ i ] );
  9341. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  9342. } else {
  9343. cubeCamera.up.set( 0, upSign[ i ], 0 );
  9344. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  9345. }
  9346. const size = this._cubeSize;
  9347. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  9348. renderer.setRenderTarget( cubeUVRenderTarget );
  9349. if ( useSolidColor ) {
  9350. renderer.render( backgroundBox, cubeCamera );
  9351. }
  9352. renderer.render( scene, cubeCamera );
  9353. }
  9354. backgroundBox.geometry.dispose();
  9355. backgroundBox.material.dispose();
  9356. renderer.toneMapping = toneMapping;
  9357. renderer.autoClear = originalAutoClear;
  9358. scene.background = background;
  9359. }
  9360. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  9361. const renderer = this._renderer;
  9362. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  9363. if ( isCubeTexture ) {
  9364. if ( this._cubemapMaterial === null ) {
  9365. this._cubemapMaterial = _getCubemapMaterial();
  9366. }
  9367. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? - 1 : 1;
  9368. } else {
  9369. if ( this._equirectMaterial === null ) {
  9370. this._equirectMaterial = _getEquirectMaterial();
  9371. }
  9372. }
  9373. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  9374. const mesh = new Mesh( this._lodPlanes[ 0 ], material );
  9375. const uniforms = material.uniforms;
  9376. uniforms[ 'envMap' ].value = texture;
  9377. const size = this._cubeSize;
  9378. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  9379. renderer.setRenderTarget( cubeUVRenderTarget );
  9380. renderer.render( mesh, _flatCamera );
  9381. }
  9382. _applyPMREM( cubeUVRenderTarget ) {
  9383. const renderer = this._renderer;
  9384. const autoClear = renderer.autoClear;
  9385. renderer.autoClear = false;
  9386. for ( let i = 1; i < this._lodPlanes.length; i ++ ) {
  9387. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  9388. const poleAxis = _axisDirections[ ( i - 1 ) % _axisDirections.length ];
  9389. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  9390. }
  9391. renderer.autoClear = autoClear;
  9392. }
  9393. /**
  9394. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  9395. * vertically and horizontally, but this breaks down on a cube. Here we apply
  9396. * the blur latitudinally (around the poles), and then longitudinally (towards
  9397. * the poles) to approximate the orthogonally-separable blur. It is least
  9398. * accurate at the poles, but still does a decent job.
  9399. */
  9400. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  9401. const pingPongRenderTarget = this._pingPongRenderTarget;
  9402. this._halfBlur(
  9403. cubeUVRenderTarget,
  9404. pingPongRenderTarget,
  9405. lodIn,
  9406. lodOut,
  9407. sigma,
  9408. 'latitudinal',
  9409. poleAxis );
  9410. this._halfBlur(
  9411. pingPongRenderTarget,
  9412. cubeUVRenderTarget,
  9413. lodOut,
  9414. lodOut,
  9415. sigma,
  9416. 'longitudinal',
  9417. poleAxis );
  9418. }
  9419. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  9420. const renderer = this._renderer;
  9421. const blurMaterial = this._blurMaterial;
  9422. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  9423. console.error(
  9424. 'blur direction must be either latitudinal or longitudinal!' );
  9425. }
  9426. // Number of standard deviations at which to cut off the discrete approximation.
  9427. const STANDARD_DEVIATIONS = 3;
  9428. const blurMesh = new Mesh( this._lodPlanes[ lodOut ], blurMaterial );
  9429. const blurUniforms = blurMaterial.uniforms;
  9430. const pixels = this._sizeLods[ lodIn ] - 1;
  9431. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  9432. const sigmaPixels = sigmaRadians / radiansPerPixel;
  9433. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  9434. if ( samples > MAX_SAMPLES ) {
  9435. console.warn( `sigmaRadians, ${
  9436. sigmaRadians}, is too large and will clip, as it requested ${
  9437. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  9438. }
  9439. const weights = [];
  9440. let sum = 0;
  9441. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  9442. const x = i / sigmaPixels;
  9443. const weight = Math.exp( - x * x / 2 );
  9444. weights.push( weight );
  9445. if ( i === 0 ) {
  9446. sum += weight;
  9447. } else if ( i < samples ) {
  9448. sum += 2 * weight;
  9449. }
  9450. }
  9451. for ( let i = 0; i < weights.length; i ++ ) {
  9452. weights[ i ] = weights[ i ] / sum;
  9453. }
  9454. blurUniforms[ 'envMap' ].value = targetIn.texture;
  9455. blurUniforms[ 'samples' ].value = samples;
  9456. blurUniforms[ 'weights' ].value = weights;
  9457. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  9458. if ( poleAxis ) {
  9459. blurUniforms[ 'poleAxis' ].value = poleAxis;
  9460. }
  9461. const { _lodMax } = this;
  9462. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  9463. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  9464. const outputSize = this._sizeLods[ lodOut ];
  9465. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  9466. const y = 4 * ( this._cubeSize - outputSize );
  9467. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  9468. renderer.setRenderTarget( targetOut );
  9469. renderer.render( blurMesh, _flatCamera );
  9470. }
  9471. }
  9472. function _createPlanes( lodMax ) {
  9473. const lodPlanes = [];
  9474. const sizeLods = [];
  9475. const sigmas = [];
  9476. let lod = lodMax;
  9477. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  9478. for ( let i = 0; i < totalLods; i ++ ) {
  9479. const sizeLod = Math.pow( 2, lod );
  9480. sizeLods.push( sizeLod );
  9481. let sigma = 1.0 / sizeLod;
  9482. if ( i > lodMax - LOD_MIN ) {
  9483. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  9484. } else if ( i === 0 ) {
  9485. sigma = 0;
  9486. }
  9487. sigmas.push( sigma );
  9488. const texelSize = 1.0 / ( sizeLod - 2 );
  9489. const min = - texelSize;
  9490. const max = 1 + texelSize;
  9491. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  9492. const cubeFaces = 6;
  9493. const vertices = 6;
  9494. const positionSize = 3;
  9495. const uvSize = 2;
  9496. const faceIndexSize = 1;
  9497. const position = new Float32Array( positionSize * vertices * cubeFaces );
  9498. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  9499. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  9500. for ( let face = 0; face < cubeFaces; face ++ ) {
  9501. const x = ( face % 3 ) * 2 / 3 - 1;
  9502. const y = face > 2 ? 0 : - 1;
  9503. const coordinates = [
  9504. x, y, 0,
  9505. x + 2 / 3, y, 0,
  9506. x + 2 / 3, y + 1, 0,
  9507. x, y, 0,
  9508. x + 2 / 3, y + 1, 0,
  9509. x, y + 1, 0
  9510. ];
  9511. position.set( coordinates, positionSize * vertices * face );
  9512. uv.set( uv1, uvSize * vertices * face );
  9513. const fill = [ face, face, face, face, face, face ];
  9514. faceIndex.set( fill, faceIndexSize * vertices * face );
  9515. }
  9516. const planes = new BufferGeometry();
  9517. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  9518. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  9519. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  9520. lodPlanes.push( planes );
  9521. if ( lod > LOD_MIN ) {
  9522. lod --;
  9523. }
  9524. }
  9525. return { lodPlanes, sizeLods, sigmas };
  9526. }
  9527. function _createRenderTarget( width, height, params ) {
  9528. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  9529. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  9530. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  9531. cubeUVRenderTarget.scissorTest = true;
  9532. return cubeUVRenderTarget;
  9533. }
  9534. function _setViewport( target, x, y, width, height ) {
  9535. target.viewport.set( x, y, width, height );
  9536. target.scissor.set( x, y, width, height );
  9537. }
  9538. function _getBlurShader( lodMax, width, height ) {
  9539. const weights = new Float32Array( MAX_SAMPLES );
  9540. const poleAxis = new Vector3( 0, 1, 0 );
  9541. const shaderMaterial = new ShaderMaterial( {
  9542. name: 'SphericalGaussianBlur',
  9543. defines: {
  9544. 'n': MAX_SAMPLES,
  9545. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  9546. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  9547. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  9548. },
  9549. uniforms: {
  9550. 'envMap': { value: null },
  9551. 'samples': { value: 1 },
  9552. 'weights': { value: weights },
  9553. 'latitudinal': { value: false },
  9554. 'dTheta': { value: 0 },
  9555. 'mipInt': { value: 0 },
  9556. 'poleAxis': { value: poleAxis }
  9557. },
  9558. vertexShader: _getCommonVertexShader(),
  9559. fragmentShader: /* glsl */`
  9560. precision mediump float;
  9561. precision mediump int;
  9562. varying vec3 vOutputDirection;
  9563. uniform sampler2D envMap;
  9564. uniform int samples;
  9565. uniform float weights[ n ];
  9566. uniform bool latitudinal;
  9567. uniform float dTheta;
  9568. uniform float mipInt;
  9569. uniform vec3 poleAxis;
  9570. #define ENVMAP_TYPE_CUBE_UV
  9571. #include <cube_uv_reflection_fragment>
  9572. vec3 getSample( float theta, vec3 axis ) {
  9573. float cosTheta = cos( theta );
  9574. // Rodrigues' axis-angle rotation
  9575. vec3 sampleDirection = vOutputDirection * cosTheta
  9576. + cross( axis, vOutputDirection ) * sin( theta )
  9577. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  9578. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  9579. }
  9580. void main() {
  9581. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  9582. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  9583. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  9584. }
  9585. axis = normalize( axis );
  9586. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  9587. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  9588. for ( int i = 1; i < n; i++ ) {
  9589. if ( i >= samples ) {
  9590. break;
  9591. }
  9592. float theta = dTheta * float( i );
  9593. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  9594. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  9595. }
  9596. }
  9597. `,
  9598. blending: NoBlending,
  9599. depthTest: false,
  9600. depthWrite: false
  9601. } );
  9602. return shaderMaterial;
  9603. }
  9604. function _getEquirectMaterial() {
  9605. return new ShaderMaterial( {
  9606. name: 'EquirectangularToCubeUV',
  9607. uniforms: {
  9608. 'envMap': { value: null }
  9609. },
  9610. vertexShader: _getCommonVertexShader(),
  9611. fragmentShader: /* glsl */`
  9612. precision mediump float;
  9613. precision mediump int;
  9614. varying vec3 vOutputDirection;
  9615. uniform sampler2D envMap;
  9616. #include <common>
  9617. void main() {
  9618. vec3 outputDirection = normalize( vOutputDirection );
  9619. vec2 uv = equirectUv( outputDirection );
  9620. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  9621. }
  9622. `,
  9623. blending: NoBlending,
  9624. depthTest: false,
  9625. depthWrite: false
  9626. } );
  9627. }
  9628. function _getCubemapMaterial() {
  9629. return new ShaderMaterial( {
  9630. name: 'CubemapToCubeUV',
  9631. uniforms: {
  9632. 'envMap': { value: null },
  9633. 'flipEnvMap': { value: - 1 }
  9634. },
  9635. vertexShader: _getCommonVertexShader(),
  9636. fragmentShader: /* glsl */`
  9637. precision mediump float;
  9638. precision mediump int;
  9639. uniform float flipEnvMap;
  9640. varying vec3 vOutputDirection;
  9641. uniform samplerCube envMap;
  9642. void main() {
  9643. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  9644. }
  9645. `,
  9646. blending: NoBlending,
  9647. depthTest: false,
  9648. depthWrite: false
  9649. } );
  9650. }
  9651. function _getCommonVertexShader() {
  9652. return /* glsl */`
  9653. precision mediump float;
  9654. precision mediump int;
  9655. attribute float faceIndex;
  9656. varying vec3 vOutputDirection;
  9657. // RH coordinate system; PMREM face-indexing convention
  9658. vec3 getDirection( vec2 uv, float face ) {
  9659. uv = 2.0 * uv - 1.0;
  9660. vec3 direction = vec3( uv, 1.0 );
  9661. if ( face == 0.0 ) {
  9662. direction = direction.zyx; // ( 1, v, u ) pos x
  9663. } else if ( face == 1.0 ) {
  9664. direction = direction.xzy;
  9665. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  9666. } else if ( face == 2.0 ) {
  9667. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  9668. } else if ( face == 3.0 ) {
  9669. direction = direction.zyx;
  9670. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  9671. } else if ( face == 4.0 ) {
  9672. direction = direction.xzy;
  9673. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  9674. } else if ( face == 5.0 ) {
  9675. direction.z *= -1.0; // ( u, v, -1 ) neg z
  9676. }
  9677. return direction;
  9678. }
  9679. void main() {
  9680. vOutputDirection = getDirection( uv, faceIndex );
  9681. gl_Position = vec4( position, 1.0 );
  9682. }
  9683. `;
  9684. }
  9685. function WebGLCubeUVMaps( renderer ) {
  9686. let cubeUVmaps = new WeakMap();
  9687. let pmremGenerator = null;
  9688. function get( texture ) {
  9689. if ( texture && texture.isTexture ) {
  9690. const mapping = texture.mapping;
  9691. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  9692. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  9693. // equirect/cube map to cubeUV conversion
  9694. if ( isEquirectMap || isCubeMap ) {
  9695. if ( texture.isRenderTargetTexture && texture.needsPMREMUpdate === true ) {
  9696. texture.needsPMREMUpdate = false;
  9697. let renderTarget = cubeUVmaps.get( texture );
  9698. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  9699. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  9700. cubeUVmaps.set( texture, renderTarget );
  9701. return renderTarget.texture;
  9702. } else {
  9703. if ( cubeUVmaps.has( texture ) ) {
  9704. return cubeUVmaps.get( texture ).texture;
  9705. } else {
  9706. const image = texture.image;
  9707. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  9708. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  9709. const renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  9710. cubeUVmaps.set( texture, renderTarget );
  9711. texture.addEventListener( 'dispose', onTextureDispose );
  9712. return renderTarget.texture;
  9713. } else {
  9714. // image not yet ready. try the conversion next frame
  9715. return null;
  9716. }
  9717. }
  9718. }
  9719. }
  9720. }
  9721. return texture;
  9722. }
  9723. function isCubeTextureComplete( image ) {
  9724. let count = 0;
  9725. const length = 6;
  9726. for ( let i = 0; i < length; i ++ ) {
  9727. if ( image[ i ] !== undefined ) count ++;
  9728. }
  9729. return count === length;
  9730. }
  9731. function onTextureDispose( event ) {
  9732. const texture = event.target;
  9733. texture.removeEventListener( 'dispose', onTextureDispose );
  9734. const cubemapUV = cubeUVmaps.get( texture );
  9735. if ( cubemapUV !== undefined ) {
  9736. cubeUVmaps.delete( texture );
  9737. cubemapUV.dispose();
  9738. }
  9739. }
  9740. function dispose() {
  9741. cubeUVmaps = new WeakMap();
  9742. if ( pmremGenerator !== null ) {
  9743. pmremGenerator.dispose();
  9744. pmremGenerator = null;
  9745. }
  9746. }
  9747. return {
  9748. get: get,
  9749. dispose: dispose
  9750. };
  9751. }
  9752. function WebGLExtensions( gl ) {
  9753. const extensions = {};
  9754. function getExtension( name ) {
  9755. if ( extensions[ name ] !== undefined ) {
  9756. return extensions[ name ];
  9757. }
  9758. let extension;
  9759. switch ( name ) {
  9760. case 'WEBGL_depth_texture':
  9761. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  9762. break;
  9763. case 'EXT_texture_filter_anisotropic':
  9764. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  9765. break;
  9766. case 'WEBGL_compressed_texture_s3tc':
  9767. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  9768. break;
  9769. case 'WEBGL_compressed_texture_pvrtc':
  9770. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  9771. break;
  9772. default:
  9773. extension = gl.getExtension( name );
  9774. }
  9775. extensions[ name ] = extension;
  9776. return extension;
  9777. }
  9778. return {
  9779. has: function ( name ) {
  9780. return getExtension( name ) !== null;
  9781. },
  9782. init: function ( capabilities ) {
  9783. if ( capabilities.isWebGL2 ) {
  9784. getExtension( 'EXT_color_buffer_float' );
  9785. } else {
  9786. getExtension( 'WEBGL_depth_texture' );
  9787. getExtension( 'OES_texture_float' );
  9788. getExtension( 'OES_texture_half_float' );
  9789. getExtension( 'OES_texture_half_float_linear' );
  9790. getExtension( 'OES_standard_derivatives' );
  9791. getExtension( 'OES_element_index_uint' );
  9792. getExtension( 'OES_vertex_array_object' );
  9793. getExtension( 'ANGLE_instanced_arrays' );
  9794. }
  9795. getExtension( 'OES_texture_float_linear' );
  9796. getExtension( 'EXT_color_buffer_half_float' );
  9797. getExtension( 'WEBGL_multisampled_render_to_texture' );
  9798. },
  9799. get: function ( name ) {
  9800. const extension = getExtension( name );
  9801. if ( extension === null ) {
  9802. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  9803. }
  9804. return extension;
  9805. }
  9806. };
  9807. }
  9808. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  9809. const geometries = {};
  9810. const wireframeAttributes = new WeakMap();
  9811. function onGeometryDispose( event ) {
  9812. const geometry = event.target;
  9813. if ( geometry.index !== null ) {
  9814. attributes.remove( geometry.index );
  9815. }
  9816. for ( const name in geometry.attributes ) {
  9817. attributes.remove( geometry.attributes[ name ] );
  9818. }
  9819. geometry.removeEventListener( 'dispose', onGeometryDispose );
  9820. delete geometries[ geometry.id ];
  9821. const attribute = wireframeAttributes.get( geometry );
  9822. if ( attribute ) {
  9823. attributes.remove( attribute );
  9824. wireframeAttributes.delete( geometry );
  9825. }
  9826. bindingStates.releaseStatesOfGeometry( geometry );
  9827. if ( geometry.isInstancedBufferGeometry === true ) {
  9828. delete geometry._maxInstanceCount;
  9829. }
  9830. //
  9831. info.memory.geometries --;
  9832. }
  9833. function get( object, geometry ) {
  9834. if ( geometries[ geometry.id ] === true ) return geometry;
  9835. geometry.addEventListener( 'dispose', onGeometryDispose );
  9836. geometries[ geometry.id ] = true;
  9837. info.memory.geometries ++;
  9838. return geometry;
  9839. }
  9840. function update( geometry ) {
  9841. const geometryAttributes = geometry.attributes;
  9842. // Updating index buffer in VAO now. See WebGLBindingStates.
  9843. for ( const name in geometryAttributes ) {
  9844. attributes.update( geometryAttributes[ name ], 34962 );
  9845. }
  9846. // morph targets
  9847. const morphAttributes = geometry.morphAttributes;
  9848. for ( const name in morphAttributes ) {
  9849. const array = morphAttributes[ name ];
  9850. for ( let i = 0, l = array.length; i < l; i ++ ) {
  9851. attributes.update( array[ i ], 34962 );
  9852. }
  9853. }
  9854. }
  9855. function updateWireframeAttribute( geometry ) {
  9856. const indices = [];
  9857. const geometryIndex = geometry.index;
  9858. const geometryPosition = geometry.attributes.position;
  9859. let version = 0;
  9860. if ( geometryIndex !== null ) {
  9861. const array = geometryIndex.array;
  9862. version = geometryIndex.version;
  9863. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  9864. const a = array[ i + 0 ];
  9865. const b = array[ i + 1 ];
  9866. const c = array[ i + 2 ];
  9867. indices.push( a, b, b, c, c, a );
  9868. }
  9869. } else {
  9870. const array = geometryPosition.array;
  9871. version = geometryPosition.version;
  9872. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  9873. const a = i + 0;
  9874. const b = i + 1;
  9875. const c = i + 2;
  9876. indices.push( a, b, b, c, c, a );
  9877. }
  9878. }
  9879. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  9880. attribute.version = version;
  9881. // Updating index buffer in VAO now. See WebGLBindingStates
  9882. //
  9883. const previousAttribute = wireframeAttributes.get( geometry );
  9884. if ( previousAttribute ) attributes.remove( previousAttribute );
  9885. //
  9886. wireframeAttributes.set( geometry, attribute );
  9887. }
  9888. function getWireframeAttribute( geometry ) {
  9889. const currentAttribute = wireframeAttributes.get( geometry );
  9890. if ( currentAttribute ) {
  9891. const geometryIndex = geometry.index;
  9892. if ( geometryIndex !== null ) {
  9893. // if the attribute is obsolete, create a new one
  9894. if ( currentAttribute.version < geometryIndex.version ) {
  9895. updateWireframeAttribute( geometry );
  9896. }
  9897. }
  9898. } else {
  9899. updateWireframeAttribute( geometry );
  9900. }
  9901. return wireframeAttributes.get( geometry );
  9902. }
  9903. return {
  9904. get: get,
  9905. update: update,
  9906. getWireframeAttribute: getWireframeAttribute
  9907. };
  9908. }
  9909. function WebGLIndexedBufferRenderer( gl, extensions, info, capabilities ) {
  9910. const isWebGL2 = capabilities.isWebGL2;
  9911. let mode;
  9912. function setMode( value ) {
  9913. mode = value;
  9914. }
  9915. let type, bytesPerElement;
  9916. function setIndex( value ) {
  9917. type = value.type;
  9918. bytesPerElement = value.bytesPerElement;
  9919. }
  9920. function render( start, count ) {
  9921. gl.drawElements( mode, count, type, start * bytesPerElement );
  9922. info.update( count, mode, 1 );
  9923. }
  9924. function renderInstances( start, count, primcount ) {
  9925. if ( primcount === 0 ) return;
  9926. let extension, methodName;
  9927. if ( isWebGL2 ) {
  9928. extension = gl;
  9929. methodName = 'drawElementsInstanced';
  9930. } else {
  9931. extension = extensions.get( 'ANGLE_instanced_arrays' );
  9932. methodName = 'drawElementsInstancedANGLE';
  9933. if ( extension === null ) {
  9934. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  9935. return;
  9936. }
  9937. }
  9938. extension[ methodName ]( mode, count, type, start * bytesPerElement, primcount );
  9939. info.update( count, mode, primcount );
  9940. }
  9941. //
  9942. this.setMode = setMode;
  9943. this.setIndex = setIndex;
  9944. this.render = render;
  9945. this.renderInstances = renderInstances;
  9946. }
  9947. function WebGLInfo( gl ) {
  9948. const memory = {
  9949. geometries: 0,
  9950. textures: 0
  9951. };
  9952. const render = {
  9953. frame: 0,
  9954. calls: 0,
  9955. triangles: 0,
  9956. points: 0,
  9957. lines: 0
  9958. };
  9959. function update( count, mode, instanceCount ) {
  9960. render.calls ++;
  9961. switch ( mode ) {
  9962. case 4:
  9963. render.triangles += instanceCount * ( count / 3 );
  9964. break;
  9965. case 1:
  9966. render.lines += instanceCount * ( count / 2 );
  9967. break;
  9968. case 3:
  9969. render.lines += instanceCount * ( count - 1 );
  9970. break;
  9971. case 2:
  9972. render.lines += instanceCount * count;
  9973. break;
  9974. case 0:
  9975. render.points += instanceCount * count;
  9976. break;
  9977. default:
  9978. console.error( 'THREE.WebGLInfo: Unknown draw mode:', mode );
  9979. break;
  9980. }
  9981. }
  9982. function reset() {
  9983. render.frame ++;
  9984. render.calls = 0;
  9985. render.triangles = 0;
  9986. render.points = 0;
  9987. render.lines = 0;
  9988. }
  9989. return {
  9990. memory: memory,
  9991. render: render,
  9992. programs: null,
  9993. autoReset: true,
  9994. reset: reset,
  9995. update: update
  9996. };
  9997. }
  9998. function numericalSort( a, b ) {
  9999. return a[ 0 ] - b[ 0 ];
  10000. }
  10001. function absNumericalSort( a, b ) {
  10002. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  10003. }
  10004. function denormalize( morph, attribute ) {
  10005. let denominator = 1;
  10006. const array = attribute.isInterleavedBufferAttribute ? attribute.data.array : attribute.array;
  10007. if ( array instanceof Int8Array ) denominator = 127;
  10008. else if ( array instanceof Uint8Array ) denominator = 255;
  10009. else if ( array instanceof Uint16Array ) denominator = 65535;
  10010. else if ( array instanceof Int16Array ) denominator = 32767;
  10011. else if ( array instanceof Int32Array ) denominator = 2147483647;
  10012. else console.error( 'THREE.WebGLMorphtargets: Unsupported morph attribute data type: ', array );
  10013. morph.divideScalar( denominator );
  10014. }
  10015. function WebGLMorphtargets( gl, capabilities, textures ) {
  10016. const influencesList = {};
  10017. const morphInfluences = new Float32Array( 8 );
  10018. const morphTextures = new WeakMap();
  10019. const morph = new Vector4();
  10020. const workInfluences = [];
  10021. for ( let i = 0; i < 8; i ++ ) {
  10022. workInfluences[ i ] = [ i, 0 ];
  10023. }
  10024. function update( object, geometry, material, program ) {
  10025. const objectInfluences = object.morphTargetInfluences;
  10026. if ( capabilities.isWebGL2 === true ) {
  10027. // instead of using attributes, the WebGL 2 code path encodes morph targets
  10028. // into an array of data textures. Each layer represents a single morph target.
  10029. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  10030. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  10031. let entry = morphTextures.get( geometry );
  10032. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  10033. if ( entry !== undefined ) entry.texture.dispose();
  10034. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  10035. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  10036. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  10037. const morphTargets = geometry.morphAttributes.position || [];
  10038. const morphNormals = geometry.morphAttributes.normal || [];
  10039. const morphColors = geometry.morphAttributes.color || [];
  10040. let vertexDataCount = 0;
  10041. if ( hasMorphPosition === true ) vertexDataCount = 1;
  10042. if ( hasMorphNormals === true ) vertexDataCount = 2;
  10043. if ( hasMorphColors === true ) vertexDataCount = 3;
  10044. let width = geometry.attributes.position.count * vertexDataCount;
  10045. let height = 1;
  10046. if ( width > capabilities.maxTextureSize ) {
  10047. height = Math.ceil( width / capabilities.maxTextureSize );
  10048. width = capabilities.maxTextureSize;
  10049. }
  10050. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  10051. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  10052. texture.type = FloatType;
  10053. texture.needsUpdate = true;
  10054. // fill buffer
  10055. const vertexDataStride = vertexDataCount * 4;
  10056. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  10057. const morphTarget = morphTargets[ i ];
  10058. const morphNormal = morphNormals[ i ];
  10059. const morphColor = morphColors[ i ];
  10060. const offset = width * height * 4 * i;
  10061. for ( let j = 0; j < morphTarget.count; j ++ ) {
  10062. const stride = j * vertexDataStride;
  10063. if ( hasMorphPosition === true ) {
  10064. morph.fromBufferAttribute( morphTarget, j );
  10065. if ( morphTarget.normalized === true ) denormalize( morph, morphTarget );
  10066. buffer[ offset + stride + 0 ] = morph.x;
  10067. buffer[ offset + stride + 1 ] = morph.y;
  10068. buffer[ offset + stride + 2 ] = morph.z;
  10069. buffer[ offset + stride + 3 ] = 0;
  10070. }
  10071. if ( hasMorphNormals === true ) {
  10072. morph.fromBufferAttribute( morphNormal, j );
  10073. if ( morphNormal.normalized === true ) denormalize( morph, morphNormal );
  10074. buffer[ offset + stride + 4 ] = morph.x;
  10075. buffer[ offset + stride + 5 ] = morph.y;
  10076. buffer[ offset + stride + 6 ] = morph.z;
  10077. buffer[ offset + stride + 7 ] = 0;
  10078. }
  10079. if ( hasMorphColors === true ) {
  10080. morph.fromBufferAttribute( morphColor, j );
  10081. if ( morphColor.normalized === true ) denormalize( morph, morphColor );
  10082. buffer[ offset + stride + 8 ] = morph.x;
  10083. buffer[ offset + stride + 9 ] = morph.y;
  10084. buffer[ offset + stride + 10 ] = morph.z;
  10085. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  10086. }
  10087. }
  10088. }
  10089. entry = {
  10090. count: morphTargetsCount,
  10091. texture: texture,
  10092. size: new Vector2( width, height )
  10093. };
  10094. morphTextures.set( geometry, entry );
  10095. function disposeTexture() {
  10096. texture.dispose();
  10097. morphTextures.delete( geometry );
  10098. geometry.removeEventListener( 'dispose', disposeTexture );
  10099. }
  10100. geometry.addEventListener( 'dispose', disposeTexture );
  10101. }
  10102. //
  10103. let morphInfluencesSum = 0;
  10104. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  10105. morphInfluencesSum += objectInfluences[ i ];
  10106. }
  10107. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10108. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10109. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  10110. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  10111. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  10112. } else {
  10113. // When object doesn't have morph target influences defined, we treat it as a 0-length array
  10114. // This is important to make sure we set up morphTargetBaseInfluence / morphTargetInfluences
  10115. const length = objectInfluences === undefined ? 0 : objectInfluences.length;
  10116. let influences = influencesList[ geometry.id ];
  10117. if ( influences === undefined || influences.length !== length ) {
  10118. // initialise list
  10119. influences = [];
  10120. for ( let i = 0; i < length; i ++ ) {
  10121. influences[ i ] = [ i, 0 ];
  10122. }
  10123. influencesList[ geometry.id ] = influences;
  10124. }
  10125. // Collect influences
  10126. for ( let i = 0; i < length; i ++ ) {
  10127. const influence = influences[ i ];
  10128. influence[ 0 ] = i;
  10129. influence[ 1 ] = objectInfluences[ i ];
  10130. }
  10131. influences.sort( absNumericalSort );
  10132. for ( let i = 0; i < 8; i ++ ) {
  10133. if ( i < length && influences[ i ][ 1 ] ) {
  10134. workInfluences[ i ][ 0 ] = influences[ i ][ 0 ];
  10135. workInfluences[ i ][ 1 ] = influences[ i ][ 1 ];
  10136. } else {
  10137. workInfluences[ i ][ 0 ] = Number.MAX_SAFE_INTEGER;
  10138. workInfluences[ i ][ 1 ] = 0;
  10139. }
  10140. }
  10141. workInfluences.sort( numericalSort );
  10142. const morphTargets = geometry.morphAttributes.position;
  10143. const morphNormals = geometry.morphAttributes.normal;
  10144. let morphInfluencesSum = 0;
  10145. for ( let i = 0; i < 8; i ++ ) {
  10146. const influence = workInfluences[ i ];
  10147. const index = influence[ 0 ];
  10148. const value = influence[ 1 ];
  10149. if ( index !== Number.MAX_SAFE_INTEGER && value ) {
  10150. if ( morphTargets && geometry.getAttribute( 'morphTarget' + i ) !== morphTargets[ index ] ) {
  10151. geometry.setAttribute( 'morphTarget' + i, morphTargets[ index ] );
  10152. }
  10153. if ( morphNormals && geometry.getAttribute( 'morphNormal' + i ) !== morphNormals[ index ] ) {
  10154. geometry.setAttribute( 'morphNormal' + i, morphNormals[ index ] );
  10155. }
  10156. morphInfluences[ i ] = value;
  10157. morphInfluencesSum += value;
  10158. } else {
  10159. if ( morphTargets && geometry.hasAttribute( 'morphTarget' + i ) === true ) {
  10160. geometry.deleteAttribute( 'morphTarget' + i );
  10161. }
  10162. if ( morphNormals && geometry.hasAttribute( 'morphNormal' + i ) === true ) {
  10163. geometry.deleteAttribute( 'morphNormal' + i );
  10164. }
  10165. morphInfluences[ i ] = 0;
  10166. }
  10167. }
  10168. // GLSL shader uses formula baseinfluence * base + sum(target * influence)
  10169. // This allows us to switch between absolute morphs and relative morphs without changing shader code
  10170. // When baseinfluence = 1 - sum(influence), the above is equivalent to sum((target - base) * influence)
  10171. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  10172. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  10173. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  10174. }
  10175. }
  10176. return {
  10177. update: update
  10178. };
  10179. }
  10180. function WebGLObjects( gl, geometries, attributes, info ) {
  10181. let updateMap = new WeakMap();
  10182. function update( object ) {
  10183. const frame = info.render.frame;
  10184. const geometry = object.geometry;
  10185. const buffergeometry = geometries.get( object, geometry );
  10186. // Update once per frame
  10187. if ( updateMap.get( buffergeometry ) !== frame ) {
  10188. geometries.update( buffergeometry );
  10189. updateMap.set( buffergeometry, frame );
  10190. }
  10191. if ( object.isInstancedMesh ) {
  10192. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  10193. object.addEventListener( 'dispose', onInstancedMeshDispose );
  10194. }
  10195. attributes.update( object.instanceMatrix, 34962 );
  10196. if ( object.instanceColor !== null ) {
  10197. attributes.update( object.instanceColor, 34962 );
  10198. }
  10199. }
  10200. return buffergeometry;
  10201. }
  10202. function dispose() {
  10203. updateMap = new WeakMap();
  10204. }
  10205. function onInstancedMeshDispose( event ) {
  10206. const instancedMesh = event.target;
  10207. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  10208. attributes.remove( instancedMesh.instanceMatrix );
  10209. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  10210. }
  10211. return {
  10212. update: update,
  10213. dispose: dispose
  10214. };
  10215. }
  10216. /**
  10217. * Uniforms of a program.
  10218. * Those form a tree structure with a special top-level container for the root,
  10219. * which you get by calling 'new WebGLUniforms( gl, program )'.
  10220. *
  10221. *
  10222. * Properties of inner nodes including the top-level container:
  10223. *
  10224. * .seq - array of nested uniforms
  10225. * .map - nested uniforms by name
  10226. *
  10227. *
  10228. * Methods of all nodes except the top-level container:
  10229. *
  10230. * .setValue( gl, value, [textures] )
  10231. *
  10232. * uploads a uniform value(s)
  10233. * the 'textures' parameter is needed for sampler uniforms
  10234. *
  10235. *
  10236. * Static methods of the top-level container (textures factorizations):
  10237. *
  10238. * .upload( gl, seq, values, textures )
  10239. *
  10240. * sets uniforms in 'seq' to 'values[id].value'
  10241. *
  10242. * .seqWithValue( seq, values ) : filteredSeq
  10243. *
  10244. * filters 'seq' entries with corresponding entry in values
  10245. *
  10246. *
  10247. * Methods of the top-level container (textures factorizations):
  10248. *
  10249. * .setValue( gl, name, value, textures )
  10250. *
  10251. * sets uniform with name 'name' to 'value'
  10252. *
  10253. * .setOptional( gl, obj, prop )
  10254. *
  10255. * like .set for an optional property of the object
  10256. *
  10257. */
  10258. const emptyTexture = /*@__PURE__*/ new Texture();
  10259. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  10260. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  10261. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  10262. // --- Utilities ---
  10263. // Array Caches (provide typed arrays for temporary by size)
  10264. const arrayCacheF32 = [];
  10265. const arrayCacheI32 = [];
  10266. // Float32Array caches used for uploading Matrix uniforms
  10267. const mat4array = new Float32Array( 16 );
  10268. const mat3array = new Float32Array( 9 );
  10269. const mat2array = new Float32Array( 4 );
  10270. // Flattening for arrays of vectors and matrices
  10271. function flatten( array, nBlocks, blockSize ) {
  10272. const firstElem = array[ 0 ];
  10273. if ( firstElem <= 0 || firstElem > 0 ) return array;
  10274. // unoptimized: ! isNaN( firstElem )
  10275. // see http://jacksondunstan.com/articles/983
  10276. const n = nBlocks * blockSize;
  10277. let r = arrayCacheF32[ n ];
  10278. if ( r === undefined ) {
  10279. r = new Float32Array( n );
  10280. arrayCacheF32[ n ] = r;
  10281. }
  10282. if ( nBlocks !== 0 ) {
  10283. firstElem.toArray( r, 0 );
  10284. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  10285. offset += blockSize;
  10286. array[ i ].toArray( r, offset );
  10287. }
  10288. }
  10289. return r;
  10290. }
  10291. function arraysEqual( a, b ) {
  10292. if ( a.length !== b.length ) return false;
  10293. for ( let i = 0, l = a.length; i < l; i ++ ) {
  10294. if ( a[ i ] !== b[ i ] ) return false;
  10295. }
  10296. return true;
  10297. }
  10298. function copyArray( a, b ) {
  10299. for ( let i = 0, l = b.length; i < l; i ++ ) {
  10300. a[ i ] = b[ i ];
  10301. }
  10302. }
  10303. // Texture unit allocation
  10304. function allocTexUnits( textures, n ) {
  10305. let r = arrayCacheI32[ n ];
  10306. if ( r === undefined ) {
  10307. r = new Int32Array( n );
  10308. arrayCacheI32[ n ] = r;
  10309. }
  10310. for ( let i = 0; i !== n; ++ i ) {
  10311. r[ i ] = textures.allocateTextureUnit();
  10312. }
  10313. return r;
  10314. }
  10315. // --- Setters ---
  10316. // Note: Defining these methods externally, because they come in a bunch
  10317. // and this way their names minify.
  10318. // Single scalar
  10319. function setValueV1f( gl, v ) {
  10320. const cache = this.cache;
  10321. if ( cache[ 0 ] === v ) return;
  10322. gl.uniform1f( this.addr, v );
  10323. cache[ 0 ] = v;
  10324. }
  10325. // Single float vector (from flat array or THREE.VectorN)
  10326. function setValueV2f( gl, v ) {
  10327. const cache = this.cache;
  10328. if ( v.x !== undefined ) {
  10329. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  10330. gl.uniform2f( this.addr, v.x, v.y );
  10331. cache[ 0 ] = v.x;
  10332. cache[ 1 ] = v.y;
  10333. }
  10334. } else {
  10335. if ( arraysEqual( cache, v ) ) return;
  10336. gl.uniform2fv( this.addr, v );
  10337. copyArray( cache, v );
  10338. }
  10339. }
  10340. function setValueV3f( gl, v ) {
  10341. const cache = this.cache;
  10342. if ( v.x !== undefined ) {
  10343. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  10344. gl.uniform3f( this.addr, v.x, v.y, v.z );
  10345. cache[ 0 ] = v.x;
  10346. cache[ 1 ] = v.y;
  10347. cache[ 2 ] = v.z;
  10348. }
  10349. } else if ( v.r !== undefined ) {
  10350. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  10351. gl.uniform3f( this.addr, v.r, v.g, v.b );
  10352. cache[ 0 ] = v.r;
  10353. cache[ 1 ] = v.g;
  10354. cache[ 2 ] = v.b;
  10355. }
  10356. } else {
  10357. if ( arraysEqual( cache, v ) ) return;
  10358. gl.uniform3fv( this.addr, v );
  10359. copyArray( cache, v );
  10360. }
  10361. }
  10362. function setValueV4f( gl, v ) {
  10363. const cache = this.cache;
  10364. if ( v.x !== undefined ) {
  10365. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  10366. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  10367. cache[ 0 ] = v.x;
  10368. cache[ 1 ] = v.y;
  10369. cache[ 2 ] = v.z;
  10370. cache[ 3 ] = v.w;
  10371. }
  10372. } else {
  10373. if ( arraysEqual( cache, v ) ) return;
  10374. gl.uniform4fv( this.addr, v );
  10375. copyArray( cache, v );
  10376. }
  10377. }
  10378. // Single matrix (from flat array or THREE.MatrixN)
  10379. function setValueM2( gl, v ) {
  10380. const cache = this.cache;
  10381. const elements = v.elements;
  10382. if ( elements === undefined ) {
  10383. if ( arraysEqual( cache, v ) ) return;
  10384. gl.uniformMatrix2fv( this.addr, false, v );
  10385. copyArray( cache, v );
  10386. } else {
  10387. if ( arraysEqual( cache, elements ) ) return;
  10388. mat2array.set( elements );
  10389. gl.uniformMatrix2fv( this.addr, false, mat2array );
  10390. copyArray( cache, elements );
  10391. }
  10392. }
  10393. function setValueM3( gl, v ) {
  10394. const cache = this.cache;
  10395. const elements = v.elements;
  10396. if ( elements === undefined ) {
  10397. if ( arraysEqual( cache, v ) ) return;
  10398. gl.uniformMatrix3fv( this.addr, false, v );
  10399. copyArray( cache, v );
  10400. } else {
  10401. if ( arraysEqual( cache, elements ) ) return;
  10402. mat3array.set( elements );
  10403. gl.uniformMatrix3fv( this.addr, false, mat3array );
  10404. copyArray( cache, elements );
  10405. }
  10406. }
  10407. function setValueM4( gl, v ) {
  10408. const cache = this.cache;
  10409. const elements = v.elements;
  10410. if ( elements === undefined ) {
  10411. if ( arraysEqual( cache, v ) ) return;
  10412. gl.uniformMatrix4fv( this.addr, false, v );
  10413. copyArray( cache, v );
  10414. } else {
  10415. if ( arraysEqual( cache, elements ) ) return;
  10416. mat4array.set( elements );
  10417. gl.uniformMatrix4fv( this.addr, false, mat4array );
  10418. copyArray( cache, elements );
  10419. }
  10420. }
  10421. // Single integer / boolean
  10422. function setValueV1i( gl, v ) {
  10423. const cache = this.cache;
  10424. if ( cache[ 0 ] === v ) return;
  10425. gl.uniform1i( this.addr, v );
  10426. cache[ 0 ] = v;
  10427. }
  10428. // Single integer / boolean vector (from flat array)
  10429. function setValueV2i( gl, v ) {
  10430. const cache = this.cache;
  10431. if ( arraysEqual( cache, v ) ) return;
  10432. gl.uniform2iv( this.addr, v );
  10433. copyArray( cache, v );
  10434. }
  10435. function setValueV3i( gl, v ) {
  10436. const cache = this.cache;
  10437. if ( arraysEqual( cache, v ) ) return;
  10438. gl.uniform3iv( this.addr, v );
  10439. copyArray( cache, v );
  10440. }
  10441. function setValueV4i( gl, v ) {
  10442. const cache = this.cache;
  10443. if ( arraysEqual( cache, v ) ) return;
  10444. gl.uniform4iv( this.addr, v );
  10445. copyArray( cache, v );
  10446. }
  10447. // Single unsigned integer
  10448. function setValueV1ui( gl, v ) {
  10449. const cache = this.cache;
  10450. if ( cache[ 0 ] === v ) return;
  10451. gl.uniform1ui( this.addr, v );
  10452. cache[ 0 ] = v;
  10453. }
  10454. // Single unsigned integer vector (from flat array)
  10455. function setValueV2ui( gl, v ) {
  10456. const cache = this.cache;
  10457. if ( arraysEqual( cache, v ) ) return;
  10458. gl.uniform2uiv( this.addr, v );
  10459. copyArray( cache, v );
  10460. }
  10461. function setValueV3ui( gl, v ) {
  10462. const cache = this.cache;
  10463. if ( arraysEqual( cache, v ) ) return;
  10464. gl.uniform3uiv( this.addr, v );
  10465. copyArray( cache, v );
  10466. }
  10467. function setValueV4ui( gl, v ) {
  10468. const cache = this.cache;
  10469. if ( arraysEqual( cache, v ) ) return;
  10470. gl.uniform4uiv( this.addr, v );
  10471. copyArray( cache, v );
  10472. }
  10473. // Single texture (2D / Cube)
  10474. function setValueT1( gl, v, textures ) {
  10475. const cache = this.cache;
  10476. const unit = textures.allocateTextureUnit();
  10477. if ( cache[ 0 ] !== unit ) {
  10478. gl.uniform1i( this.addr, unit );
  10479. cache[ 0 ] = unit;
  10480. }
  10481. textures.setTexture2D( v || emptyTexture, unit );
  10482. }
  10483. function setValueT3D1( gl, v, textures ) {
  10484. const cache = this.cache;
  10485. const unit = textures.allocateTextureUnit();
  10486. if ( cache[ 0 ] !== unit ) {
  10487. gl.uniform1i( this.addr, unit );
  10488. cache[ 0 ] = unit;
  10489. }
  10490. textures.setTexture3D( v || empty3dTexture, unit );
  10491. }
  10492. function setValueT6( gl, v, textures ) {
  10493. const cache = this.cache;
  10494. const unit = textures.allocateTextureUnit();
  10495. if ( cache[ 0 ] !== unit ) {
  10496. gl.uniform1i( this.addr, unit );
  10497. cache[ 0 ] = unit;
  10498. }
  10499. textures.setTextureCube( v || emptyCubeTexture, unit );
  10500. }
  10501. function setValueT2DArray1( gl, v, textures ) {
  10502. const cache = this.cache;
  10503. const unit = textures.allocateTextureUnit();
  10504. if ( cache[ 0 ] !== unit ) {
  10505. gl.uniform1i( this.addr, unit );
  10506. cache[ 0 ] = unit;
  10507. }
  10508. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  10509. }
  10510. // Helper to pick the right setter for the singular case
  10511. function getSingularSetter( type ) {
  10512. switch ( type ) {
  10513. case 0x1406: return setValueV1f; // FLOAT
  10514. case 0x8b50: return setValueV2f; // _VEC2
  10515. case 0x8b51: return setValueV3f; // _VEC3
  10516. case 0x8b52: return setValueV4f; // _VEC4
  10517. case 0x8b5a: return setValueM2; // _MAT2
  10518. case 0x8b5b: return setValueM3; // _MAT3
  10519. case 0x8b5c: return setValueM4; // _MAT4
  10520. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  10521. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  10522. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  10523. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  10524. case 0x1405: return setValueV1ui; // UINT
  10525. case 0x8dc6: return setValueV2ui; // _VEC2
  10526. case 0x8dc7: return setValueV3ui; // _VEC3
  10527. case 0x8dc8: return setValueV4ui; // _VEC4
  10528. case 0x8b5e: // SAMPLER_2D
  10529. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10530. case 0x8dca: // INT_SAMPLER_2D
  10531. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10532. case 0x8b62: // SAMPLER_2D_SHADOW
  10533. return setValueT1;
  10534. case 0x8b5f: // SAMPLER_3D
  10535. case 0x8dcb: // INT_SAMPLER_3D
  10536. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10537. return setValueT3D1;
  10538. case 0x8b60: // SAMPLER_CUBE
  10539. case 0x8dcc: // INT_SAMPLER_CUBE
  10540. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10541. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10542. return setValueT6;
  10543. case 0x8dc1: // SAMPLER_2D_ARRAY
  10544. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10545. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10546. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10547. return setValueT2DArray1;
  10548. }
  10549. }
  10550. // Array of scalars
  10551. function setValueV1fArray( gl, v ) {
  10552. gl.uniform1fv( this.addr, v );
  10553. }
  10554. // Array of vectors (from flat array or array of THREE.VectorN)
  10555. function setValueV2fArray( gl, v ) {
  10556. const data = flatten( v, this.size, 2 );
  10557. gl.uniform2fv( this.addr, data );
  10558. }
  10559. function setValueV3fArray( gl, v ) {
  10560. const data = flatten( v, this.size, 3 );
  10561. gl.uniform3fv( this.addr, data );
  10562. }
  10563. function setValueV4fArray( gl, v ) {
  10564. const data = flatten( v, this.size, 4 );
  10565. gl.uniform4fv( this.addr, data );
  10566. }
  10567. // Array of matrices (from flat array or array of THREE.MatrixN)
  10568. function setValueM2Array( gl, v ) {
  10569. const data = flatten( v, this.size, 4 );
  10570. gl.uniformMatrix2fv( this.addr, false, data );
  10571. }
  10572. function setValueM3Array( gl, v ) {
  10573. const data = flatten( v, this.size, 9 );
  10574. gl.uniformMatrix3fv( this.addr, false, data );
  10575. }
  10576. function setValueM4Array( gl, v ) {
  10577. const data = flatten( v, this.size, 16 );
  10578. gl.uniformMatrix4fv( this.addr, false, data );
  10579. }
  10580. // Array of integer / boolean
  10581. function setValueV1iArray( gl, v ) {
  10582. gl.uniform1iv( this.addr, v );
  10583. }
  10584. // Array of integer / boolean vectors (from flat array)
  10585. function setValueV2iArray( gl, v ) {
  10586. gl.uniform2iv( this.addr, v );
  10587. }
  10588. function setValueV3iArray( gl, v ) {
  10589. gl.uniform3iv( this.addr, v );
  10590. }
  10591. function setValueV4iArray( gl, v ) {
  10592. gl.uniform4iv( this.addr, v );
  10593. }
  10594. // Array of unsigned integer
  10595. function setValueV1uiArray( gl, v ) {
  10596. gl.uniform1uiv( this.addr, v );
  10597. }
  10598. // Array of unsigned integer vectors (from flat array)
  10599. function setValueV2uiArray( gl, v ) {
  10600. gl.uniform2uiv( this.addr, v );
  10601. }
  10602. function setValueV3uiArray( gl, v ) {
  10603. gl.uniform3uiv( this.addr, v );
  10604. }
  10605. function setValueV4uiArray( gl, v ) {
  10606. gl.uniform4uiv( this.addr, v );
  10607. }
  10608. // Array of textures (2D / 3D / Cube / 2DArray)
  10609. function setValueT1Array( gl, v, textures ) {
  10610. const n = v.length;
  10611. const units = allocTexUnits( textures, n );
  10612. gl.uniform1iv( this.addr, units );
  10613. for ( let i = 0; i !== n; ++ i ) {
  10614. textures.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  10615. }
  10616. }
  10617. function setValueT3DArray( gl, v, textures ) {
  10618. const n = v.length;
  10619. const units = allocTexUnits( textures, n );
  10620. gl.uniform1iv( this.addr, units );
  10621. for ( let i = 0; i !== n; ++ i ) {
  10622. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  10623. }
  10624. }
  10625. function setValueT6Array( gl, v, textures ) {
  10626. const n = v.length;
  10627. const units = allocTexUnits( textures, n );
  10628. gl.uniform1iv( this.addr, units );
  10629. for ( let i = 0; i !== n; ++ i ) {
  10630. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  10631. }
  10632. }
  10633. function setValueT2DArrayArray( gl, v, textures ) {
  10634. const n = v.length;
  10635. const units = allocTexUnits( textures, n );
  10636. gl.uniform1iv( this.addr, units );
  10637. for ( let i = 0; i !== n; ++ i ) {
  10638. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  10639. }
  10640. }
  10641. // Helper to pick the right setter for a pure (bottom-level) array
  10642. function getPureArraySetter( type ) {
  10643. switch ( type ) {
  10644. case 0x1406: return setValueV1fArray; // FLOAT
  10645. case 0x8b50: return setValueV2fArray; // _VEC2
  10646. case 0x8b51: return setValueV3fArray; // _VEC3
  10647. case 0x8b52: return setValueV4fArray; // _VEC4
  10648. case 0x8b5a: return setValueM2Array; // _MAT2
  10649. case 0x8b5b: return setValueM3Array; // _MAT3
  10650. case 0x8b5c: return setValueM4Array; // _MAT4
  10651. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  10652. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  10653. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  10654. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  10655. case 0x1405: return setValueV1uiArray; // UINT
  10656. case 0x8dc6: return setValueV2uiArray; // _VEC2
  10657. case 0x8dc7: return setValueV3uiArray; // _VEC3
  10658. case 0x8dc8: return setValueV4uiArray; // _VEC4
  10659. case 0x8b5e: // SAMPLER_2D
  10660. case 0x8d66: // SAMPLER_EXTERNAL_OES
  10661. case 0x8dca: // INT_SAMPLER_2D
  10662. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  10663. case 0x8b62: // SAMPLER_2D_SHADOW
  10664. return setValueT1Array;
  10665. case 0x8b5f: // SAMPLER_3D
  10666. case 0x8dcb: // INT_SAMPLER_3D
  10667. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  10668. return setValueT3DArray;
  10669. case 0x8b60: // SAMPLER_CUBE
  10670. case 0x8dcc: // INT_SAMPLER_CUBE
  10671. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  10672. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  10673. return setValueT6Array;
  10674. case 0x8dc1: // SAMPLER_2D_ARRAY
  10675. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  10676. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  10677. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  10678. return setValueT2DArrayArray;
  10679. }
  10680. }
  10681. // --- Uniform Classes ---
  10682. class SingleUniform {
  10683. constructor( id, activeInfo, addr ) {
  10684. this.id = id;
  10685. this.addr = addr;
  10686. this.cache = [];
  10687. this.setValue = getSingularSetter( activeInfo.type );
  10688. // this.path = activeInfo.name; // DEBUG
  10689. }
  10690. }
  10691. class PureArrayUniform {
  10692. constructor( id, activeInfo, addr ) {
  10693. this.id = id;
  10694. this.addr = addr;
  10695. this.cache = [];
  10696. this.size = activeInfo.size;
  10697. this.setValue = getPureArraySetter( activeInfo.type );
  10698. // this.path = activeInfo.name; // DEBUG
  10699. }
  10700. }
  10701. class StructuredUniform {
  10702. constructor( id ) {
  10703. this.id = id;
  10704. this.seq = [];
  10705. this.map = {};
  10706. }
  10707. setValue( gl, value, textures ) {
  10708. const seq = this.seq;
  10709. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10710. const u = seq[ i ];
  10711. u.setValue( gl, value[ u.id ], textures );
  10712. }
  10713. }
  10714. }
  10715. // --- Top-level ---
  10716. // Parser - builds up the property tree from the path strings
  10717. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  10718. // extracts
  10719. // - the identifier (member name or array index)
  10720. // - followed by an optional right bracket (found when array index)
  10721. // - followed by an optional left bracket or dot (type of subscript)
  10722. //
  10723. // Note: These portions can be read in a non-overlapping fashion and
  10724. // allow straightforward parsing of the hierarchy that WebGL encodes
  10725. // in the uniform names.
  10726. function addUniform( container, uniformObject ) {
  10727. container.seq.push( uniformObject );
  10728. container.map[ uniformObject.id ] = uniformObject;
  10729. }
  10730. function parseUniform( activeInfo, addr, container ) {
  10731. const path = activeInfo.name,
  10732. pathLength = path.length;
  10733. // reset RegExp object, because of the early exit of a previous run
  10734. RePathPart.lastIndex = 0;
  10735. while ( true ) {
  10736. const match = RePathPart.exec( path ),
  10737. matchEnd = RePathPart.lastIndex;
  10738. let id = match[ 1 ];
  10739. const idIsIndex = match[ 2 ] === ']',
  10740. subscript = match[ 3 ];
  10741. if ( idIsIndex ) id = id | 0; // convert to integer
  10742. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  10743. // bare name or "pure" bottom-level array "[0]" suffix
  10744. addUniform( container, subscript === undefined ?
  10745. new SingleUniform( id, activeInfo, addr ) :
  10746. new PureArrayUniform( id, activeInfo, addr ) );
  10747. break;
  10748. } else {
  10749. // step into inner node / create it in case it doesn't exist
  10750. const map = container.map;
  10751. let next = map[ id ];
  10752. if ( next === undefined ) {
  10753. next = new StructuredUniform( id );
  10754. addUniform( container, next );
  10755. }
  10756. container = next;
  10757. }
  10758. }
  10759. }
  10760. // Root Container
  10761. class WebGLUniforms {
  10762. constructor( gl, program ) {
  10763. this.seq = [];
  10764. this.map = {};
  10765. const n = gl.getProgramParameter( program, 35718 );
  10766. for ( let i = 0; i < n; ++ i ) {
  10767. const info = gl.getActiveUniform( program, i ),
  10768. addr = gl.getUniformLocation( program, info.name );
  10769. parseUniform( info, addr, this );
  10770. }
  10771. }
  10772. setValue( gl, name, value, textures ) {
  10773. const u = this.map[ name ];
  10774. if ( u !== undefined ) u.setValue( gl, value, textures );
  10775. }
  10776. setOptional( gl, object, name ) {
  10777. const v = object[ name ];
  10778. if ( v !== undefined ) this.setValue( gl, name, v );
  10779. }
  10780. static upload( gl, seq, values, textures ) {
  10781. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10782. const u = seq[ i ],
  10783. v = values[ u.id ];
  10784. if ( v.needsUpdate !== false ) {
  10785. // note: always updating when .needsUpdate is undefined
  10786. u.setValue( gl, v.value, textures );
  10787. }
  10788. }
  10789. }
  10790. static seqWithValue( seq, values ) {
  10791. const r = [];
  10792. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  10793. const u = seq[ i ];
  10794. if ( u.id in values ) r.push( u );
  10795. }
  10796. return r;
  10797. }
  10798. }
  10799. function WebGLShader( gl, type, string ) {
  10800. const shader = gl.createShader( type );
  10801. gl.shaderSource( shader, string );
  10802. gl.compileShader( shader );
  10803. return shader;
  10804. }
  10805. let programIdCount = 0;
  10806. function handleSource( string, errorLine ) {
  10807. const lines = string.split( '\n' );
  10808. const lines2 = [];
  10809. const from = Math.max( errorLine - 6, 0 );
  10810. const to = Math.min( errorLine + 6, lines.length );
  10811. for ( let i = from; i < to; i ++ ) {
  10812. const line = i + 1;
  10813. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  10814. }
  10815. return lines2.join( '\n' );
  10816. }
  10817. function getEncodingComponents( encoding ) {
  10818. switch ( encoding ) {
  10819. case LinearEncoding:
  10820. return [ 'Linear', '( value )' ];
  10821. case sRGBEncoding:
  10822. return [ 'sRGB', '( value )' ];
  10823. default:
  10824. console.warn( 'THREE.WebGLProgram: Unsupported encoding:', encoding );
  10825. return [ 'Linear', '( value )' ];
  10826. }
  10827. }
  10828. function getShaderErrors( gl, shader, type ) {
  10829. const status = gl.getShaderParameter( shader, 35713 );
  10830. const errors = gl.getShaderInfoLog( shader ).trim();
  10831. if ( status && errors === '' ) return '';
  10832. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  10833. if ( errorMatches ) {
  10834. // --enable-privileged-webgl-extension
  10835. // console.log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  10836. const errorLine = parseInt( errorMatches[ 1 ] );
  10837. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  10838. } else {
  10839. return errors;
  10840. }
  10841. }
  10842. function getTexelEncodingFunction( functionName, encoding ) {
  10843. const components = getEncodingComponents( encoding );
  10844. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  10845. }
  10846. function getToneMappingFunction( functionName, toneMapping ) {
  10847. let toneMappingName;
  10848. switch ( toneMapping ) {
  10849. case LinearToneMapping:
  10850. toneMappingName = 'Linear';
  10851. break;
  10852. case ReinhardToneMapping:
  10853. toneMappingName = 'Reinhard';
  10854. break;
  10855. case CineonToneMapping:
  10856. toneMappingName = 'OptimizedCineon';
  10857. break;
  10858. case ACESFilmicToneMapping:
  10859. toneMappingName = 'ACESFilmic';
  10860. break;
  10861. case CustomToneMapping:
  10862. toneMappingName = 'Custom';
  10863. break;
  10864. default:
  10865. console.warn( 'THREE.WebGLProgram: Unsupported toneMapping:', toneMapping );
  10866. toneMappingName = 'Linear';
  10867. }
  10868. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  10869. }
  10870. function generateExtensions( parameters ) {
  10871. const chunks = [
  10872. ( parameters.extensionDerivatives || !! parameters.envMapCubeUVHeight || parameters.bumpMap || parameters.tangentSpaceNormalMap || parameters.clearcoatNormalMap || parameters.flatShading || parameters.shaderID === 'physical' ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  10873. ( parameters.extensionFragDepth || parameters.logarithmicDepthBuffer ) && parameters.rendererExtensionFragDepth ? '#extension GL_EXT_frag_depth : enable' : '',
  10874. ( parameters.extensionDrawBuffers && parameters.rendererExtensionDrawBuffers ) ? '#extension GL_EXT_draw_buffers : require' : '',
  10875. ( parameters.extensionShaderTextureLOD || parameters.envMap || parameters.transmission ) && parameters.rendererExtensionShaderTextureLod ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  10876. ];
  10877. return chunks.filter( filterEmptyLine ).join( '\n' );
  10878. }
  10879. function generateDefines( defines ) {
  10880. const chunks = [];
  10881. for ( const name in defines ) {
  10882. const value = defines[ name ];
  10883. if ( value === false ) continue;
  10884. chunks.push( '#define ' + name + ' ' + value );
  10885. }
  10886. return chunks.join( '\n' );
  10887. }
  10888. function fetchAttributeLocations( gl, program ) {
  10889. const attributes = {};
  10890. const n = gl.getProgramParameter( program, 35721 );
  10891. for ( let i = 0; i < n; i ++ ) {
  10892. const info = gl.getActiveAttrib( program, i );
  10893. const name = info.name;
  10894. let locationSize = 1;
  10895. if ( info.type === 35674 ) locationSize = 2;
  10896. if ( info.type === 35675 ) locationSize = 3;
  10897. if ( info.type === 35676 ) locationSize = 4;
  10898. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  10899. attributes[ name ] = {
  10900. type: info.type,
  10901. location: gl.getAttribLocation( program, name ),
  10902. locationSize: locationSize
  10903. };
  10904. }
  10905. return attributes;
  10906. }
  10907. function filterEmptyLine( string ) {
  10908. return string !== '';
  10909. }
  10910. function replaceLightNums( string, parameters ) {
  10911. return string
  10912. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  10913. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  10914. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  10915. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  10916. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  10917. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  10918. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  10919. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  10920. }
  10921. function replaceClippingPlaneNums( string, parameters ) {
  10922. return string
  10923. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  10924. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  10925. }
  10926. // Resolve Includes
  10927. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  10928. function resolveIncludes( string ) {
  10929. return string.replace( includePattern, includeReplacer );
  10930. }
  10931. function includeReplacer( match, include ) {
  10932. const string = ShaderChunk[ include ];
  10933. if ( string === undefined ) {
  10934. throw new Error( 'Can not resolve #include <' + include + '>' );
  10935. }
  10936. return resolveIncludes( string );
  10937. }
  10938. // Unroll Loops
  10939. 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;
  10940. function unrollLoops( string ) {
  10941. return string.replace( unrollLoopPattern, loopReplacer );
  10942. }
  10943. function loopReplacer( match, start, end, snippet ) {
  10944. let string = '';
  10945. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  10946. string += snippet
  10947. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  10948. .replace( /UNROLLED_LOOP_INDEX/g, i );
  10949. }
  10950. return string;
  10951. }
  10952. //
  10953. function generatePrecision( parameters ) {
  10954. let precisionstring = 'precision ' + parameters.precision + ' float;\nprecision ' + parameters.precision + ' int;';
  10955. if ( parameters.precision === 'highp' ) {
  10956. precisionstring += '\n#define HIGH_PRECISION';
  10957. } else if ( parameters.precision === 'mediump' ) {
  10958. precisionstring += '\n#define MEDIUM_PRECISION';
  10959. } else if ( parameters.precision === 'lowp' ) {
  10960. precisionstring += '\n#define LOW_PRECISION';
  10961. }
  10962. return precisionstring;
  10963. }
  10964. function generateShadowMapTypeDefine( parameters ) {
  10965. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  10966. if ( parameters.shadowMapType === PCFShadowMap ) {
  10967. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  10968. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  10969. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  10970. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  10971. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  10972. }
  10973. return shadowMapTypeDefine;
  10974. }
  10975. function generateEnvMapTypeDefine( parameters ) {
  10976. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10977. if ( parameters.envMap ) {
  10978. switch ( parameters.envMapMode ) {
  10979. case CubeReflectionMapping:
  10980. case CubeRefractionMapping:
  10981. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  10982. break;
  10983. case CubeUVReflectionMapping:
  10984. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  10985. break;
  10986. }
  10987. }
  10988. return envMapTypeDefine;
  10989. }
  10990. function generateEnvMapModeDefine( parameters ) {
  10991. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  10992. if ( parameters.envMap ) {
  10993. switch ( parameters.envMapMode ) {
  10994. case CubeRefractionMapping:
  10995. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  10996. break;
  10997. }
  10998. }
  10999. return envMapModeDefine;
  11000. }
  11001. function generateEnvMapBlendingDefine( parameters ) {
  11002. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  11003. if ( parameters.envMap ) {
  11004. switch ( parameters.combine ) {
  11005. case MultiplyOperation:
  11006. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  11007. break;
  11008. case MixOperation:
  11009. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  11010. break;
  11011. case AddOperation:
  11012. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  11013. break;
  11014. }
  11015. }
  11016. return envMapBlendingDefine;
  11017. }
  11018. function generateCubeUVSize( parameters ) {
  11019. const imageHeight = parameters.envMapCubeUVHeight;
  11020. if ( imageHeight === null ) return null;
  11021. const maxMip = Math.log2( imageHeight ) - 2;
  11022. const texelHeight = 1.0 / imageHeight;
  11023. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  11024. return { texelWidth, texelHeight, maxMip };
  11025. }
  11026. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  11027. // TODO Send this event to Three.js DevTools
  11028. // console.log( 'WebGLProgram', cacheKey );
  11029. const gl = renderer.getContext();
  11030. const defines = parameters.defines;
  11031. let vertexShader = parameters.vertexShader;
  11032. let fragmentShader = parameters.fragmentShader;
  11033. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  11034. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  11035. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  11036. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  11037. const envMapCubeUVSize = generateCubeUVSize( parameters );
  11038. const customExtensions = parameters.isWebGL2 ? '' : generateExtensions( parameters );
  11039. const customDefines = generateDefines( defines );
  11040. const program = gl.createProgram();
  11041. let prefixVertex, prefixFragment;
  11042. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  11043. if ( parameters.isRawShaderMaterial ) {
  11044. prefixVertex = [
  11045. customDefines
  11046. ].filter( filterEmptyLine ).join( '\n' );
  11047. if ( prefixVertex.length > 0 ) {
  11048. prefixVertex += '\n';
  11049. }
  11050. prefixFragment = [
  11051. customExtensions,
  11052. customDefines
  11053. ].filter( filterEmptyLine ).join( '\n' );
  11054. if ( prefixFragment.length > 0 ) {
  11055. prefixFragment += '\n';
  11056. }
  11057. } else {
  11058. prefixVertex = [
  11059. generatePrecision( parameters ),
  11060. '#define SHADER_NAME ' + parameters.shaderName,
  11061. customDefines,
  11062. parameters.instancing ? '#define USE_INSTANCING' : '',
  11063. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  11064. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  11065. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11066. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11067. parameters.map ? '#define USE_MAP' : '',
  11068. parameters.envMap ? '#define USE_ENVMAP' : '',
  11069. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11070. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11071. parameters.aoMap ? '#define USE_AOMAP' : '',
  11072. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11073. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11074. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11075. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11076. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11077. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11078. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11079. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11080. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11081. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11082. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  11083. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11084. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  11085. parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '',
  11086. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11087. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11088. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11089. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11090. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11091. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11092. parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '',
  11093. parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '',
  11094. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11095. parameters.vertexColors ? '#define USE_COLOR' : '',
  11096. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11097. parameters.vertexUvs ? '#define USE_UV' : '',
  11098. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11099. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11100. parameters.skinning ? '#define USE_SKINNING' : '',
  11101. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  11102. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  11103. ( parameters.morphColors && parameters.isWebGL2 ) ? '#define USE_MORPHCOLORS' : '',
  11104. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE' : '',
  11105. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  11106. ( parameters.morphTargetsCount > 0 && parameters.isWebGL2 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  11107. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11108. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11109. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11110. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11111. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  11112. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11113. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11114. 'uniform mat4 modelMatrix;',
  11115. 'uniform mat4 modelViewMatrix;',
  11116. 'uniform mat4 projectionMatrix;',
  11117. 'uniform mat4 viewMatrix;',
  11118. 'uniform mat3 normalMatrix;',
  11119. 'uniform vec3 cameraPosition;',
  11120. 'uniform bool isOrthographic;',
  11121. '#ifdef USE_INSTANCING',
  11122. ' attribute mat4 instanceMatrix;',
  11123. '#endif',
  11124. '#ifdef USE_INSTANCING_COLOR',
  11125. ' attribute vec3 instanceColor;',
  11126. '#endif',
  11127. 'attribute vec3 position;',
  11128. 'attribute vec3 normal;',
  11129. 'attribute vec2 uv;',
  11130. '#ifdef USE_TANGENT',
  11131. ' attribute vec4 tangent;',
  11132. '#endif',
  11133. '#if defined( USE_COLOR_ALPHA )',
  11134. ' attribute vec4 color;',
  11135. '#elif defined( USE_COLOR )',
  11136. ' attribute vec3 color;',
  11137. '#endif',
  11138. '#if ( defined( USE_MORPHTARGETS ) && ! defined( MORPHTARGETS_TEXTURE ) )',
  11139. ' attribute vec3 morphTarget0;',
  11140. ' attribute vec3 morphTarget1;',
  11141. ' attribute vec3 morphTarget2;',
  11142. ' attribute vec3 morphTarget3;',
  11143. ' #ifdef USE_MORPHNORMALS',
  11144. ' attribute vec3 morphNormal0;',
  11145. ' attribute vec3 morphNormal1;',
  11146. ' attribute vec3 morphNormal2;',
  11147. ' attribute vec3 morphNormal3;',
  11148. ' #else',
  11149. ' attribute vec3 morphTarget4;',
  11150. ' attribute vec3 morphTarget5;',
  11151. ' attribute vec3 morphTarget6;',
  11152. ' attribute vec3 morphTarget7;',
  11153. ' #endif',
  11154. '#endif',
  11155. '#ifdef USE_SKINNING',
  11156. ' attribute vec4 skinIndex;',
  11157. ' attribute vec4 skinWeight;',
  11158. '#endif',
  11159. '\n'
  11160. ].filter( filterEmptyLine ).join( '\n' );
  11161. prefixFragment = [
  11162. customExtensions,
  11163. generatePrecision( parameters ),
  11164. '#define SHADER_NAME ' + parameters.shaderName,
  11165. customDefines,
  11166. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  11167. ( parameters.useFog && parameters.fogExp2 ) ? '#define FOG_EXP2' : '',
  11168. parameters.map ? '#define USE_MAP' : '',
  11169. parameters.matcap ? '#define USE_MATCAP' : '',
  11170. parameters.envMap ? '#define USE_ENVMAP' : '',
  11171. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  11172. parameters.envMap ? '#define ' + envMapModeDefine : '',
  11173. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  11174. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  11175. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  11176. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  11177. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  11178. parameters.aoMap ? '#define USE_AOMAP' : '',
  11179. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  11180. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  11181. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  11182. ( parameters.normalMap && parameters.objectSpaceNormalMap ) ? '#define OBJECTSPACE_NORMALMAP' : '',
  11183. ( parameters.normalMap && parameters.tangentSpaceNormalMap ) ? '#define TANGENTSPACE_NORMALMAP' : '',
  11184. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  11185. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  11186. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  11187. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  11188. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  11189. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  11190. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  11191. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  11192. parameters.specularIntensityMap ? '#define USE_SPECULARINTENSITYMAP' : '',
  11193. parameters.specularColorMap ? '#define USE_SPECULARCOLORMAP' : '',
  11194. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  11195. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  11196. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  11197. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  11198. parameters.sheen ? '#define USE_SHEEN' : '',
  11199. parameters.sheenColorMap ? '#define USE_SHEENCOLORMAP' : '',
  11200. parameters.sheenRoughnessMap ? '#define USE_SHEENROUGHNESSMAP' : '',
  11201. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  11202. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  11203. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  11204. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  11205. parameters.vertexTangents ? '#define USE_TANGENT' : '',
  11206. parameters.vertexColors || parameters.instancingColor ? '#define USE_COLOR' : '',
  11207. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  11208. parameters.vertexUvs ? '#define USE_UV' : '',
  11209. parameters.uvsVertexOnly ? '#define UVS_VERTEX_ONLY' : '',
  11210. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  11211. parameters.flatShading ? '#define FLAT_SHADED' : '',
  11212. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  11213. parameters.flipSided ? '#define FLIP_SIDED' : '',
  11214. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  11215. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  11216. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  11217. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  11218. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  11219. ( parameters.logarithmicDepthBuffer && parameters.rendererExtensionFragDepth ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  11220. 'uniform mat4 viewMatrix;',
  11221. 'uniform vec3 cameraPosition;',
  11222. 'uniform bool isOrthographic;',
  11223. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  11224. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  11225. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  11226. parameters.dithering ? '#define DITHERING' : '',
  11227. parameters.opaque ? '#define OPAQUE' : '',
  11228. ShaderChunk[ 'encodings_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  11229. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ),
  11230. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  11231. '\n'
  11232. ].filter( filterEmptyLine ).join( '\n' );
  11233. }
  11234. vertexShader = resolveIncludes( vertexShader );
  11235. vertexShader = replaceLightNums( vertexShader, parameters );
  11236. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  11237. fragmentShader = resolveIncludes( fragmentShader );
  11238. fragmentShader = replaceLightNums( fragmentShader, parameters );
  11239. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  11240. vertexShader = unrollLoops( vertexShader );
  11241. fragmentShader = unrollLoops( fragmentShader );
  11242. if ( parameters.isWebGL2 && parameters.isRawShaderMaterial !== true ) {
  11243. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  11244. versionString = '#version 300 es\n';
  11245. prefixVertex = [
  11246. 'precision mediump sampler2DArray;',
  11247. '#define attribute in',
  11248. '#define varying out',
  11249. '#define texture2D texture'
  11250. ].join( '\n' ) + '\n' + prefixVertex;
  11251. prefixFragment = [
  11252. '#define varying in',
  11253. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  11254. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  11255. '#define gl_FragDepthEXT gl_FragDepth',
  11256. '#define texture2D texture',
  11257. '#define textureCube texture',
  11258. '#define texture2DProj textureProj',
  11259. '#define texture2DLodEXT textureLod',
  11260. '#define texture2DProjLodEXT textureProjLod',
  11261. '#define textureCubeLodEXT textureLod',
  11262. '#define texture2DGradEXT textureGrad',
  11263. '#define texture2DProjGradEXT textureProjGrad',
  11264. '#define textureCubeGradEXT textureGrad'
  11265. ].join( '\n' ) + '\n' + prefixFragment;
  11266. }
  11267. const vertexGlsl = versionString + prefixVertex + vertexShader;
  11268. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  11269. // console.log( '*VERTEX*', vertexGlsl );
  11270. // console.log( '*FRAGMENT*', fragmentGlsl );
  11271. const glVertexShader = WebGLShader( gl, 35633, vertexGlsl );
  11272. const glFragmentShader = WebGLShader( gl, 35632, fragmentGlsl );
  11273. gl.attachShader( program, glVertexShader );
  11274. gl.attachShader( program, glFragmentShader );
  11275. // Force a particular attribute to index 0.
  11276. if ( parameters.index0AttributeName !== undefined ) {
  11277. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  11278. } else if ( parameters.morphTargets === true ) {
  11279. // programs with morphTargets displace position out of attribute 0
  11280. gl.bindAttribLocation( program, 0, 'position' );
  11281. }
  11282. gl.linkProgram( program );
  11283. // check for link errors
  11284. if ( renderer.debug.checkShaderErrors ) {
  11285. const programLog = gl.getProgramInfoLog( program ).trim();
  11286. const vertexLog = gl.getShaderInfoLog( glVertexShader ).trim();
  11287. const fragmentLog = gl.getShaderInfoLog( glFragmentShader ).trim();
  11288. let runnable = true;
  11289. let haveDiagnostics = true;
  11290. if ( gl.getProgramParameter( program, 35714 ) === false ) {
  11291. runnable = false;
  11292. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  11293. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  11294. console.error(
  11295. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  11296. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, 35715 ) + '\n\n' +
  11297. 'Program Info Log: ' + programLog + '\n' +
  11298. vertexErrors + '\n' +
  11299. fragmentErrors
  11300. );
  11301. } else if ( programLog !== '' ) {
  11302. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  11303. } else if ( vertexLog === '' || fragmentLog === '' ) {
  11304. haveDiagnostics = false;
  11305. }
  11306. if ( haveDiagnostics ) {
  11307. this.diagnostics = {
  11308. runnable: runnable,
  11309. programLog: programLog,
  11310. vertexShader: {
  11311. log: vertexLog,
  11312. prefix: prefixVertex
  11313. },
  11314. fragmentShader: {
  11315. log: fragmentLog,
  11316. prefix: prefixFragment
  11317. }
  11318. };
  11319. }
  11320. }
  11321. // Clean up
  11322. // Crashes in iOS9 and iOS10. #18402
  11323. // gl.detachShader( program, glVertexShader );
  11324. // gl.detachShader( program, glFragmentShader );
  11325. gl.deleteShader( glVertexShader );
  11326. gl.deleteShader( glFragmentShader );
  11327. // set up caching for uniform locations
  11328. let cachedUniforms;
  11329. this.getUniforms = function () {
  11330. if ( cachedUniforms === undefined ) {
  11331. cachedUniforms = new WebGLUniforms( gl, program );
  11332. }
  11333. return cachedUniforms;
  11334. };
  11335. // set up caching for attribute locations
  11336. let cachedAttributes;
  11337. this.getAttributes = function () {
  11338. if ( cachedAttributes === undefined ) {
  11339. cachedAttributes = fetchAttributeLocations( gl, program );
  11340. }
  11341. return cachedAttributes;
  11342. };
  11343. // free resource
  11344. this.destroy = function () {
  11345. bindingStates.releaseStatesOfProgram( this );
  11346. gl.deleteProgram( program );
  11347. this.program = undefined;
  11348. };
  11349. //
  11350. this.name = parameters.shaderName;
  11351. this.id = programIdCount ++;
  11352. this.cacheKey = cacheKey;
  11353. this.usedTimes = 1;
  11354. this.program = program;
  11355. this.vertexShader = glVertexShader;
  11356. this.fragmentShader = glFragmentShader;
  11357. return this;
  11358. }
  11359. let _id = 0;
  11360. class WebGLShaderCache {
  11361. constructor() {
  11362. this.shaderCache = new Map();
  11363. this.materialCache = new Map();
  11364. }
  11365. update( material ) {
  11366. const vertexShader = material.vertexShader;
  11367. const fragmentShader = material.fragmentShader;
  11368. const vertexShaderStage = this._getShaderStage( vertexShader );
  11369. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  11370. const materialShaders = this._getShaderCacheForMaterial( material );
  11371. if ( materialShaders.has( vertexShaderStage ) === false ) {
  11372. materialShaders.add( vertexShaderStage );
  11373. vertexShaderStage.usedTimes ++;
  11374. }
  11375. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  11376. materialShaders.add( fragmentShaderStage );
  11377. fragmentShaderStage.usedTimes ++;
  11378. }
  11379. return this;
  11380. }
  11381. remove( material ) {
  11382. const materialShaders = this.materialCache.get( material );
  11383. for ( const shaderStage of materialShaders ) {
  11384. shaderStage.usedTimes --;
  11385. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  11386. }
  11387. this.materialCache.delete( material );
  11388. return this;
  11389. }
  11390. getVertexShaderID( material ) {
  11391. return this._getShaderStage( material.vertexShader ).id;
  11392. }
  11393. getFragmentShaderID( material ) {
  11394. return this._getShaderStage( material.fragmentShader ).id;
  11395. }
  11396. dispose() {
  11397. this.shaderCache.clear();
  11398. this.materialCache.clear();
  11399. }
  11400. _getShaderCacheForMaterial( material ) {
  11401. const cache = this.materialCache;
  11402. let set = cache.get( material );
  11403. if ( set === undefined ) {
  11404. set = new Set();
  11405. cache.set( material, set );
  11406. }
  11407. return set;
  11408. }
  11409. _getShaderStage( code ) {
  11410. const cache = this.shaderCache;
  11411. let stage = cache.get( code );
  11412. if ( stage === undefined ) {
  11413. stage = new WebGLShaderStage( code );
  11414. cache.set( code, stage );
  11415. }
  11416. return stage;
  11417. }
  11418. }
  11419. class WebGLShaderStage {
  11420. constructor( code ) {
  11421. this.id = _id ++;
  11422. this.code = code;
  11423. this.usedTimes = 0;
  11424. }
  11425. }
  11426. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  11427. const _programLayers = new Layers();
  11428. const _customShaders = new WebGLShaderCache();
  11429. const programs = [];
  11430. const isWebGL2 = capabilities.isWebGL2;
  11431. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  11432. const vertexTextures = capabilities.vertexTextures;
  11433. let precision = capabilities.precision;
  11434. const shaderIDs = {
  11435. MeshDepthMaterial: 'depth',
  11436. MeshDistanceMaterial: 'distanceRGBA',
  11437. MeshNormalMaterial: 'normal',
  11438. MeshBasicMaterial: 'basic',
  11439. MeshLambertMaterial: 'lambert',
  11440. MeshPhongMaterial: 'phong',
  11441. MeshToonMaterial: 'toon',
  11442. MeshStandardMaterial: 'physical',
  11443. MeshPhysicalMaterial: 'physical',
  11444. MeshMatcapMaterial: 'matcap',
  11445. LineBasicMaterial: 'basic',
  11446. LineDashedMaterial: 'dashed',
  11447. PointsMaterial: 'points',
  11448. ShadowMaterial: 'shadow',
  11449. SpriteMaterial: 'sprite'
  11450. };
  11451. function getParameters( material, lights, shadows, scene, object ) {
  11452. const fog = scene.fog;
  11453. const geometry = object.geometry;
  11454. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  11455. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  11456. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  11457. const shaderID = shaderIDs[ material.type ];
  11458. // heuristics to create shader parameters according to lights in the scene
  11459. // (not to blow over maxLights budget)
  11460. if ( material.precision !== null ) {
  11461. precision = capabilities.getMaxPrecision( material.precision );
  11462. if ( precision !== material.precision ) {
  11463. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  11464. }
  11465. }
  11466. //
  11467. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11468. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11469. let morphTextureStride = 0;
  11470. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  11471. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  11472. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  11473. //
  11474. let vertexShader, fragmentShader;
  11475. let customVertexShaderID, customFragmentShaderID;
  11476. if ( shaderID ) {
  11477. const shader = ShaderLib[ shaderID ];
  11478. vertexShader = shader.vertexShader;
  11479. fragmentShader = shader.fragmentShader;
  11480. } else {
  11481. vertexShader = material.vertexShader;
  11482. fragmentShader = material.fragmentShader;
  11483. _customShaders.update( material );
  11484. customVertexShaderID = _customShaders.getVertexShaderID( material );
  11485. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  11486. }
  11487. const currentRenderTarget = renderer.getRenderTarget();
  11488. const useAlphaTest = material.alphaTest > 0;
  11489. const useClearcoat = material.clearcoat > 0;
  11490. const useIridescence = material.iridescence > 0;
  11491. const parameters = {
  11492. isWebGL2: isWebGL2,
  11493. shaderID: shaderID,
  11494. shaderName: material.type,
  11495. vertexShader: vertexShader,
  11496. fragmentShader: fragmentShader,
  11497. defines: material.defines,
  11498. customVertexShaderID: customVertexShaderID,
  11499. customFragmentShaderID: customFragmentShaderID,
  11500. isRawShaderMaterial: material.isRawShaderMaterial === true,
  11501. glslVersion: material.glslVersion,
  11502. precision: precision,
  11503. instancing: object.isInstancedMesh === true,
  11504. instancingColor: object.isInstancedMesh === true && object.instanceColor !== null,
  11505. supportsVertexTextures: vertexTextures,
  11506. outputEncoding: ( currentRenderTarget === null ) ? renderer.outputEncoding : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.encoding : LinearEncoding ),
  11507. map: !! material.map,
  11508. matcap: !! material.matcap,
  11509. envMap: !! envMap,
  11510. envMapMode: envMap && envMap.mapping,
  11511. envMapCubeUVHeight: envMapCubeUVHeight,
  11512. lightMap: !! material.lightMap,
  11513. aoMap: !! material.aoMap,
  11514. emissiveMap: !! material.emissiveMap,
  11515. bumpMap: !! material.bumpMap,
  11516. normalMap: !! material.normalMap,
  11517. objectSpaceNormalMap: material.normalMapType === ObjectSpaceNormalMap,
  11518. tangentSpaceNormalMap: material.normalMapType === TangentSpaceNormalMap,
  11519. decodeVideoTexture: !! material.map && ( material.map.isVideoTexture === true ) && ( material.map.encoding === sRGBEncoding ),
  11520. clearcoat: useClearcoat,
  11521. clearcoatMap: useClearcoat && !! material.clearcoatMap,
  11522. clearcoatRoughnessMap: useClearcoat && !! material.clearcoatRoughnessMap,
  11523. clearcoatNormalMap: useClearcoat && !! material.clearcoatNormalMap,
  11524. iridescence: useIridescence,
  11525. iridescenceMap: useIridescence && !! material.iridescenceMap,
  11526. iridescenceThicknessMap: useIridescence && !! material.iridescenceThicknessMap,
  11527. displacementMap: !! material.displacementMap,
  11528. roughnessMap: !! material.roughnessMap,
  11529. metalnessMap: !! material.metalnessMap,
  11530. specularMap: !! material.specularMap,
  11531. specularIntensityMap: !! material.specularIntensityMap,
  11532. specularColorMap: !! material.specularColorMap,
  11533. opaque: material.transparent === false && material.blending === NormalBlending,
  11534. alphaMap: !! material.alphaMap,
  11535. alphaTest: useAlphaTest,
  11536. gradientMap: !! material.gradientMap,
  11537. sheen: material.sheen > 0,
  11538. sheenColorMap: !! material.sheenColorMap,
  11539. sheenRoughnessMap: !! material.sheenRoughnessMap,
  11540. transmission: material.transmission > 0,
  11541. transmissionMap: !! material.transmissionMap,
  11542. thicknessMap: !! material.thicknessMap,
  11543. combine: material.combine,
  11544. vertexTangents: ( !! material.normalMap && !! geometry.attributes.tangent ),
  11545. vertexColors: material.vertexColors,
  11546. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  11547. 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,
  11548. 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,
  11549. fog: !! fog,
  11550. useFog: material.fog === true,
  11551. fogExp2: ( fog && fog.isFogExp2 ),
  11552. flatShading: !! material.flatShading,
  11553. sizeAttenuation: material.sizeAttenuation,
  11554. logarithmicDepthBuffer: logarithmicDepthBuffer,
  11555. skinning: object.isSkinnedMesh === true,
  11556. morphTargets: geometry.morphAttributes.position !== undefined,
  11557. morphNormals: geometry.morphAttributes.normal !== undefined,
  11558. morphColors: geometry.morphAttributes.color !== undefined,
  11559. morphTargetsCount: morphTargetsCount,
  11560. morphTextureStride: morphTextureStride,
  11561. numDirLights: lights.directional.length,
  11562. numPointLights: lights.point.length,
  11563. numSpotLights: lights.spot.length,
  11564. numRectAreaLights: lights.rectArea.length,
  11565. numHemiLights: lights.hemi.length,
  11566. numDirLightShadows: lights.directionalShadowMap.length,
  11567. numPointLightShadows: lights.pointShadowMap.length,
  11568. numSpotLightShadows: lights.spotShadowMap.length,
  11569. numClippingPlanes: clipping.numPlanes,
  11570. numClipIntersection: clipping.numIntersection,
  11571. dithering: material.dithering,
  11572. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  11573. shadowMapType: renderer.shadowMap.type,
  11574. toneMapping: material.toneMapped ? renderer.toneMapping : NoToneMapping,
  11575. physicallyCorrectLights: renderer.physicallyCorrectLights,
  11576. premultipliedAlpha: material.premultipliedAlpha,
  11577. doubleSided: material.side === DoubleSide,
  11578. flipSided: material.side === BackSide,
  11579. useDepthPacking: !! material.depthPacking,
  11580. depthPacking: material.depthPacking || 0,
  11581. index0AttributeName: material.index0AttributeName,
  11582. extensionDerivatives: material.extensions && material.extensions.derivatives,
  11583. extensionFragDepth: material.extensions && material.extensions.fragDepth,
  11584. extensionDrawBuffers: material.extensions && material.extensions.drawBuffers,
  11585. extensionShaderTextureLOD: material.extensions && material.extensions.shaderTextureLOD,
  11586. rendererExtensionFragDepth: isWebGL2 || extensions.has( 'EXT_frag_depth' ),
  11587. rendererExtensionDrawBuffers: isWebGL2 || extensions.has( 'WEBGL_draw_buffers' ),
  11588. rendererExtensionShaderTextureLod: isWebGL2 || extensions.has( 'EXT_shader_texture_lod' ),
  11589. customProgramCacheKey: material.customProgramCacheKey()
  11590. };
  11591. return parameters;
  11592. }
  11593. function getProgramCacheKey( parameters ) {
  11594. const array = [];
  11595. if ( parameters.shaderID ) {
  11596. array.push( parameters.shaderID );
  11597. } else {
  11598. array.push( parameters.customVertexShaderID );
  11599. array.push( parameters.customFragmentShaderID );
  11600. }
  11601. if ( parameters.defines !== undefined ) {
  11602. for ( const name in parameters.defines ) {
  11603. array.push( name );
  11604. array.push( parameters.defines[ name ] );
  11605. }
  11606. }
  11607. if ( parameters.isRawShaderMaterial === false ) {
  11608. getProgramCacheKeyParameters( array, parameters );
  11609. getProgramCacheKeyBooleans( array, parameters );
  11610. array.push( renderer.outputEncoding );
  11611. }
  11612. array.push( parameters.customProgramCacheKey );
  11613. return array.join();
  11614. }
  11615. function getProgramCacheKeyParameters( array, parameters ) {
  11616. array.push( parameters.precision );
  11617. array.push( parameters.outputEncoding );
  11618. array.push( parameters.envMapMode );
  11619. array.push( parameters.envMapCubeUVHeight );
  11620. array.push( parameters.combine );
  11621. array.push( parameters.vertexUvs );
  11622. array.push( parameters.fogExp2 );
  11623. array.push( parameters.sizeAttenuation );
  11624. array.push( parameters.morphTargetsCount );
  11625. array.push( parameters.morphAttributeCount );
  11626. array.push( parameters.numDirLights );
  11627. array.push( parameters.numPointLights );
  11628. array.push( parameters.numSpotLights );
  11629. array.push( parameters.numHemiLights );
  11630. array.push( parameters.numRectAreaLights );
  11631. array.push( parameters.numDirLightShadows );
  11632. array.push( parameters.numPointLightShadows );
  11633. array.push( parameters.numSpotLightShadows );
  11634. array.push( parameters.shadowMapType );
  11635. array.push( parameters.toneMapping );
  11636. array.push( parameters.numClippingPlanes );
  11637. array.push( parameters.numClipIntersection );
  11638. array.push( parameters.depthPacking );
  11639. }
  11640. function getProgramCacheKeyBooleans( array, parameters ) {
  11641. _programLayers.disableAll();
  11642. if ( parameters.isWebGL2 )
  11643. _programLayers.enable( 0 );
  11644. if ( parameters.supportsVertexTextures )
  11645. _programLayers.enable( 1 );
  11646. if ( parameters.instancing )
  11647. _programLayers.enable( 2 );
  11648. if ( parameters.instancingColor )
  11649. _programLayers.enable( 3 );
  11650. if ( parameters.map )
  11651. _programLayers.enable( 4 );
  11652. if ( parameters.matcap )
  11653. _programLayers.enable( 5 );
  11654. if ( parameters.envMap )
  11655. _programLayers.enable( 6 );
  11656. if ( parameters.lightMap )
  11657. _programLayers.enable( 7 );
  11658. if ( parameters.aoMap )
  11659. _programLayers.enable( 8 );
  11660. if ( parameters.emissiveMap )
  11661. _programLayers.enable( 9 );
  11662. if ( parameters.bumpMap )
  11663. _programLayers.enable( 10 );
  11664. if ( parameters.normalMap )
  11665. _programLayers.enable( 11 );
  11666. if ( parameters.objectSpaceNormalMap )
  11667. _programLayers.enable( 12 );
  11668. if ( parameters.tangentSpaceNormalMap )
  11669. _programLayers.enable( 13 );
  11670. if ( parameters.clearcoat )
  11671. _programLayers.enable( 14 );
  11672. if ( parameters.clearcoatMap )
  11673. _programLayers.enable( 15 );
  11674. if ( parameters.clearcoatRoughnessMap )
  11675. _programLayers.enable( 16 );
  11676. if ( parameters.clearcoatNormalMap )
  11677. _programLayers.enable( 17 );
  11678. if ( parameters.iridescence )
  11679. _programLayers.enable( 18 );
  11680. if ( parameters.iridescenceMap )
  11681. _programLayers.enable( 19 );
  11682. if ( parameters.iridescenceThicknessMap )
  11683. _programLayers.enable( 20 );
  11684. if ( parameters.displacementMap )
  11685. _programLayers.enable( 21 );
  11686. if ( parameters.specularMap )
  11687. _programLayers.enable( 22 );
  11688. if ( parameters.roughnessMap )
  11689. _programLayers.enable( 23 );
  11690. if ( parameters.metalnessMap )
  11691. _programLayers.enable( 24 );
  11692. if ( parameters.gradientMap )
  11693. _programLayers.enable( 25 );
  11694. if ( parameters.alphaMap )
  11695. _programLayers.enable( 26 );
  11696. if ( parameters.alphaTest )
  11697. _programLayers.enable( 27 );
  11698. if ( parameters.vertexColors )
  11699. _programLayers.enable( 28 );
  11700. if ( parameters.vertexAlphas )
  11701. _programLayers.enable( 29 );
  11702. if ( parameters.vertexUvs )
  11703. _programLayers.enable( 30 );
  11704. if ( parameters.vertexTangents )
  11705. _programLayers.enable( 31 );
  11706. if ( parameters.uvsVertexOnly )
  11707. _programLayers.enable( 32 );
  11708. array.push( _programLayers.mask );
  11709. _programLayers.disableAll();
  11710. if ( parameters.fog )
  11711. _programLayers.enable( 0 );
  11712. if ( parameters.useFog )
  11713. _programLayers.enable( 1 );
  11714. if ( parameters.flatShading )
  11715. _programLayers.enable( 2 );
  11716. if ( parameters.logarithmicDepthBuffer )
  11717. _programLayers.enable( 3 );
  11718. if ( parameters.skinning )
  11719. _programLayers.enable( 4 );
  11720. if ( parameters.morphTargets )
  11721. _programLayers.enable( 5 );
  11722. if ( parameters.morphNormals )
  11723. _programLayers.enable( 6 );
  11724. if ( parameters.morphColors )
  11725. _programLayers.enable( 7 );
  11726. if ( parameters.premultipliedAlpha )
  11727. _programLayers.enable( 8 );
  11728. if ( parameters.shadowMapEnabled )
  11729. _programLayers.enable( 9 );
  11730. if ( parameters.physicallyCorrectLights )
  11731. _programLayers.enable( 10 );
  11732. if ( parameters.doubleSided )
  11733. _programLayers.enable( 11 );
  11734. if ( parameters.flipSided )
  11735. _programLayers.enable( 12 );
  11736. if ( parameters.useDepthPacking )
  11737. _programLayers.enable( 13 );
  11738. if ( parameters.dithering )
  11739. _programLayers.enable( 14 );
  11740. if ( parameters.specularIntensityMap )
  11741. _programLayers.enable( 15 );
  11742. if ( parameters.specularColorMap )
  11743. _programLayers.enable( 16 );
  11744. if ( parameters.transmission )
  11745. _programLayers.enable( 17 );
  11746. if ( parameters.transmissionMap )
  11747. _programLayers.enable( 18 );
  11748. if ( parameters.thicknessMap )
  11749. _programLayers.enable( 19 );
  11750. if ( parameters.sheen )
  11751. _programLayers.enable( 20 );
  11752. if ( parameters.sheenColorMap )
  11753. _programLayers.enable( 21 );
  11754. if ( parameters.sheenRoughnessMap )
  11755. _programLayers.enable( 22 );
  11756. if ( parameters.decodeVideoTexture )
  11757. _programLayers.enable( 23 );
  11758. if ( parameters.opaque )
  11759. _programLayers.enable( 24 );
  11760. array.push( _programLayers.mask );
  11761. }
  11762. function getUniforms( material ) {
  11763. const shaderID = shaderIDs[ material.type ];
  11764. let uniforms;
  11765. if ( shaderID ) {
  11766. const shader = ShaderLib[ shaderID ];
  11767. uniforms = UniformsUtils.clone( shader.uniforms );
  11768. } else {
  11769. uniforms = material.uniforms;
  11770. }
  11771. return uniforms;
  11772. }
  11773. function acquireProgram( parameters, cacheKey ) {
  11774. let program;
  11775. // Check if code has been already compiled
  11776. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  11777. const preexistingProgram = programs[ p ];
  11778. if ( preexistingProgram.cacheKey === cacheKey ) {
  11779. program = preexistingProgram;
  11780. ++ program.usedTimes;
  11781. break;
  11782. }
  11783. }
  11784. if ( program === undefined ) {
  11785. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  11786. programs.push( program );
  11787. }
  11788. return program;
  11789. }
  11790. function releaseProgram( program ) {
  11791. if ( -- program.usedTimes === 0 ) {
  11792. // Remove from unordered set
  11793. const i = programs.indexOf( program );
  11794. programs[ i ] = programs[ programs.length - 1 ];
  11795. programs.pop();
  11796. // Free WebGL resources
  11797. program.destroy();
  11798. }
  11799. }
  11800. function releaseShaderCache( material ) {
  11801. _customShaders.remove( material );
  11802. }
  11803. function dispose() {
  11804. _customShaders.dispose();
  11805. }
  11806. return {
  11807. getParameters: getParameters,
  11808. getProgramCacheKey: getProgramCacheKey,
  11809. getUniforms: getUniforms,
  11810. acquireProgram: acquireProgram,
  11811. releaseProgram: releaseProgram,
  11812. releaseShaderCache: releaseShaderCache,
  11813. // Exposed for resource monitoring & error feedback via renderer.info:
  11814. programs: programs,
  11815. dispose: dispose
  11816. };
  11817. }
  11818. function WebGLProperties() {
  11819. let properties = new WeakMap();
  11820. function get( object ) {
  11821. let map = properties.get( object );
  11822. if ( map === undefined ) {
  11823. map = {};
  11824. properties.set( object, map );
  11825. }
  11826. return map;
  11827. }
  11828. function remove( object ) {
  11829. properties.delete( object );
  11830. }
  11831. function update( object, key, value ) {
  11832. properties.get( object )[ key ] = value;
  11833. }
  11834. function dispose() {
  11835. properties = new WeakMap();
  11836. }
  11837. return {
  11838. get: get,
  11839. remove: remove,
  11840. update: update,
  11841. dispose: dispose
  11842. };
  11843. }
  11844. function painterSortStable( a, b ) {
  11845. if ( a.groupOrder !== b.groupOrder ) {
  11846. return a.groupOrder - b.groupOrder;
  11847. } else if ( a.renderOrder !== b.renderOrder ) {
  11848. return a.renderOrder - b.renderOrder;
  11849. } else if ( a.material.id !== b.material.id ) {
  11850. return a.material.id - b.material.id;
  11851. } else if ( a.z !== b.z ) {
  11852. return a.z - b.z;
  11853. } else {
  11854. return a.id - b.id;
  11855. }
  11856. }
  11857. function reversePainterSortStable( a, b ) {
  11858. if ( a.groupOrder !== b.groupOrder ) {
  11859. return a.groupOrder - b.groupOrder;
  11860. } else if ( a.renderOrder !== b.renderOrder ) {
  11861. return a.renderOrder - b.renderOrder;
  11862. } else if ( a.z !== b.z ) {
  11863. return b.z - a.z;
  11864. } else {
  11865. return a.id - b.id;
  11866. }
  11867. }
  11868. function WebGLRenderList() {
  11869. const renderItems = [];
  11870. let renderItemsIndex = 0;
  11871. const opaque = [];
  11872. const transmissive = [];
  11873. const transparent = [];
  11874. function init() {
  11875. renderItemsIndex = 0;
  11876. opaque.length = 0;
  11877. transmissive.length = 0;
  11878. transparent.length = 0;
  11879. }
  11880. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  11881. let renderItem = renderItems[ renderItemsIndex ];
  11882. if ( renderItem === undefined ) {
  11883. renderItem = {
  11884. id: object.id,
  11885. object: object,
  11886. geometry: geometry,
  11887. material: material,
  11888. groupOrder: groupOrder,
  11889. renderOrder: object.renderOrder,
  11890. z: z,
  11891. group: group
  11892. };
  11893. renderItems[ renderItemsIndex ] = renderItem;
  11894. } else {
  11895. renderItem.id = object.id;
  11896. renderItem.object = object;
  11897. renderItem.geometry = geometry;
  11898. renderItem.material = material;
  11899. renderItem.groupOrder = groupOrder;
  11900. renderItem.renderOrder = object.renderOrder;
  11901. renderItem.z = z;
  11902. renderItem.group = group;
  11903. }
  11904. renderItemsIndex ++;
  11905. return renderItem;
  11906. }
  11907. function push( object, geometry, material, groupOrder, z, group ) {
  11908. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  11909. if ( material.transmission > 0.0 ) {
  11910. transmissive.push( renderItem );
  11911. } else if ( material.transparent === true ) {
  11912. transparent.push( renderItem );
  11913. } else {
  11914. opaque.push( renderItem );
  11915. }
  11916. }
  11917. function unshift( object, geometry, material, groupOrder, z, group ) {
  11918. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  11919. if ( material.transmission > 0.0 ) {
  11920. transmissive.unshift( renderItem );
  11921. } else if ( material.transparent === true ) {
  11922. transparent.unshift( renderItem );
  11923. } else {
  11924. opaque.unshift( renderItem );
  11925. }
  11926. }
  11927. function sort( customOpaqueSort, customTransparentSort ) {
  11928. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  11929. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  11930. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  11931. }
  11932. function finish() {
  11933. // Clear references from inactive renderItems in the list
  11934. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  11935. const renderItem = renderItems[ i ];
  11936. if ( renderItem.id === null ) break;
  11937. renderItem.id = null;
  11938. renderItem.object = null;
  11939. renderItem.geometry = null;
  11940. renderItem.material = null;
  11941. renderItem.group = null;
  11942. }
  11943. }
  11944. return {
  11945. opaque: opaque,
  11946. transmissive: transmissive,
  11947. transparent: transparent,
  11948. init: init,
  11949. push: push,
  11950. unshift: unshift,
  11951. finish: finish,
  11952. sort: sort
  11953. };
  11954. }
  11955. function WebGLRenderLists() {
  11956. let lists = new WeakMap();
  11957. function get( scene, renderCallDepth ) {
  11958. let list;
  11959. if ( lists.has( scene ) === false ) {
  11960. list = new WebGLRenderList();
  11961. lists.set( scene, [ list ] );
  11962. } else {
  11963. if ( renderCallDepth >= lists.get( scene ).length ) {
  11964. list = new WebGLRenderList();
  11965. lists.get( scene ).push( list );
  11966. } else {
  11967. list = lists.get( scene )[ renderCallDepth ];
  11968. }
  11969. }
  11970. return list;
  11971. }
  11972. function dispose() {
  11973. lists = new WeakMap();
  11974. }
  11975. return {
  11976. get: get,
  11977. dispose: dispose
  11978. };
  11979. }
  11980. function UniformsCache() {
  11981. const lights = {};
  11982. return {
  11983. get: function ( light ) {
  11984. if ( lights[ light.id ] !== undefined ) {
  11985. return lights[ light.id ];
  11986. }
  11987. let uniforms;
  11988. switch ( light.type ) {
  11989. case 'DirectionalLight':
  11990. uniforms = {
  11991. direction: new Vector3(),
  11992. color: new Color()
  11993. };
  11994. break;
  11995. case 'SpotLight':
  11996. uniforms = {
  11997. position: new Vector3(),
  11998. direction: new Vector3(),
  11999. color: new Color(),
  12000. distance: 0,
  12001. coneCos: 0,
  12002. penumbraCos: 0,
  12003. decay: 0
  12004. };
  12005. break;
  12006. case 'PointLight':
  12007. uniforms = {
  12008. position: new Vector3(),
  12009. color: new Color(),
  12010. distance: 0,
  12011. decay: 0
  12012. };
  12013. break;
  12014. case 'HemisphereLight':
  12015. uniforms = {
  12016. direction: new Vector3(),
  12017. skyColor: new Color(),
  12018. groundColor: new Color()
  12019. };
  12020. break;
  12021. case 'RectAreaLight':
  12022. uniforms = {
  12023. color: new Color(),
  12024. position: new Vector3(),
  12025. halfWidth: new Vector3(),
  12026. halfHeight: new Vector3()
  12027. };
  12028. break;
  12029. }
  12030. lights[ light.id ] = uniforms;
  12031. return uniforms;
  12032. }
  12033. };
  12034. }
  12035. function ShadowUniformsCache() {
  12036. const lights = {};
  12037. return {
  12038. get: function ( light ) {
  12039. if ( lights[ light.id ] !== undefined ) {
  12040. return lights[ light.id ];
  12041. }
  12042. let uniforms;
  12043. switch ( light.type ) {
  12044. case 'DirectionalLight':
  12045. uniforms = {
  12046. shadowBias: 0,
  12047. shadowNormalBias: 0,
  12048. shadowRadius: 1,
  12049. shadowMapSize: new Vector2()
  12050. };
  12051. break;
  12052. case 'SpotLight':
  12053. uniforms = {
  12054. shadowBias: 0,
  12055. shadowNormalBias: 0,
  12056. shadowRadius: 1,
  12057. shadowMapSize: new Vector2()
  12058. };
  12059. break;
  12060. case 'PointLight':
  12061. uniforms = {
  12062. shadowBias: 0,
  12063. shadowNormalBias: 0,
  12064. shadowRadius: 1,
  12065. shadowMapSize: new Vector2(),
  12066. shadowCameraNear: 1,
  12067. shadowCameraFar: 1000
  12068. };
  12069. break;
  12070. // TODO (abelnation): set RectAreaLight shadow uniforms
  12071. }
  12072. lights[ light.id ] = uniforms;
  12073. return uniforms;
  12074. }
  12075. };
  12076. }
  12077. let nextVersion = 0;
  12078. function shadowCastingLightsFirst( lightA, lightB ) {
  12079. return ( lightB.castShadow ? 1 : 0 ) - ( lightA.castShadow ? 1 : 0 );
  12080. }
  12081. function WebGLLights( extensions, capabilities ) {
  12082. const cache = new UniformsCache();
  12083. const shadowCache = ShadowUniformsCache();
  12084. const state = {
  12085. version: 0,
  12086. hash: {
  12087. directionalLength: - 1,
  12088. pointLength: - 1,
  12089. spotLength: - 1,
  12090. rectAreaLength: - 1,
  12091. hemiLength: - 1,
  12092. numDirectionalShadows: - 1,
  12093. numPointShadows: - 1,
  12094. numSpotShadows: - 1
  12095. },
  12096. ambient: [ 0, 0, 0 ],
  12097. probe: [],
  12098. directional: [],
  12099. directionalShadow: [],
  12100. directionalShadowMap: [],
  12101. directionalShadowMatrix: [],
  12102. spot: [],
  12103. spotShadow: [],
  12104. spotShadowMap: [],
  12105. spotShadowMatrix: [],
  12106. rectArea: [],
  12107. rectAreaLTC1: null,
  12108. rectAreaLTC2: null,
  12109. point: [],
  12110. pointShadow: [],
  12111. pointShadowMap: [],
  12112. pointShadowMatrix: [],
  12113. hemi: []
  12114. };
  12115. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  12116. const vector3 = new Vector3();
  12117. const matrix4 = new Matrix4();
  12118. const matrix42 = new Matrix4();
  12119. function setup( lights, physicallyCorrectLights ) {
  12120. let r = 0, g = 0, b = 0;
  12121. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  12122. let directionalLength = 0;
  12123. let pointLength = 0;
  12124. let spotLength = 0;
  12125. let rectAreaLength = 0;
  12126. let hemiLength = 0;
  12127. let numDirectionalShadows = 0;
  12128. let numPointShadows = 0;
  12129. let numSpotShadows = 0;
  12130. lights.sort( shadowCastingLightsFirst );
  12131. // artist-friendly light intensity scaling factor
  12132. const scaleFactor = ( physicallyCorrectLights !== true ) ? Math.PI : 1;
  12133. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12134. const light = lights[ i ];
  12135. const color = light.color;
  12136. const intensity = light.intensity;
  12137. const distance = light.distance;
  12138. const shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  12139. if ( light.isAmbientLight ) {
  12140. r += color.r * intensity * scaleFactor;
  12141. g += color.g * intensity * scaleFactor;
  12142. b += color.b * intensity * scaleFactor;
  12143. } else if ( light.isLightProbe ) {
  12144. for ( let j = 0; j < 9; j ++ ) {
  12145. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  12146. }
  12147. } else if ( light.isDirectionalLight ) {
  12148. const uniforms = cache.get( light );
  12149. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12150. if ( light.castShadow ) {
  12151. const shadow = light.shadow;
  12152. const shadowUniforms = shadowCache.get( light );
  12153. shadowUniforms.shadowBias = shadow.bias;
  12154. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12155. shadowUniforms.shadowRadius = shadow.radius;
  12156. shadowUniforms.shadowMapSize = shadow.mapSize;
  12157. state.directionalShadow[ directionalLength ] = shadowUniforms;
  12158. state.directionalShadowMap[ directionalLength ] = shadowMap;
  12159. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  12160. numDirectionalShadows ++;
  12161. }
  12162. state.directional[ directionalLength ] = uniforms;
  12163. directionalLength ++;
  12164. } else if ( light.isSpotLight ) {
  12165. const uniforms = cache.get( light );
  12166. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12167. uniforms.color.copy( color ).multiplyScalar( intensity * scaleFactor );
  12168. uniforms.distance = distance;
  12169. uniforms.coneCos = Math.cos( light.angle );
  12170. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  12171. uniforms.decay = light.decay;
  12172. if ( light.castShadow ) {
  12173. const shadow = light.shadow;
  12174. const shadowUniforms = shadowCache.get( light );
  12175. shadowUniforms.shadowBias = shadow.bias;
  12176. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12177. shadowUniforms.shadowRadius = shadow.radius;
  12178. shadowUniforms.shadowMapSize = shadow.mapSize;
  12179. state.spotShadow[ spotLength ] = shadowUniforms;
  12180. state.spotShadowMap[ spotLength ] = shadowMap;
  12181. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  12182. numSpotShadows ++;
  12183. }
  12184. state.spot[ spotLength ] = uniforms;
  12185. spotLength ++;
  12186. } else if ( light.isRectAreaLight ) {
  12187. const uniforms = cache.get( light );
  12188. // (a) intensity is the total visible light emitted
  12189. //uniforms.color.copy( color ).multiplyScalar( intensity / ( light.width * light.height * Math.PI ) );
  12190. // (b) intensity is the brightness of the light
  12191. uniforms.color.copy( color ).multiplyScalar( intensity );
  12192. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12193. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12194. state.rectArea[ rectAreaLength ] = uniforms;
  12195. rectAreaLength ++;
  12196. } else if ( light.isPointLight ) {
  12197. const uniforms = cache.get( light );
  12198. uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );
  12199. uniforms.distance = light.distance;
  12200. uniforms.decay = light.decay;
  12201. if ( light.castShadow ) {
  12202. const shadow = light.shadow;
  12203. const shadowUniforms = shadowCache.get( light );
  12204. shadowUniforms.shadowBias = shadow.bias;
  12205. shadowUniforms.shadowNormalBias = shadow.normalBias;
  12206. shadowUniforms.shadowRadius = shadow.radius;
  12207. shadowUniforms.shadowMapSize = shadow.mapSize;
  12208. shadowUniforms.shadowCameraNear = shadow.camera.near;
  12209. shadowUniforms.shadowCameraFar = shadow.camera.far;
  12210. state.pointShadow[ pointLength ] = shadowUniforms;
  12211. state.pointShadowMap[ pointLength ] = shadowMap;
  12212. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  12213. numPointShadows ++;
  12214. }
  12215. state.point[ pointLength ] = uniforms;
  12216. pointLength ++;
  12217. } else if ( light.isHemisphereLight ) {
  12218. const uniforms = cache.get( light );
  12219. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity * scaleFactor );
  12220. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity * scaleFactor );
  12221. state.hemi[ hemiLength ] = uniforms;
  12222. hemiLength ++;
  12223. }
  12224. }
  12225. if ( rectAreaLength > 0 ) {
  12226. if ( capabilities.isWebGL2 ) {
  12227. // WebGL 2
  12228. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12229. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12230. } else {
  12231. // WebGL 1
  12232. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  12233. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  12234. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  12235. } else if ( extensions.has( 'OES_texture_half_float_linear' ) === true ) {
  12236. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  12237. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  12238. } else {
  12239. console.error( 'THREE.WebGLRenderer: Unable to use RectAreaLight. Missing WebGL extensions.' );
  12240. }
  12241. }
  12242. }
  12243. state.ambient[ 0 ] = r;
  12244. state.ambient[ 1 ] = g;
  12245. state.ambient[ 2 ] = b;
  12246. const hash = state.hash;
  12247. if ( hash.directionalLength !== directionalLength ||
  12248. hash.pointLength !== pointLength ||
  12249. hash.spotLength !== spotLength ||
  12250. hash.rectAreaLength !== rectAreaLength ||
  12251. hash.hemiLength !== hemiLength ||
  12252. hash.numDirectionalShadows !== numDirectionalShadows ||
  12253. hash.numPointShadows !== numPointShadows ||
  12254. hash.numSpotShadows !== numSpotShadows ) {
  12255. state.directional.length = directionalLength;
  12256. state.spot.length = spotLength;
  12257. state.rectArea.length = rectAreaLength;
  12258. state.point.length = pointLength;
  12259. state.hemi.length = hemiLength;
  12260. state.directionalShadow.length = numDirectionalShadows;
  12261. state.directionalShadowMap.length = numDirectionalShadows;
  12262. state.pointShadow.length = numPointShadows;
  12263. state.pointShadowMap.length = numPointShadows;
  12264. state.spotShadow.length = numSpotShadows;
  12265. state.spotShadowMap.length = numSpotShadows;
  12266. state.directionalShadowMatrix.length = numDirectionalShadows;
  12267. state.pointShadowMatrix.length = numPointShadows;
  12268. state.spotShadowMatrix.length = numSpotShadows;
  12269. hash.directionalLength = directionalLength;
  12270. hash.pointLength = pointLength;
  12271. hash.spotLength = spotLength;
  12272. hash.rectAreaLength = rectAreaLength;
  12273. hash.hemiLength = hemiLength;
  12274. hash.numDirectionalShadows = numDirectionalShadows;
  12275. hash.numPointShadows = numPointShadows;
  12276. hash.numSpotShadows = numSpotShadows;
  12277. state.version = nextVersion ++;
  12278. }
  12279. }
  12280. function setupView( lights, camera ) {
  12281. let directionalLength = 0;
  12282. let pointLength = 0;
  12283. let spotLength = 0;
  12284. let rectAreaLength = 0;
  12285. let hemiLength = 0;
  12286. const viewMatrix = camera.matrixWorldInverse;
  12287. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  12288. const light = lights[ i ];
  12289. if ( light.isDirectionalLight ) {
  12290. const uniforms = state.directional[ directionalLength ];
  12291. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12292. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12293. uniforms.direction.sub( vector3 );
  12294. uniforms.direction.transformDirection( viewMatrix );
  12295. directionalLength ++;
  12296. } else if ( light.isSpotLight ) {
  12297. const uniforms = state.spot[ spotLength ];
  12298. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12299. uniforms.position.applyMatrix4( viewMatrix );
  12300. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12301. vector3.setFromMatrixPosition( light.target.matrixWorld );
  12302. uniforms.direction.sub( vector3 );
  12303. uniforms.direction.transformDirection( viewMatrix );
  12304. spotLength ++;
  12305. } else if ( light.isRectAreaLight ) {
  12306. const uniforms = state.rectArea[ rectAreaLength ];
  12307. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12308. uniforms.position.applyMatrix4( viewMatrix );
  12309. // extract local rotation of light to derive width/height half vectors
  12310. matrix42.identity();
  12311. matrix4.copy( light.matrixWorld );
  12312. matrix4.premultiply( viewMatrix );
  12313. matrix42.extractRotation( matrix4 );
  12314. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  12315. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  12316. uniforms.halfWidth.applyMatrix4( matrix42 );
  12317. uniforms.halfHeight.applyMatrix4( matrix42 );
  12318. rectAreaLength ++;
  12319. } else if ( light.isPointLight ) {
  12320. const uniforms = state.point[ pointLength ];
  12321. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  12322. uniforms.position.applyMatrix4( viewMatrix );
  12323. pointLength ++;
  12324. } else if ( light.isHemisphereLight ) {
  12325. const uniforms = state.hemi[ hemiLength ];
  12326. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  12327. uniforms.direction.transformDirection( viewMatrix );
  12328. hemiLength ++;
  12329. }
  12330. }
  12331. }
  12332. return {
  12333. setup: setup,
  12334. setupView: setupView,
  12335. state: state
  12336. };
  12337. }
  12338. function WebGLRenderState( extensions, capabilities ) {
  12339. const lights = new WebGLLights( extensions, capabilities );
  12340. const lightsArray = [];
  12341. const shadowsArray = [];
  12342. function init() {
  12343. lightsArray.length = 0;
  12344. shadowsArray.length = 0;
  12345. }
  12346. function pushLight( light ) {
  12347. lightsArray.push( light );
  12348. }
  12349. function pushShadow( shadowLight ) {
  12350. shadowsArray.push( shadowLight );
  12351. }
  12352. function setupLights( physicallyCorrectLights ) {
  12353. lights.setup( lightsArray, physicallyCorrectLights );
  12354. }
  12355. function setupLightsView( camera ) {
  12356. lights.setupView( lightsArray, camera );
  12357. }
  12358. const state = {
  12359. lightsArray: lightsArray,
  12360. shadowsArray: shadowsArray,
  12361. lights: lights
  12362. };
  12363. return {
  12364. init: init,
  12365. state: state,
  12366. setupLights: setupLights,
  12367. setupLightsView: setupLightsView,
  12368. pushLight: pushLight,
  12369. pushShadow: pushShadow
  12370. };
  12371. }
  12372. function WebGLRenderStates( extensions, capabilities ) {
  12373. let renderStates = new WeakMap();
  12374. function get( scene, renderCallDepth = 0 ) {
  12375. let renderState;
  12376. if ( renderStates.has( scene ) === false ) {
  12377. renderState = new WebGLRenderState( extensions, capabilities );
  12378. renderStates.set( scene, [ renderState ] );
  12379. } else {
  12380. if ( renderCallDepth >= renderStates.get( scene ).length ) {
  12381. renderState = new WebGLRenderState( extensions, capabilities );
  12382. renderStates.get( scene ).push( renderState );
  12383. } else {
  12384. renderState = renderStates.get( scene )[ renderCallDepth ];
  12385. }
  12386. }
  12387. return renderState;
  12388. }
  12389. function dispose() {
  12390. renderStates = new WeakMap();
  12391. }
  12392. return {
  12393. get: get,
  12394. dispose: dispose
  12395. };
  12396. }
  12397. class MeshDepthMaterial extends Material {
  12398. constructor( parameters ) {
  12399. super();
  12400. this.isMeshDepthMaterial = true;
  12401. this.type = 'MeshDepthMaterial';
  12402. this.depthPacking = BasicDepthPacking;
  12403. this.map = null;
  12404. this.alphaMap = null;
  12405. this.displacementMap = null;
  12406. this.displacementScale = 1;
  12407. this.displacementBias = 0;
  12408. this.wireframe = false;
  12409. this.wireframeLinewidth = 1;
  12410. this.setValues( parameters );
  12411. }
  12412. copy( source ) {
  12413. super.copy( source );
  12414. this.depthPacking = source.depthPacking;
  12415. this.map = source.map;
  12416. this.alphaMap = source.alphaMap;
  12417. this.displacementMap = source.displacementMap;
  12418. this.displacementScale = source.displacementScale;
  12419. this.displacementBias = source.displacementBias;
  12420. this.wireframe = source.wireframe;
  12421. this.wireframeLinewidth = source.wireframeLinewidth;
  12422. return this;
  12423. }
  12424. }
  12425. class MeshDistanceMaterial extends Material {
  12426. constructor( parameters ) {
  12427. super();
  12428. this.isMeshDistanceMaterial = true;
  12429. this.type = 'MeshDistanceMaterial';
  12430. this.referencePosition = new Vector3();
  12431. this.nearDistance = 1;
  12432. this.farDistance = 1000;
  12433. this.map = null;
  12434. this.alphaMap = null;
  12435. this.displacementMap = null;
  12436. this.displacementScale = 1;
  12437. this.displacementBias = 0;
  12438. this.setValues( parameters );
  12439. }
  12440. copy( source ) {
  12441. super.copy( source );
  12442. this.referencePosition.copy( source.referencePosition );
  12443. this.nearDistance = source.nearDistance;
  12444. this.farDistance = source.farDistance;
  12445. this.map = source.map;
  12446. this.alphaMap = source.alphaMap;
  12447. this.displacementMap = source.displacementMap;
  12448. this.displacementScale = source.displacementScale;
  12449. this.displacementBias = source.displacementBias;
  12450. return this;
  12451. }
  12452. }
  12453. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  12454. 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}";
  12455. function WebGLShadowMap( _renderer, _objects, _capabilities ) {
  12456. let _frustum = new Frustum();
  12457. const _shadowMapSize = new Vector2(),
  12458. _viewportSize = new Vector2(),
  12459. _viewport = new Vector4(),
  12460. _depthMaterial = new MeshDepthMaterial( { depthPacking: RGBADepthPacking } ),
  12461. _distanceMaterial = new MeshDistanceMaterial(),
  12462. _materialCache = {},
  12463. _maxTextureSize = _capabilities.maxTextureSize;
  12464. const shadowSide = { 0: BackSide, 1: FrontSide, 2: DoubleSide };
  12465. const shadowMaterialVertical = new ShaderMaterial( {
  12466. defines: {
  12467. VSM_SAMPLES: 8
  12468. },
  12469. uniforms: {
  12470. shadow_pass: { value: null },
  12471. resolution: { value: new Vector2() },
  12472. radius: { value: 4.0 }
  12473. },
  12474. vertexShader: vertex,
  12475. fragmentShader: fragment
  12476. } );
  12477. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  12478. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  12479. const fullScreenTri = new BufferGeometry();
  12480. fullScreenTri.setAttribute(
  12481. 'position',
  12482. new BufferAttribute(
  12483. new Float32Array( [ - 1, - 1, 0.5, 3, - 1, 0.5, - 1, 3, 0.5 ] ),
  12484. 3
  12485. )
  12486. );
  12487. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  12488. const scope = this;
  12489. this.enabled = false;
  12490. this.autoUpdate = true;
  12491. this.needsUpdate = false;
  12492. this.type = PCFShadowMap;
  12493. this.render = function ( lights, scene, camera ) {
  12494. if ( scope.enabled === false ) return;
  12495. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  12496. if ( lights.length === 0 ) return;
  12497. const currentRenderTarget = _renderer.getRenderTarget();
  12498. const activeCubeFace = _renderer.getActiveCubeFace();
  12499. const activeMipmapLevel = _renderer.getActiveMipmapLevel();
  12500. const _state = _renderer.state;
  12501. // Set GL state for depth map.
  12502. _state.setBlending( NoBlending );
  12503. _state.buffers.color.setClear( 1, 1, 1, 1 );
  12504. _state.buffers.depth.setTest( true );
  12505. _state.setScissorTest( false );
  12506. // render depth map
  12507. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  12508. const light = lights[ i ];
  12509. const shadow = light.shadow;
  12510. if ( shadow === undefined ) {
  12511. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  12512. continue;
  12513. }
  12514. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  12515. _shadowMapSize.copy( shadow.mapSize );
  12516. const shadowFrameExtents = shadow.getFrameExtents();
  12517. _shadowMapSize.multiply( shadowFrameExtents );
  12518. _viewportSize.copy( shadow.mapSize );
  12519. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  12520. if ( _shadowMapSize.x > _maxTextureSize ) {
  12521. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  12522. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  12523. shadow.mapSize.x = _viewportSize.x;
  12524. }
  12525. if ( _shadowMapSize.y > _maxTextureSize ) {
  12526. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  12527. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  12528. shadow.mapSize.y = _viewportSize.y;
  12529. }
  12530. }
  12531. if ( shadow.map === null ) {
  12532. const pars = ( this.type !== VSMShadowMap ) ? { minFilter: NearestFilter, magFilter: NearestFilter } : {};
  12533. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  12534. shadow.map.texture.name = light.name + '.shadowMap';
  12535. shadow.camera.updateProjectionMatrix();
  12536. }
  12537. _renderer.setRenderTarget( shadow.map );
  12538. _renderer.clear();
  12539. const viewportCount = shadow.getViewportCount();
  12540. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  12541. const viewport = shadow.getViewport( vp );
  12542. _viewport.set(
  12543. _viewportSize.x * viewport.x,
  12544. _viewportSize.y * viewport.y,
  12545. _viewportSize.x * viewport.z,
  12546. _viewportSize.y * viewport.w
  12547. );
  12548. _state.viewport( _viewport );
  12549. shadow.updateMatrices( light, vp );
  12550. _frustum = shadow.getFrustum();
  12551. renderObject( scene, camera, shadow.camera, light, this.type );
  12552. }
  12553. // do blur pass for VSM
  12554. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  12555. VSMPass( shadow, camera );
  12556. }
  12557. shadow.needsUpdate = false;
  12558. }
  12559. scope.needsUpdate = false;
  12560. _renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  12561. };
  12562. function VSMPass( shadow, camera ) {
  12563. const geometry = _objects.update( fullScreenMesh );
  12564. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  12565. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  12566. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  12567. shadowMaterialVertical.needsUpdate = true;
  12568. shadowMaterialHorizontal.needsUpdate = true;
  12569. }
  12570. if ( shadow.mapPass === null ) {
  12571. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  12572. }
  12573. // vertical pass
  12574. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  12575. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  12576. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  12577. _renderer.setRenderTarget( shadow.mapPass );
  12578. _renderer.clear();
  12579. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  12580. // horizontal pass
  12581. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  12582. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  12583. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  12584. _renderer.setRenderTarget( shadow.map );
  12585. _renderer.clear();
  12586. _renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  12587. }
  12588. function getDepthMaterial( object, material, light, shadowCameraNear, shadowCameraFar, type ) {
  12589. let result = null;
  12590. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  12591. if ( customMaterial !== undefined ) {
  12592. result = customMaterial;
  12593. } else {
  12594. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  12595. }
  12596. if ( ( _renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  12597. ( material.displacementMap && material.displacementScale !== 0 ) ||
  12598. ( material.alphaMap && material.alphaTest > 0 ) ) {
  12599. // in this case we need a unique material instance reflecting the
  12600. // appropriate state
  12601. const keyA = result.uuid, keyB = material.uuid;
  12602. let materialsForVariant = _materialCache[ keyA ];
  12603. if ( materialsForVariant === undefined ) {
  12604. materialsForVariant = {};
  12605. _materialCache[ keyA ] = materialsForVariant;
  12606. }
  12607. let cachedMaterial = materialsForVariant[ keyB ];
  12608. if ( cachedMaterial === undefined ) {
  12609. cachedMaterial = result.clone();
  12610. materialsForVariant[ keyB ] = cachedMaterial;
  12611. }
  12612. result = cachedMaterial;
  12613. }
  12614. result.visible = material.visible;
  12615. result.wireframe = material.wireframe;
  12616. if ( type === VSMShadowMap ) {
  12617. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  12618. } else {
  12619. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  12620. }
  12621. result.alphaMap = material.alphaMap;
  12622. result.alphaTest = material.alphaTest;
  12623. result.clipShadows = material.clipShadows;
  12624. result.clippingPlanes = material.clippingPlanes;
  12625. result.clipIntersection = material.clipIntersection;
  12626. result.displacementMap = material.displacementMap;
  12627. result.displacementScale = material.displacementScale;
  12628. result.displacementBias = material.displacementBias;
  12629. result.wireframeLinewidth = material.wireframeLinewidth;
  12630. result.linewidth = material.linewidth;
  12631. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  12632. result.referencePosition.setFromMatrixPosition( light.matrixWorld );
  12633. result.nearDistance = shadowCameraNear;
  12634. result.farDistance = shadowCameraFar;
  12635. }
  12636. return result;
  12637. }
  12638. function renderObject( object, camera, shadowCamera, light, type ) {
  12639. if ( object.visible === false ) return;
  12640. const visible = object.layers.test( camera.layers );
  12641. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  12642. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  12643. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  12644. const geometry = _objects.update( object );
  12645. const material = object.material;
  12646. if ( Array.isArray( material ) ) {
  12647. const groups = geometry.groups;
  12648. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  12649. const group = groups[ k ];
  12650. const groupMaterial = material[ group.materialIndex ];
  12651. if ( groupMaterial && groupMaterial.visible ) {
  12652. const depthMaterial = getDepthMaterial( object, groupMaterial, light, shadowCamera.near, shadowCamera.far, type );
  12653. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  12654. }
  12655. }
  12656. } else if ( material.visible ) {
  12657. const depthMaterial = getDepthMaterial( object, material, light, shadowCamera.near, shadowCamera.far, type );
  12658. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  12659. }
  12660. }
  12661. }
  12662. const children = object.children;
  12663. for ( let i = 0, l = children.length; i < l; i ++ ) {
  12664. renderObject( children[ i ], camera, shadowCamera, light, type );
  12665. }
  12666. }
  12667. }
  12668. function WebGLState( gl, extensions, capabilities ) {
  12669. const isWebGL2 = capabilities.isWebGL2;
  12670. function ColorBuffer() {
  12671. let locked = false;
  12672. const color = new Vector4();
  12673. let currentColorMask = null;
  12674. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  12675. return {
  12676. setMask: function ( colorMask ) {
  12677. if ( currentColorMask !== colorMask && ! locked ) {
  12678. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  12679. currentColorMask = colorMask;
  12680. }
  12681. },
  12682. setLocked: function ( lock ) {
  12683. locked = lock;
  12684. },
  12685. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  12686. if ( premultipliedAlpha === true ) {
  12687. r *= a; g *= a; b *= a;
  12688. }
  12689. color.set( r, g, b, a );
  12690. if ( currentColorClear.equals( color ) === false ) {
  12691. gl.clearColor( r, g, b, a );
  12692. currentColorClear.copy( color );
  12693. }
  12694. },
  12695. reset: function () {
  12696. locked = false;
  12697. currentColorMask = null;
  12698. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  12699. }
  12700. };
  12701. }
  12702. function DepthBuffer() {
  12703. let locked = false;
  12704. let currentDepthMask = null;
  12705. let currentDepthFunc = null;
  12706. let currentDepthClear = null;
  12707. return {
  12708. setTest: function ( depthTest ) {
  12709. if ( depthTest ) {
  12710. enable( 2929 );
  12711. } else {
  12712. disable( 2929 );
  12713. }
  12714. },
  12715. setMask: function ( depthMask ) {
  12716. if ( currentDepthMask !== depthMask && ! locked ) {
  12717. gl.depthMask( depthMask );
  12718. currentDepthMask = depthMask;
  12719. }
  12720. },
  12721. setFunc: function ( depthFunc ) {
  12722. if ( currentDepthFunc !== depthFunc ) {
  12723. if ( depthFunc ) {
  12724. switch ( depthFunc ) {
  12725. case NeverDepth:
  12726. gl.depthFunc( 512 );
  12727. break;
  12728. case AlwaysDepth:
  12729. gl.depthFunc( 519 );
  12730. break;
  12731. case LessDepth:
  12732. gl.depthFunc( 513 );
  12733. break;
  12734. case LessEqualDepth:
  12735. gl.depthFunc( 515 );
  12736. break;
  12737. case EqualDepth:
  12738. gl.depthFunc( 514 );
  12739. break;
  12740. case GreaterEqualDepth:
  12741. gl.depthFunc( 518 );
  12742. break;
  12743. case GreaterDepth:
  12744. gl.depthFunc( 516 );
  12745. break;
  12746. case NotEqualDepth:
  12747. gl.depthFunc( 517 );
  12748. break;
  12749. default:
  12750. gl.depthFunc( 515 );
  12751. }
  12752. } else {
  12753. gl.depthFunc( 515 );
  12754. }
  12755. currentDepthFunc = depthFunc;
  12756. }
  12757. },
  12758. setLocked: function ( lock ) {
  12759. locked = lock;
  12760. },
  12761. setClear: function ( depth ) {
  12762. if ( currentDepthClear !== depth ) {
  12763. gl.clearDepth( depth );
  12764. currentDepthClear = depth;
  12765. }
  12766. },
  12767. reset: function () {
  12768. locked = false;
  12769. currentDepthMask = null;
  12770. currentDepthFunc = null;
  12771. currentDepthClear = null;
  12772. }
  12773. };
  12774. }
  12775. function StencilBuffer() {
  12776. let locked = false;
  12777. let currentStencilMask = null;
  12778. let currentStencilFunc = null;
  12779. let currentStencilRef = null;
  12780. let currentStencilFuncMask = null;
  12781. let currentStencilFail = null;
  12782. let currentStencilZFail = null;
  12783. let currentStencilZPass = null;
  12784. let currentStencilClear = null;
  12785. return {
  12786. setTest: function ( stencilTest ) {
  12787. if ( ! locked ) {
  12788. if ( stencilTest ) {
  12789. enable( 2960 );
  12790. } else {
  12791. disable( 2960 );
  12792. }
  12793. }
  12794. },
  12795. setMask: function ( stencilMask ) {
  12796. if ( currentStencilMask !== stencilMask && ! locked ) {
  12797. gl.stencilMask( stencilMask );
  12798. currentStencilMask = stencilMask;
  12799. }
  12800. },
  12801. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  12802. if ( currentStencilFunc !== stencilFunc ||
  12803. currentStencilRef !== stencilRef ||
  12804. currentStencilFuncMask !== stencilMask ) {
  12805. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  12806. currentStencilFunc = stencilFunc;
  12807. currentStencilRef = stencilRef;
  12808. currentStencilFuncMask = stencilMask;
  12809. }
  12810. },
  12811. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  12812. if ( currentStencilFail !== stencilFail ||
  12813. currentStencilZFail !== stencilZFail ||
  12814. currentStencilZPass !== stencilZPass ) {
  12815. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  12816. currentStencilFail = stencilFail;
  12817. currentStencilZFail = stencilZFail;
  12818. currentStencilZPass = stencilZPass;
  12819. }
  12820. },
  12821. setLocked: function ( lock ) {
  12822. locked = lock;
  12823. },
  12824. setClear: function ( stencil ) {
  12825. if ( currentStencilClear !== stencil ) {
  12826. gl.clearStencil( stencil );
  12827. currentStencilClear = stencil;
  12828. }
  12829. },
  12830. reset: function () {
  12831. locked = false;
  12832. currentStencilMask = null;
  12833. currentStencilFunc = null;
  12834. currentStencilRef = null;
  12835. currentStencilFuncMask = null;
  12836. currentStencilFail = null;
  12837. currentStencilZFail = null;
  12838. currentStencilZPass = null;
  12839. currentStencilClear = null;
  12840. }
  12841. };
  12842. }
  12843. //
  12844. const colorBuffer = new ColorBuffer();
  12845. const depthBuffer = new DepthBuffer();
  12846. const stencilBuffer = new StencilBuffer();
  12847. const uboBindings = new WeakMap();
  12848. const uboProgamMap = new WeakMap();
  12849. let enabledCapabilities = {};
  12850. let currentBoundFramebuffers = {};
  12851. let currentDrawbuffers = new WeakMap();
  12852. let defaultDrawbuffers = [];
  12853. let currentProgram = null;
  12854. let currentBlendingEnabled = false;
  12855. let currentBlending = null;
  12856. let currentBlendEquation = null;
  12857. let currentBlendSrc = null;
  12858. let currentBlendDst = null;
  12859. let currentBlendEquationAlpha = null;
  12860. let currentBlendSrcAlpha = null;
  12861. let currentBlendDstAlpha = null;
  12862. let currentPremultipledAlpha = false;
  12863. let currentFlipSided = null;
  12864. let currentCullFace = null;
  12865. let currentLineWidth = null;
  12866. let currentPolygonOffsetFactor = null;
  12867. let currentPolygonOffsetUnits = null;
  12868. const maxTextures = gl.getParameter( 35661 );
  12869. let lineWidthAvailable = false;
  12870. let version = 0;
  12871. const glVersion = gl.getParameter( 7938 );
  12872. if ( glVersion.indexOf( 'WebGL' ) !== - 1 ) {
  12873. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  12874. lineWidthAvailable = ( version >= 1.0 );
  12875. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== - 1 ) {
  12876. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  12877. lineWidthAvailable = ( version >= 2.0 );
  12878. }
  12879. let currentTextureSlot = null;
  12880. let currentBoundTextures = {};
  12881. const scissorParam = gl.getParameter( 3088 );
  12882. const viewportParam = gl.getParameter( 2978 );
  12883. const currentScissor = new Vector4().fromArray( scissorParam );
  12884. const currentViewport = new Vector4().fromArray( viewportParam );
  12885. function createTexture( type, target, count ) {
  12886. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  12887. const texture = gl.createTexture();
  12888. gl.bindTexture( type, texture );
  12889. gl.texParameteri( type, 10241, 9728 );
  12890. gl.texParameteri( type, 10240, 9728 );
  12891. for ( let i = 0; i < count; i ++ ) {
  12892. gl.texImage2D( target + i, 0, 6408, 1, 1, 0, 6408, 5121, data );
  12893. }
  12894. return texture;
  12895. }
  12896. const emptyTextures = {};
  12897. emptyTextures[ 3553 ] = createTexture( 3553, 3553, 1 );
  12898. emptyTextures[ 34067 ] = createTexture( 34067, 34069, 6 );
  12899. // init
  12900. colorBuffer.setClear( 0, 0, 0, 1 );
  12901. depthBuffer.setClear( 1 );
  12902. stencilBuffer.setClear( 0 );
  12903. enable( 2929 );
  12904. depthBuffer.setFunc( LessEqualDepth );
  12905. setFlipSided( false );
  12906. setCullFace( CullFaceBack );
  12907. enable( 2884 );
  12908. setBlending( NoBlending );
  12909. //
  12910. function enable( id ) {
  12911. if ( enabledCapabilities[ id ] !== true ) {
  12912. gl.enable( id );
  12913. enabledCapabilities[ id ] = true;
  12914. }
  12915. }
  12916. function disable( id ) {
  12917. if ( enabledCapabilities[ id ] !== false ) {
  12918. gl.disable( id );
  12919. enabledCapabilities[ id ] = false;
  12920. }
  12921. }
  12922. function bindFramebuffer( target, framebuffer ) {
  12923. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  12924. gl.bindFramebuffer( target, framebuffer );
  12925. currentBoundFramebuffers[ target ] = framebuffer;
  12926. if ( isWebGL2 ) {
  12927. // 36009 is equivalent to 36160
  12928. if ( target === 36009 ) {
  12929. currentBoundFramebuffers[ 36160 ] = framebuffer;
  12930. }
  12931. if ( target === 36160 ) {
  12932. currentBoundFramebuffers[ 36009 ] = framebuffer;
  12933. }
  12934. }
  12935. return true;
  12936. }
  12937. return false;
  12938. }
  12939. function drawBuffers( renderTarget, framebuffer ) {
  12940. let drawBuffers = defaultDrawbuffers;
  12941. let needsUpdate = false;
  12942. if ( renderTarget ) {
  12943. drawBuffers = currentDrawbuffers.get( framebuffer );
  12944. if ( drawBuffers === undefined ) {
  12945. drawBuffers = [];
  12946. currentDrawbuffers.set( framebuffer, drawBuffers );
  12947. }
  12948. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  12949. const textures = renderTarget.texture;
  12950. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== 36064 ) {
  12951. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  12952. drawBuffers[ i ] = 36064 + i;
  12953. }
  12954. drawBuffers.length = textures.length;
  12955. needsUpdate = true;
  12956. }
  12957. } else {
  12958. if ( drawBuffers[ 0 ] !== 36064 ) {
  12959. drawBuffers[ 0 ] = 36064;
  12960. needsUpdate = true;
  12961. }
  12962. }
  12963. } else {
  12964. if ( drawBuffers[ 0 ] !== 1029 ) {
  12965. drawBuffers[ 0 ] = 1029;
  12966. needsUpdate = true;
  12967. }
  12968. }
  12969. if ( needsUpdate ) {
  12970. if ( capabilities.isWebGL2 ) {
  12971. gl.drawBuffers( drawBuffers );
  12972. } else {
  12973. extensions.get( 'WEBGL_draw_buffers' ).drawBuffersWEBGL( drawBuffers );
  12974. }
  12975. }
  12976. }
  12977. function useProgram( program ) {
  12978. if ( currentProgram !== program ) {
  12979. gl.useProgram( program );
  12980. currentProgram = program;
  12981. return true;
  12982. }
  12983. return false;
  12984. }
  12985. const equationToGL = {
  12986. [ AddEquation ]: 32774,
  12987. [ SubtractEquation ]: 32778,
  12988. [ ReverseSubtractEquation ]: 32779
  12989. };
  12990. if ( isWebGL2 ) {
  12991. equationToGL[ MinEquation ] = 32775;
  12992. equationToGL[ MaxEquation ] = 32776;
  12993. } else {
  12994. const extension = extensions.get( 'EXT_blend_minmax' );
  12995. if ( extension !== null ) {
  12996. equationToGL[ MinEquation ] = extension.MIN_EXT;
  12997. equationToGL[ MaxEquation ] = extension.MAX_EXT;
  12998. }
  12999. }
  13000. const factorToGL = {
  13001. [ ZeroFactor ]: 0,
  13002. [ OneFactor ]: 1,
  13003. [ SrcColorFactor ]: 768,
  13004. [ SrcAlphaFactor ]: 770,
  13005. [ SrcAlphaSaturateFactor ]: 776,
  13006. [ DstColorFactor ]: 774,
  13007. [ DstAlphaFactor ]: 772,
  13008. [ OneMinusSrcColorFactor ]: 769,
  13009. [ OneMinusSrcAlphaFactor ]: 771,
  13010. [ OneMinusDstColorFactor ]: 775,
  13011. [ OneMinusDstAlphaFactor ]: 773
  13012. };
  13013. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  13014. if ( blending === NoBlending ) {
  13015. if ( currentBlendingEnabled === true ) {
  13016. disable( 3042 );
  13017. currentBlendingEnabled = false;
  13018. }
  13019. return;
  13020. }
  13021. if ( currentBlendingEnabled === false ) {
  13022. enable( 3042 );
  13023. currentBlendingEnabled = true;
  13024. }
  13025. if ( blending !== CustomBlending ) {
  13026. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  13027. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  13028. gl.blendEquation( 32774 );
  13029. currentBlendEquation = AddEquation;
  13030. currentBlendEquationAlpha = AddEquation;
  13031. }
  13032. if ( premultipliedAlpha ) {
  13033. switch ( blending ) {
  13034. case NormalBlending:
  13035. gl.blendFuncSeparate( 1, 771, 1, 771 );
  13036. break;
  13037. case AdditiveBlending:
  13038. gl.blendFunc( 1, 1 );
  13039. break;
  13040. case SubtractiveBlending:
  13041. gl.blendFuncSeparate( 0, 769, 0, 1 );
  13042. break;
  13043. case MultiplyBlending:
  13044. gl.blendFuncSeparate( 0, 768, 0, 770 );
  13045. break;
  13046. default:
  13047. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13048. break;
  13049. }
  13050. } else {
  13051. switch ( blending ) {
  13052. case NormalBlending:
  13053. gl.blendFuncSeparate( 770, 771, 1, 771 );
  13054. break;
  13055. case AdditiveBlending:
  13056. gl.blendFunc( 770, 1 );
  13057. break;
  13058. case SubtractiveBlending:
  13059. gl.blendFuncSeparate( 0, 769, 0, 1 );
  13060. break;
  13061. case MultiplyBlending:
  13062. gl.blendFunc( 0, 768 );
  13063. break;
  13064. default:
  13065. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  13066. break;
  13067. }
  13068. }
  13069. currentBlendSrc = null;
  13070. currentBlendDst = null;
  13071. currentBlendSrcAlpha = null;
  13072. currentBlendDstAlpha = null;
  13073. currentBlending = blending;
  13074. currentPremultipledAlpha = premultipliedAlpha;
  13075. }
  13076. return;
  13077. }
  13078. // custom blending
  13079. blendEquationAlpha = blendEquationAlpha || blendEquation;
  13080. blendSrcAlpha = blendSrcAlpha || blendSrc;
  13081. blendDstAlpha = blendDstAlpha || blendDst;
  13082. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  13083. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  13084. currentBlendEquation = blendEquation;
  13085. currentBlendEquationAlpha = blendEquationAlpha;
  13086. }
  13087. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  13088. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  13089. currentBlendSrc = blendSrc;
  13090. currentBlendDst = blendDst;
  13091. currentBlendSrcAlpha = blendSrcAlpha;
  13092. currentBlendDstAlpha = blendDstAlpha;
  13093. }
  13094. currentBlending = blending;
  13095. currentPremultipledAlpha = null;
  13096. }
  13097. function setMaterial( material, frontFaceCW ) {
  13098. material.side === DoubleSide
  13099. ? disable( 2884 )
  13100. : enable( 2884 );
  13101. let flipSided = ( material.side === BackSide );
  13102. if ( frontFaceCW ) flipSided = ! flipSided;
  13103. setFlipSided( flipSided );
  13104. ( material.blending === NormalBlending && material.transparent === false )
  13105. ? setBlending( NoBlending )
  13106. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  13107. depthBuffer.setFunc( material.depthFunc );
  13108. depthBuffer.setTest( material.depthTest );
  13109. depthBuffer.setMask( material.depthWrite );
  13110. colorBuffer.setMask( material.colorWrite );
  13111. const stencilWrite = material.stencilWrite;
  13112. stencilBuffer.setTest( stencilWrite );
  13113. if ( stencilWrite ) {
  13114. stencilBuffer.setMask( material.stencilWriteMask );
  13115. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  13116. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  13117. }
  13118. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13119. material.alphaToCoverage === true
  13120. ? enable( 32926 )
  13121. : disable( 32926 );
  13122. }
  13123. //
  13124. function setFlipSided( flipSided ) {
  13125. if ( currentFlipSided !== flipSided ) {
  13126. if ( flipSided ) {
  13127. gl.frontFace( 2304 );
  13128. } else {
  13129. gl.frontFace( 2305 );
  13130. }
  13131. currentFlipSided = flipSided;
  13132. }
  13133. }
  13134. function setCullFace( cullFace ) {
  13135. if ( cullFace !== CullFaceNone ) {
  13136. enable( 2884 );
  13137. if ( cullFace !== currentCullFace ) {
  13138. if ( cullFace === CullFaceBack ) {
  13139. gl.cullFace( 1029 );
  13140. } else if ( cullFace === CullFaceFront ) {
  13141. gl.cullFace( 1028 );
  13142. } else {
  13143. gl.cullFace( 1032 );
  13144. }
  13145. }
  13146. } else {
  13147. disable( 2884 );
  13148. }
  13149. currentCullFace = cullFace;
  13150. }
  13151. function setLineWidth( width ) {
  13152. if ( width !== currentLineWidth ) {
  13153. if ( lineWidthAvailable ) gl.lineWidth( width );
  13154. currentLineWidth = width;
  13155. }
  13156. }
  13157. function setPolygonOffset( polygonOffset, factor, units ) {
  13158. if ( polygonOffset ) {
  13159. enable( 32823 );
  13160. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  13161. gl.polygonOffset( factor, units );
  13162. currentPolygonOffsetFactor = factor;
  13163. currentPolygonOffsetUnits = units;
  13164. }
  13165. } else {
  13166. disable( 32823 );
  13167. }
  13168. }
  13169. function setScissorTest( scissorTest ) {
  13170. if ( scissorTest ) {
  13171. enable( 3089 );
  13172. } else {
  13173. disable( 3089 );
  13174. }
  13175. }
  13176. // texture
  13177. function activeTexture( webglSlot ) {
  13178. if ( webglSlot === undefined ) webglSlot = 33984 + maxTextures - 1;
  13179. if ( currentTextureSlot !== webglSlot ) {
  13180. gl.activeTexture( webglSlot );
  13181. currentTextureSlot = webglSlot;
  13182. }
  13183. }
  13184. function bindTexture( webglType, webglTexture ) {
  13185. if ( currentTextureSlot === null ) {
  13186. activeTexture();
  13187. }
  13188. let boundTexture = currentBoundTextures[ currentTextureSlot ];
  13189. if ( boundTexture === undefined ) {
  13190. boundTexture = { type: undefined, texture: undefined };
  13191. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  13192. }
  13193. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  13194. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  13195. boundTexture.type = webglType;
  13196. boundTexture.texture = webglTexture;
  13197. }
  13198. }
  13199. function unbindTexture() {
  13200. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  13201. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  13202. gl.bindTexture( boundTexture.type, null );
  13203. boundTexture.type = undefined;
  13204. boundTexture.texture = undefined;
  13205. }
  13206. }
  13207. function compressedTexImage2D() {
  13208. try {
  13209. gl.compressedTexImage2D.apply( gl, arguments );
  13210. } catch ( error ) {
  13211. console.error( 'THREE.WebGLState:', error );
  13212. }
  13213. }
  13214. function texSubImage2D() {
  13215. try {
  13216. gl.texSubImage2D.apply( gl, arguments );
  13217. } catch ( error ) {
  13218. console.error( 'THREE.WebGLState:', error );
  13219. }
  13220. }
  13221. function texSubImage3D() {
  13222. try {
  13223. gl.texSubImage3D.apply( gl, arguments );
  13224. } catch ( error ) {
  13225. console.error( 'THREE.WebGLState:', error );
  13226. }
  13227. }
  13228. function compressedTexSubImage2D() {
  13229. try {
  13230. gl.compressedTexSubImage2D.apply( gl, arguments );
  13231. } catch ( error ) {
  13232. console.error( 'THREE.WebGLState:', error );
  13233. }
  13234. }
  13235. function texStorage2D() {
  13236. try {
  13237. gl.texStorage2D.apply( gl, arguments );
  13238. } catch ( error ) {
  13239. console.error( 'THREE.WebGLState:', error );
  13240. }
  13241. }
  13242. function texStorage3D() {
  13243. try {
  13244. gl.texStorage3D.apply( gl, arguments );
  13245. } catch ( error ) {
  13246. console.error( 'THREE.WebGLState:', error );
  13247. }
  13248. }
  13249. function texImage2D() {
  13250. try {
  13251. gl.texImage2D.apply( gl, arguments );
  13252. } catch ( error ) {
  13253. console.error( 'THREE.WebGLState:', error );
  13254. }
  13255. }
  13256. function texImage3D() {
  13257. try {
  13258. gl.texImage3D.apply( gl, arguments );
  13259. } catch ( error ) {
  13260. console.error( 'THREE.WebGLState:', error );
  13261. }
  13262. }
  13263. //
  13264. function scissor( scissor ) {
  13265. if ( currentScissor.equals( scissor ) === false ) {
  13266. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  13267. currentScissor.copy( scissor );
  13268. }
  13269. }
  13270. function viewport( viewport ) {
  13271. if ( currentViewport.equals( viewport ) === false ) {
  13272. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  13273. currentViewport.copy( viewport );
  13274. }
  13275. }
  13276. function updateUBOMapping( uniformsGroup, program ) {
  13277. let mapping = uboProgamMap.get( program );
  13278. if ( mapping === undefined ) {
  13279. mapping = new WeakMap();
  13280. uboProgamMap.set( program, mapping );
  13281. }
  13282. let blockIndex = mapping.get( uniformsGroup );
  13283. if ( blockIndex === undefined ) {
  13284. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  13285. mapping.set( uniformsGroup, blockIndex );
  13286. }
  13287. }
  13288. function uniformBlockBinding( uniformsGroup, program ) {
  13289. const mapping = uboProgamMap.get( program );
  13290. const blockIndex = mapping.get( uniformsGroup );
  13291. if ( uboBindings.get( uniformsGroup ) !== blockIndex ) {
  13292. // bind shader specific block index to global block point
  13293. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  13294. uboBindings.set( uniformsGroup, blockIndex );
  13295. }
  13296. }
  13297. //
  13298. function reset() {
  13299. // reset state
  13300. gl.disable( 3042 );
  13301. gl.disable( 2884 );
  13302. gl.disable( 2929 );
  13303. gl.disable( 32823 );
  13304. gl.disable( 3089 );
  13305. gl.disable( 2960 );
  13306. gl.disable( 32926 );
  13307. gl.blendEquation( 32774 );
  13308. gl.blendFunc( 1, 0 );
  13309. gl.blendFuncSeparate( 1, 0, 1, 0 );
  13310. gl.colorMask( true, true, true, true );
  13311. gl.clearColor( 0, 0, 0, 0 );
  13312. gl.depthMask( true );
  13313. gl.depthFunc( 513 );
  13314. gl.clearDepth( 1 );
  13315. gl.stencilMask( 0xffffffff );
  13316. gl.stencilFunc( 519, 0, 0xffffffff );
  13317. gl.stencilOp( 7680, 7680, 7680 );
  13318. gl.clearStencil( 0 );
  13319. gl.cullFace( 1029 );
  13320. gl.frontFace( 2305 );
  13321. gl.polygonOffset( 0, 0 );
  13322. gl.activeTexture( 33984 );
  13323. gl.bindFramebuffer( 36160, null );
  13324. if ( isWebGL2 === true ) {
  13325. gl.bindFramebuffer( 36009, null );
  13326. gl.bindFramebuffer( 36008, null );
  13327. }
  13328. gl.useProgram( null );
  13329. gl.lineWidth( 1 );
  13330. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  13331. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  13332. // reset internals
  13333. enabledCapabilities = {};
  13334. currentTextureSlot = null;
  13335. currentBoundTextures = {};
  13336. currentBoundFramebuffers = {};
  13337. currentDrawbuffers = new WeakMap();
  13338. defaultDrawbuffers = [];
  13339. currentProgram = null;
  13340. currentBlendingEnabled = false;
  13341. currentBlending = null;
  13342. currentBlendEquation = null;
  13343. currentBlendSrc = null;
  13344. currentBlendDst = null;
  13345. currentBlendEquationAlpha = null;
  13346. currentBlendSrcAlpha = null;
  13347. currentBlendDstAlpha = null;
  13348. currentPremultipledAlpha = false;
  13349. currentFlipSided = null;
  13350. currentCullFace = null;
  13351. currentLineWidth = null;
  13352. currentPolygonOffsetFactor = null;
  13353. currentPolygonOffsetUnits = null;
  13354. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13355. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  13356. colorBuffer.reset();
  13357. depthBuffer.reset();
  13358. stencilBuffer.reset();
  13359. }
  13360. return {
  13361. buffers: {
  13362. color: colorBuffer,
  13363. depth: depthBuffer,
  13364. stencil: stencilBuffer
  13365. },
  13366. enable: enable,
  13367. disable: disable,
  13368. bindFramebuffer: bindFramebuffer,
  13369. drawBuffers: drawBuffers,
  13370. useProgram: useProgram,
  13371. setBlending: setBlending,
  13372. setMaterial: setMaterial,
  13373. setFlipSided: setFlipSided,
  13374. setCullFace: setCullFace,
  13375. setLineWidth: setLineWidth,
  13376. setPolygonOffset: setPolygonOffset,
  13377. setScissorTest: setScissorTest,
  13378. activeTexture: activeTexture,
  13379. bindTexture: bindTexture,
  13380. unbindTexture: unbindTexture,
  13381. compressedTexImage2D: compressedTexImage2D,
  13382. texImage2D: texImage2D,
  13383. texImage3D: texImage3D,
  13384. updateUBOMapping: updateUBOMapping,
  13385. uniformBlockBinding: uniformBlockBinding,
  13386. texStorage2D: texStorage2D,
  13387. texStorage3D: texStorage3D,
  13388. texSubImage2D: texSubImage2D,
  13389. texSubImage3D: texSubImage3D,
  13390. compressedTexSubImage2D: compressedTexSubImage2D,
  13391. scissor: scissor,
  13392. viewport: viewport,
  13393. reset: reset
  13394. };
  13395. }
  13396. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  13397. const isWebGL2 = capabilities.isWebGL2;
  13398. const maxTextures = capabilities.maxTextures;
  13399. const maxCubemapSize = capabilities.maxCubemapSize;
  13400. const maxTextureSize = capabilities.maxTextureSize;
  13401. const maxSamples = capabilities.maxSamples;
  13402. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  13403. const supportsInvalidateFramebuffer = /OculusBrowser/g.test( navigator.userAgent );
  13404. const _videoTextures = new WeakMap();
  13405. let _canvas;
  13406. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  13407. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  13408. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  13409. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  13410. let useOffscreenCanvas = false;
  13411. try {
  13412. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  13413. // eslint-disable-next-line compat/compat
  13414. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  13415. } catch ( err ) {
  13416. // Ignore any errors
  13417. }
  13418. function createCanvas( width, height ) {
  13419. // Use OffscreenCanvas when available. Specially needed in web workers
  13420. return useOffscreenCanvas ?
  13421. // eslint-disable-next-line compat/compat
  13422. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  13423. }
  13424. function resizeImage( image, needsPowerOfTwo, needsNewCanvas, maxSize ) {
  13425. let scale = 1;
  13426. // handle case if texture exceeds max size
  13427. if ( image.width > maxSize || image.height > maxSize ) {
  13428. scale = maxSize / Math.max( image.width, image.height );
  13429. }
  13430. // only perform resize if necessary
  13431. if ( scale < 1 || needsPowerOfTwo === true ) {
  13432. // only perform resize for certain image types
  13433. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  13434. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  13435. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  13436. const floor = needsPowerOfTwo ? floorPowerOfTwo : Math.floor;
  13437. const width = floor( scale * image.width );
  13438. const height = floor( scale * image.height );
  13439. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  13440. // cube textures can't reuse the same canvas
  13441. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  13442. canvas.width = width;
  13443. canvas.height = height;
  13444. const context = canvas.getContext( '2d' );
  13445. context.drawImage( image, 0, 0, width, height );
  13446. console.warn( 'THREE.WebGLRenderer: Texture has been resized from (' + image.width + 'x' + image.height + ') to (' + width + 'x' + height + ').' );
  13447. return canvas;
  13448. } else {
  13449. if ( 'data' in image ) {
  13450. console.warn( 'THREE.WebGLRenderer: Image in DataTexture is too big (' + image.width + 'x' + image.height + ').' );
  13451. }
  13452. return image;
  13453. }
  13454. }
  13455. return image;
  13456. }
  13457. function isPowerOfTwo$1( image ) {
  13458. return isPowerOfTwo( image.width ) && isPowerOfTwo( image.height );
  13459. }
  13460. function textureNeedsPowerOfTwo( texture ) {
  13461. if ( isWebGL2 ) return false;
  13462. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  13463. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  13464. }
  13465. function textureNeedsGenerateMipmaps( texture, supportsMips ) {
  13466. return texture.generateMipmaps && supportsMips &&
  13467. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  13468. }
  13469. function generateMipmap( target ) {
  13470. _gl.generateMipmap( target );
  13471. }
  13472. function getInternalFormat( internalFormatName, glFormat, glType, encoding, isVideoTexture = false ) {
  13473. if ( isWebGL2 === false ) return glFormat;
  13474. if ( internalFormatName !== null ) {
  13475. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  13476. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  13477. }
  13478. let internalFormat = glFormat;
  13479. if ( glFormat === 6403 ) {
  13480. if ( glType === 5126 ) internalFormat = 33326;
  13481. if ( glType === 5131 ) internalFormat = 33325;
  13482. if ( glType === 5121 ) internalFormat = 33321;
  13483. }
  13484. if ( glFormat === 33319 ) {
  13485. if ( glType === 5126 ) internalFormat = 33328;
  13486. if ( glType === 5131 ) internalFormat = 33327;
  13487. if ( glType === 5121 ) internalFormat = 33323;
  13488. }
  13489. if ( glFormat === 6408 ) {
  13490. if ( glType === 5126 ) internalFormat = 34836;
  13491. if ( glType === 5131 ) internalFormat = 34842;
  13492. if ( glType === 5121 ) internalFormat = ( encoding === sRGBEncoding && isVideoTexture === false ) ? 35907 : 32856;
  13493. if ( glType === 32819 ) internalFormat = 32854;
  13494. if ( glType === 32820 ) internalFormat = 32855;
  13495. }
  13496. if ( internalFormat === 33325 || internalFormat === 33326 ||
  13497. internalFormat === 33327 || internalFormat === 33328 ||
  13498. internalFormat === 34842 || internalFormat === 34836 ) {
  13499. extensions.get( 'EXT_color_buffer_float' );
  13500. }
  13501. return internalFormat;
  13502. }
  13503. function getMipLevels( texture, image, supportsMips ) {
  13504. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  13505. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  13506. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  13507. // user-defined mipmaps
  13508. return texture.mipmaps.length;
  13509. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  13510. return image.mipmaps.length;
  13511. } else {
  13512. // texture without mipmaps (only base level)
  13513. return 1;
  13514. }
  13515. }
  13516. // Fallback filters for non-power-of-2 textures
  13517. function filterFallback( f ) {
  13518. if ( f === NearestFilter || f === NearestMipmapNearestFilter || f === NearestMipmapLinearFilter ) {
  13519. return 9728;
  13520. }
  13521. return 9729;
  13522. }
  13523. //
  13524. function onTextureDispose( event ) {
  13525. const texture = event.target;
  13526. texture.removeEventListener( 'dispose', onTextureDispose );
  13527. deallocateTexture( texture );
  13528. if ( texture.isVideoTexture ) {
  13529. _videoTextures.delete( texture );
  13530. }
  13531. }
  13532. function onRenderTargetDispose( event ) {
  13533. const renderTarget = event.target;
  13534. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  13535. deallocateRenderTarget( renderTarget );
  13536. }
  13537. //
  13538. function deallocateTexture( texture ) {
  13539. const textureProperties = properties.get( texture );
  13540. if ( textureProperties.__webglInit === undefined ) return;
  13541. // check if it's necessary to remove the WebGLTexture object
  13542. const source = texture.source;
  13543. const webglTextures = _sources.get( source );
  13544. if ( webglTextures ) {
  13545. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  13546. webglTexture.usedTimes --;
  13547. // the WebGLTexture object is not used anymore, remove it
  13548. if ( webglTexture.usedTimes === 0 ) {
  13549. deleteTexture( texture );
  13550. }
  13551. // remove the weak map entry if no WebGLTexture uses the source anymore
  13552. if ( Object.keys( webglTextures ).length === 0 ) {
  13553. _sources.delete( source );
  13554. }
  13555. }
  13556. properties.remove( texture );
  13557. }
  13558. function deleteTexture( texture ) {
  13559. const textureProperties = properties.get( texture );
  13560. _gl.deleteTexture( textureProperties.__webglTexture );
  13561. const source = texture.source;
  13562. const webglTextures = _sources.get( source );
  13563. delete webglTextures[ textureProperties.__cacheKey ];
  13564. info.memory.textures --;
  13565. }
  13566. function deallocateRenderTarget( renderTarget ) {
  13567. const texture = renderTarget.texture;
  13568. const renderTargetProperties = properties.get( renderTarget );
  13569. const textureProperties = properties.get( texture );
  13570. if ( textureProperties.__webglTexture !== undefined ) {
  13571. _gl.deleteTexture( textureProperties.__webglTexture );
  13572. info.memory.textures --;
  13573. }
  13574. if ( renderTarget.depthTexture ) {
  13575. renderTarget.depthTexture.dispose();
  13576. }
  13577. if ( renderTarget.isWebGLCubeRenderTarget ) {
  13578. for ( let i = 0; i < 6; i ++ ) {
  13579. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  13580. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  13581. }
  13582. } else {
  13583. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  13584. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  13585. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  13586. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  13587. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  13588. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  13589. }
  13590. }
  13591. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  13592. }
  13593. if ( renderTarget.isWebGLMultipleRenderTargets ) {
  13594. for ( let i = 0, il = texture.length; i < il; i ++ ) {
  13595. const attachmentProperties = properties.get( texture[ i ] );
  13596. if ( attachmentProperties.__webglTexture ) {
  13597. _gl.deleteTexture( attachmentProperties.__webglTexture );
  13598. info.memory.textures --;
  13599. }
  13600. properties.remove( texture[ i ] );
  13601. }
  13602. }
  13603. properties.remove( texture );
  13604. properties.remove( renderTarget );
  13605. }
  13606. //
  13607. let textureUnits = 0;
  13608. function resetTextureUnits() {
  13609. textureUnits = 0;
  13610. }
  13611. function allocateTextureUnit() {
  13612. const textureUnit = textureUnits;
  13613. if ( textureUnit >= maxTextures ) {
  13614. console.warn( 'THREE.WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + maxTextures );
  13615. }
  13616. textureUnits += 1;
  13617. return textureUnit;
  13618. }
  13619. function getTextureCacheKey( texture ) {
  13620. const array = [];
  13621. array.push( texture.wrapS );
  13622. array.push( texture.wrapT );
  13623. array.push( texture.magFilter );
  13624. array.push( texture.minFilter );
  13625. array.push( texture.anisotropy );
  13626. array.push( texture.internalFormat );
  13627. array.push( texture.format );
  13628. array.push( texture.type );
  13629. array.push( texture.generateMipmaps );
  13630. array.push( texture.premultiplyAlpha );
  13631. array.push( texture.flipY );
  13632. array.push( texture.unpackAlignment );
  13633. array.push( texture.encoding );
  13634. return array.join();
  13635. }
  13636. //
  13637. function setTexture2D( texture, slot ) {
  13638. const textureProperties = properties.get( texture );
  13639. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  13640. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  13641. const image = texture.image;
  13642. if ( image === null ) {
  13643. console.warn( 'THREE.WebGLRenderer: Texture marked for update but no image data found.' );
  13644. } else if ( image.complete === false ) {
  13645. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete' );
  13646. } else {
  13647. uploadTexture( textureProperties, texture, slot );
  13648. return;
  13649. }
  13650. }
  13651. state.activeTexture( 33984 + slot );
  13652. state.bindTexture( 3553, textureProperties.__webglTexture );
  13653. }
  13654. function setTexture2DArray( texture, slot ) {
  13655. const textureProperties = properties.get( texture );
  13656. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13657. uploadTexture( textureProperties, texture, slot );
  13658. return;
  13659. }
  13660. state.activeTexture( 33984 + slot );
  13661. state.bindTexture( 35866, textureProperties.__webglTexture );
  13662. }
  13663. function setTexture3D( texture, slot ) {
  13664. const textureProperties = properties.get( texture );
  13665. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13666. uploadTexture( textureProperties, texture, slot );
  13667. return;
  13668. }
  13669. state.activeTexture( 33984 + slot );
  13670. state.bindTexture( 32879, textureProperties.__webglTexture );
  13671. }
  13672. function setTextureCube( texture, slot ) {
  13673. const textureProperties = properties.get( texture );
  13674. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  13675. uploadCubeTexture( textureProperties, texture, slot );
  13676. return;
  13677. }
  13678. state.activeTexture( 33984 + slot );
  13679. state.bindTexture( 34067, textureProperties.__webglTexture );
  13680. }
  13681. const wrappingToGL = {
  13682. [ RepeatWrapping ]: 10497,
  13683. [ ClampToEdgeWrapping ]: 33071,
  13684. [ MirroredRepeatWrapping ]: 33648
  13685. };
  13686. const filterToGL = {
  13687. [ NearestFilter ]: 9728,
  13688. [ NearestMipmapNearestFilter ]: 9984,
  13689. [ NearestMipmapLinearFilter ]: 9986,
  13690. [ LinearFilter ]: 9729,
  13691. [ LinearMipmapNearestFilter ]: 9985,
  13692. [ LinearMipmapLinearFilter ]: 9987
  13693. };
  13694. function setTextureParameters( textureType, texture, supportsMips ) {
  13695. if ( supportsMips ) {
  13696. _gl.texParameteri( textureType, 10242, wrappingToGL[ texture.wrapS ] );
  13697. _gl.texParameteri( textureType, 10243, wrappingToGL[ texture.wrapT ] );
  13698. if ( textureType === 32879 || textureType === 35866 ) {
  13699. _gl.texParameteri( textureType, 32882, wrappingToGL[ texture.wrapR ] );
  13700. }
  13701. _gl.texParameteri( textureType, 10240, filterToGL[ texture.magFilter ] );
  13702. _gl.texParameteri( textureType, 10241, filterToGL[ texture.minFilter ] );
  13703. } else {
  13704. _gl.texParameteri( textureType, 10242, 33071 );
  13705. _gl.texParameteri( textureType, 10243, 33071 );
  13706. if ( textureType === 32879 || textureType === 35866 ) {
  13707. _gl.texParameteri( textureType, 32882, 33071 );
  13708. }
  13709. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  13710. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.' );
  13711. }
  13712. _gl.texParameteri( textureType, 10240, filterFallback( texture.magFilter ) );
  13713. _gl.texParameteri( textureType, 10241, filterFallback( texture.minFilter ) );
  13714. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  13715. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.' );
  13716. }
  13717. }
  13718. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  13719. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  13720. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  13721. if ( isWebGL2 === false && ( texture.type === HalfFloatType && extensions.has( 'OES_texture_half_float_linear' ) === false ) ) return; // verify extension for WebGL 1 only
  13722. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  13723. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  13724. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  13725. }
  13726. }
  13727. }
  13728. function initTexture( textureProperties, texture ) {
  13729. let forceUpload = false;
  13730. if ( textureProperties.__webglInit === undefined ) {
  13731. textureProperties.__webglInit = true;
  13732. texture.addEventListener( 'dispose', onTextureDispose );
  13733. }
  13734. // create Source <-> WebGLTextures mapping if necessary
  13735. const source = texture.source;
  13736. let webglTextures = _sources.get( source );
  13737. if ( webglTextures === undefined ) {
  13738. webglTextures = {};
  13739. _sources.set( source, webglTextures );
  13740. }
  13741. // check if there is already a WebGLTexture object for the given texture parameters
  13742. const textureCacheKey = getTextureCacheKey( texture );
  13743. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  13744. // if not, create a new instance of WebGLTexture
  13745. if ( webglTextures[ textureCacheKey ] === undefined ) {
  13746. // create new entry
  13747. webglTextures[ textureCacheKey ] = {
  13748. texture: _gl.createTexture(),
  13749. usedTimes: 0
  13750. };
  13751. info.memory.textures ++;
  13752. // when a new instance of WebGLTexture was created, a texture upload is required
  13753. // even if the image contents are identical
  13754. forceUpload = true;
  13755. }
  13756. webglTextures[ textureCacheKey ].usedTimes ++;
  13757. // every time the texture cache key changes, it's necessary to check if an instance of
  13758. // WebGLTexture can be deleted in order to avoid a memory leak.
  13759. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  13760. if ( webglTexture !== undefined ) {
  13761. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  13762. if ( webglTexture.usedTimes === 0 ) {
  13763. deleteTexture( texture );
  13764. }
  13765. }
  13766. // store references to cache key and WebGLTexture object
  13767. textureProperties.__cacheKey = textureCacheKey;
  13768. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  13769. }
  13770. return forceUpload;
  13771. }
  13772. function uploadTexture( textureProperties, texture, slot ) {
  13773. let textureType = 3553;
  13774. if ( texture.isDataArrayTexture ) textureType = 35866;
  13775. if ( texture.isData3DTexture ) textureType = 32879;
  13776. const forceUpload = initTexture( textureProperties, texture );
  13777. const source = texture.source;
  13778. state.activeTexture( 33984 + slot );
  13779. state.bindTexture( textureType, textureProperties.__webglTexture );
  13780. if ( source.version !== source.__currentVersion || forceUpload === true ) {
  13781. _gl.pixelStorei( 37440, texture.flipY );
  13782. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  13783. _gl.pixelStorei( 3317, texture.unpackAlignment );
  13784. _gl.pixelStorei( 37443, 0 );
  13785. const needsPowerOfTwo = textureNeedsPowerOfTwo( texture ) && isPowerOfTwo$1( texture.image ) === false;
  13786. let image = resizeImage( texture.image, needsPowerOfTwo, false, maxTextureSize );
  13787. image = verifyColorSpace( texture, image );
  13788. const supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  13789. glFormat = utils.convert( texture.format, texture.encoding );
  13790. let glType = utils.convert( texture.type ),
  13791. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding, texture.isVideoTexture );
  13792. setTextureParameters( textureType, texture, supportsMips );
  13793. let mipmap;
  13794. const mipmaps = texture.mipmaps;
  13795. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  13796. const allocateMemory = ( source.__currentVersion === undefined ) || ( forceUpload === true );
  13797. const levels = getMipLevels( texture, image, supportsMips );
  13798. if ( texture.isDepthTexture ) {
  13799. // populate depth texture with dummy data
  13800. glInternalFormat = 6402;
  13801. if ( isWebGL2 ) {
  13802. if ( texture.type === FloatType ) {
  13803. glInternalFormat = 36012;
  13804. } else if ( texture.type === UnsignedIntType ) {
  13805. glInternalFormat = 33190;
  13806. } else if ( texture.type === UnsignedInt248Type ) {
  13807. glInternalFormat = 35056;
  13808. } else {
  13809. glInternalFormat = 33189; // WebGL2 requires sized internalformat for glTexImage2D
  13810. }
  13811. } else {
  13812. if ( texture.type === FloatType ) {
  13813. console.error( 'WebGLRenderer: Floating point depth texture requires WebGL2.' );
  13814. }
  13815. }
  13816. // validation checks for WebGL 1
  13817. if ( texture.format === DepthFormat && glInternalFormat === 6402 ) {
  13818. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13819. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  13820. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13821. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  13822. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  13823. texture.type = UnsignedIntType;
  13824. glType = utils.convert( texture.type );
  13825. }
  13826. }
  13827. if ( texture.format === DepthStencilFormat && glInternalFormat === 6402 ) {
  13828. // Depth stencil textures need the DEPTH_STENCIL internal format
  13829. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13830. glInternalFormat = 34041;
  13831. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  13832. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  13833. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  13834. if ( texture.type !== UnsignedInt248Type ) {
  13835. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  13836. texture.type = UnsignedInt248Type;
  13837. glType = utils.convert( texture.type );
  13838. }
  13839. }
  13840. //
  13841. if ( allocateMemory ) {
  13842. if ( useTexStorage ) {
  13843. state.texStorage2D( 3553, 1, glInternalFormat, image.width, image.height );
  13844. } else {
  13845. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  13846. }
  13847. }
  13848. } else if ( texture.isDataTexture ) {
  13849. // use manually created mipmaps if available
  13850. // if there are no manual mipmaps
  13851. // set 0 level mipmap and then use GL to generate other mipmap levels
  13852. if ( mipmaps.length > 0 && supportsMips ) {
  13853. if ( useTexStorage && allocateMemory ) {
  13854. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  13855. }
  13856. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13857. mipmap = mipmaps[ i ];
  13858. if ( useTexStorage ) {
  13859. state.texSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  13860. } else {
  13861. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13862. }
  13863. }
  13864. texture.generateMipmaps = false;
  13865. } else {
  13866. if ( useTexStorage ) {
  13867. if ( allocateMemory ) {
  13868. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  13869. }
  13870. state.texSubImage2D( 3553, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  13871. } else {
  13872. state.texImage2D( 3553, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  13873. }
  13874. }
  13875. } else if ( texture.isCompressedTexture ) {
  13876. if ( useTexStorage && allocateMemory ) {
  13877. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  13878. }
  13879. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13880. mipmap = mipmaps[ i ];
  13881. if ( texture.format !== RGBAFormat ) {
  13882. if ( glFormat !== null ) {
  13883. if ( useTexStorage ) {
  13884. state.compressedTexSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  13885. } else {
  13886. state.compressedTexImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13887. }
  13888. } else {
  13889. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  13890. }
  13891. } else {
  13892. if ( useTexStorage ) {
  13893. state.texSubImage2D( 3553, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  13894. } else {
  13895. state.texImage2D( 3553, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13896. }
  13897. }
  13898. }
  13899. } else if ( texture.isDataArrayTexture ) {
  13900. if ( useTexStorage ) {
  13901. if ( allocateMemory ) {
  13902. state.texStorage3D( 35866, levels, glInternalFormat, image.width, image.height, image.depth );
  13903. }
  13904. state.texSubImage3D( 35866, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  13905. } else {
  13906. state.texImage3D( 35866, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  13907. }
  13908. } else if ( texture.isData3DTexture ) {
  13909. if ( useTexStorage ) {
  13910. if ( allocateMemory ) {
  13911. state.texStorage3D( 32879, levels, glInternalFormat, image.width, image.height, image.depth );
  13912. }
  13913. state.texSubImage3D( 32879, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  13914. } else {
  13915. state.texImage3D( 32879, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  13916. }
  13917. } else if ( texture.isFramebufferTexture ) {
  13918. if ( allocateMemory ) {
  13919. if ( useTexStorage ) {
  13920. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  13921. } else {
  13922. let width = image.width, height = image.height;
  13923. for ( let i = 0; i < levels; i ++ ) {
  13924. state.texImage2D( 3553, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  13925. width >>= 1;
  13926. height >>= 1;
  13927. }
  13928. }
  13929. }
  13930. } else {
  13931. // regular Texture (image, video, canvas)
  13932. // use manually created mipmaps if available
  13933. // if there are no manual mipmaps
  13934. // set 0 level mipmap and then use GL to generate other mipmap levels
  13935. if ( mipmaps.length > 0 && supportsMips ) {
  13936. if ( useTexStorage && allocateMemory ) {
  13937. state.texStorage2D( 3553, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  13938. }
  13939. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  13940. mipmap = mipmaps[ i ];
  13941. if ( useTexStorage ) {
  13942. state.texSubImage2D( 3553, i, 0, 0, glFormat, glType, mipmap );
  13943. } else {
  13944. state.texImage2D( 3553, i, glInternalFormat, glFormat, glType, mipmap );
  13945. }
  13946. }
  13947. texture.generateMipmaps = false;
  13948. } else {
  13949. if ( useTexStorage ) {
  13950. if ( allocateMemory ) {
  13951. state.texStorage2D( 3553, levels, glInternalFormat, image.width, image.height );
  13952. }
  13953. state.texSubImage2D( 3553, 0, 0, 0, glFormat, glType, image );
  13954. } else {
  13955. state.texImage2D( 3553, 0, glInternalFormat, glFormat, glType, image );
  13956. }
  13957. }
  13958. }
  13959. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  13960. generateMipmap( textureType );
  13961. }
  13962. source.__currentVersion = source.version;
  13963. if ( texture.onUpdate ) texture.onUpdate( texture );
  13964. }
  13965. textureProperties.__version = texture.version;
  13966. }
  13967. function uploadCubeTexture( textureProperties, texture, slot ) {
  13968. if ( texture.image.length !== 6 ) return;
  13969. const forceUpload = initTexture( textureProperties, texture );
  13970. const source = texture.source;
  13971. state.activeTexture( 33984 + slot );
  13972. state.bindTexture( 34067, textureProperties.__webglTexture );
  13973. if ( source.version !== source.__currentVersion || forceUpload === true ) {
  13974. _gl.pixelStorei( 37440, texture.flipY );
  13975. _gl.pixelStorei( 37441, texture.premultiplyAlpha );
  13976. _gl.pixelStorei( 3317, texture.unpackAlignment );
  13977. _gl.pixelStorei( 37443, 0 );
  13978. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  13979. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  13980. const cubeImage = [];
  13981. for ( let i = 0; i < 6; i ++ ) {
  13982. if ( ! isCompressed && ! isDataTexture ) {
  13983. cubeImage[ i ] = resizeImage( texture.image[ i ], false, true, maxCubemapSize );
  13984. } else {
  13985. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  13986. }
  13987. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  13988. }
  13989. const image = cubeImage[ 0 ],
  13990. supportsMips = isPowerOfTwo$1( image ) || isWebGL2,
  13991. glFormat = utils.convert( texture.format, texture.encoding ),
  13992. glType = utils.convert( texture.type ),
  13993. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  13994. const useTexStorage = ( isWebGL2 && texture.isVideoTexture !== true );
  13995. const allocateMemory = ( source.__currentVersion === undefined ) || ( forceUpload === true );
  13996. let levels = getMipLevels( texture, image, supportsMips );
  13997. setTextureParameters( 34067, texture, supportsMips );
  13998. let mipmaps;
  13999. if ( isCompressed ) {
  14000. if ( useTexStorage && allocateMemory ) {
  14001. state.texStorage2D( 34067, levels, glInternalFormat, image.width, image.height );
  14002. }
  14003. for ( let i = 0; i < 6; i ++ ) {
  14004. mipmaps = cubeImage[ i ].mipmaps;
  14005. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14006. const mipmap = mipmaps[ j ];
  14007. if ( texture.format !== RGBAFormat ) {
  14008. if ( glFormat !== null ) {
  14009. if ( useTexStorage ) {
  14010. state.compressedTexSubImage2D( 34069 + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  14011. } else {
  14012. state.compressedTexImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14013. }
  14014. } else {
  14015. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  14016. }
  14017. } else {
  14018. if ( useTexStorage ) {
  14019. state.texSubImage2D( 34069 + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  14020. } else {
  14021. state.texImage2D( 34069 + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14022. }
  14023. }
  14024. }
  14025. }
  14026. } else {
  14027. mipmaps = texture.mipmaps;
  14028. if ( useTexStorage && allocateMemory ) {
  14029. // TODO: Uniformly handle mipmap definitions
  14030. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  14031. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  14032. if ( mipmaps.length > 0 ) levels ++;
  14033. state.texStorage2D( 34067, levels, glInternalFormat, cubeImage[ 0 ].width, cubeImage[ 0 ].height );
  14034. }
  14035. for ( let i = 0; i < 6; i ++ ) {
  14036. if ( isDataTexture ) {
  14037. if ( useTexStorage ) {
  14038. state.texSubImage2D( 34069 + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  14039. } else {
  14040. state.texImage2D( 34069 + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  14041. }
  14042. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14043. const mipmap = mipmaps[ j ];
  14044. const mipmapImage = mipmap.image[ i ].image;
  14045. if ( useTexStorage ) {
  14046. state.texSubImage2D( 34069 + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  14047. } else {
  14048. state.texImage2D( 34069 + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  14049. }
  14050. }
  14051. } else {
  14052. if ( useTexStorage ) {
  14053. state.texSubImage2D( 34069 + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  14054. } else {
  14055. state.texImage2D( 34069 + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  14056. }
  14057. for ( let j = 0; j < mipmaps.length; j ++ ) {
  14058. const mipmap = mipmaps[ j ];
  14059. if ( useTexStorage ) {
  14060. state.texSubImage2D( 34069 + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  14061. } else {
  14062. state.texImage2D( 34069 + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  14063. }
  14064. }
  14065. }
  14066. }
  14067. }
  14068. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14069. // We assume images for cube map have the same size.
  14070. generateMipmap( 34067 );
  14071. }
  14072. source.__currentVersion = source.version;
  14073. if ( texture.onUpdate ) texture.onUpdate( texture );
  14074. }
  14075. textureProperties.__version = texture.version;
  14076. }
  14077. // Render targets
  14078. // Setup storage for target texture and bind it to correct framebuffer
  14079. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget ) {
  14080. const glFormat = utils.convert( texture.format, texture.encoding );
  14081. const glType = utils.convert( texture.type );
  14082. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14083. const renderTargetProperties = properties.get( renderTarget );
  14084. if ( ! renderTargetProperties.__hasExternalTextures ) {
  14085. if ( textureTarget === 32879 || textureTarget === 35866 ) {
  14086. state.texImage3D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, renderTarget.depth, 0, glFormat, glType, null );
  14087. } else {
  14088. state.texImage2D( textureTarget, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14089. }
  14090. }
  14091. state.bindFramebuffer( 36160, framebuffer );
  14092. if ( useMultisampledRTT( renderTarget ) ) {
  14093. multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  14094. } else {
  14095. _gl.framebufferTexture2D( 36160, attachment, textureTarget, properties.get( texture ).__webglTexture, 0 );
  14096. }
  14097. state.bindFramebuffer( 36160, null );
  14098. }
  14099. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  14100. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  14101. _gl.bindRenderbuffer( 36161, renderbuffer );
  14102. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14103. let glInternalFormat = 33189;
  14104. if ( isMultisample || useMultisampledRTT( renderTarget ) ) {
  14105. const depthTexture = renderTarget.depthTexture;
  14106. if ( depthTexture && depthTexture.isDepthTexture ) {
  14107. if ( depthTexture.type === FloatType ) {
  14108. glInternalFormat = 36012;
  14109. } else if ( depthTexture.type === UnsignedIntType ) {
  14110. glInternalFormat = 33190;
  14111. }
  14112. }
  14113. const samples = getRenderTargetSamples( renderTarget );
  14114. if ( useMultisampledRTT( renderTarget ) ) {
  14115. multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14116. } else {
  14117. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14118. }
  14119. } else {
  14120. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  14121. }
  14122. _gl.framebufferRenderbuffer( 36160, 36096, 36161, renderbuffer );
  14123. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14124. const samples = getRenderTargetSamples( renderTarget );
  14125. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14126. _gl.renderbufferStorageMultisample( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  14127. } else if ( useMultisampledRTT( renderTarget ) ) {
  14128. multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, 35056, renderTarget.width, renderTarget.height );
  14129. } else {
  14130. _gl.renderbufferStorage( 36161, 34041, renderTarget.width, renderTarget.height );
  14131. }
  14132. _gl.framebufferRenderbuffer( 36160, 33306, 36161, renderbuffer );
  14133. } else {
  14134. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14135. for ( let i = 0; i < textures.length; i ++ ) {
  14136. const texture = textures[ i ];
  14137. const glFormat = utils.convert( texture.format, texture.encoding );
  14138. const glType = utils.convert( texture.type );
  14139. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14140. const samples = getRenderTargetSamples( renderTarget );
  14141. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  14142. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14143. } else if ( useMultisampledRTT( renderTarget ) ) {
  14144. multisampledRTTExt.renderbufferStorageMultisampleEXT( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14145. } else {
  14146. _gl.renderbufferStorage( 36161, glInternalFormat, renderTarget.width, renderTarget.height );
  14147. }
  14148. }
  14149. }
  14150. _gl.bindRenderbuffer( 36161, null );
  14151. }
  14152. // Setup resources for a Depth Texture for a FBO (needs an extension)
  14153. function setupDepthTexture( framebuffer, renderTarget ) {
  14154. const isCube = ( renderTarget && renderTarget.isWebGLCubeRenderTarget );
  14155. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  14156. state.bindFramebuffer( 36160, framebuffer );
  14157. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  14158. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  14159. }
  14160. // upload an empty depth texture with framebuffer size
  14161. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  14162. renderTarget.depthTexture.image.width !== renderTarget.width ||
  14163. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  14164. renderTarget.depthTexture.image.width = renderTarget.width;
  14165. renderTarget.depthTexture.image.height = renderTarget.height;
  14166. renderTarget.depthTexture.needsUpdate = true;
  14167. }
  14168. setTexture2D( renderTarget.depthTexture, 0 );
  14169. const webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  14170. const samples = getRenderTargetSamples( renderTarget );
  14171. if ( renderTarget.depthTexture.format === DepthFormat ) {
  14172. if ( useMultisampledRTT( renderTarget ) ) {
  14173. multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, 36096, 3553, webglDepthTexture, 0, samples );
  14174. } else {
  14175. _gl.framebufferTexture2D( 36160, 36096, 3553, webglDepthTexture, 0 );
  14176. }
  14177. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  14178. if ( useMultisampledRTT( renderTarget ) ) {
  14179. multisampledRTTExt.framebufferTexture2DMultisampleEXT( 36160, 33306, 3553, webglDepthTexture, 0, samples );
  14180. } else {
  14181. _gl.framebufferTexture2D( 36160, 33306, 3553, webglDepthTexture, 0 );
  14182. }
  14183. } else {
  14184. throw new Error( 'Unknown depthTexture format' );
  14185. }
  14186. }
  14187. // Setup GL resources for a non-texture depth buffer
  14188. function setupDepthRenderbuffer( renderTarget ) {
  14189. const renderTargetProperties = properties.get( renderTarget );
  14190. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14191. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  14192. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  14193. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  14194. } else {
  14195. if ( isCube ) {
  14196. renderTargetProperties.__webglDepthbuffer = [];
  14197. for ( let i = 0; i < 6; i ++ ) {
  14198. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer[ i ] );
  14199. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  14200. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  14201. }
  14202. } else {
  14203. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  14204. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  14205. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  14206. }
  14207. }
  14208. state.bindFramebuffer( 36160, null );
  14209. }
  14210. // rebind framebuffer with external textures
  14211. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  14212. const renderTargetProperties = properties.get( renderTarget );
  14213. if ( colorTexture !== undefined ) {
  14214. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, 36064, 3553 );
  14215. }
  14216. if ( depthTexture !== undefined ) {
  14217. setupDepthRenderbuffer( renderTarget );
  14218. }
  14219. }
  14220. // Set up GL resources for the render target
  14221. function setupRenderTarget( renderTarget ) {
  14222. const texture = renderTarget.texture;
  14223. const renderTargetProperties = properties.get( renderTarget );
  14224. const textureProperties = properties.get( texture );
  14225. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14226. if ( renderTarget.isWebGLMultipleRenderTargets !== true ) {
  14227. if ( textureProperties.__webglTexture === undefined ) {
  14228. textureProperties.__webglTexture = _gl.createTexture();
  14229. }
  14230. textureProperties.__version = texture.version;
  14231. info.memory.textures ++;
  14232. }
  14233. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  14234. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14235. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14236. // Setup framebuffer
  14237. if ( isCube ) {
  14238. renderTargetProperties.__webglFramebuffer = [];
  14239. for ( let i = 0; i < 6; i ++ ) {
  14240. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14241. }
  14242. } else {
  14243. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  14244. if ( isMultipleRenderTargets ) {
  14245. if ( capabilities.drawBuffers ) {
  14246. const textures = renderTarget.texture;
  14247. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14248. const attachmentProperties = properties.get( textures[ i ] );
  14249. if ( attachmentProperties.__webglTexture === undefined ) {
  14250. attachmentProperties.__webglTexture = _gl.createTexture();
  14251. info.memory.textures ++;
  14252. }
  14253. }
  14254. } else {
  14255. console.warn( 'THREE.WebGLRenderer: WebGLMultipleRenderTargets can only be used with WebGL2 or WEBGL_draw_buffers extension.' );
  14256. }
  14257. }
  14258. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  14259. const textures = isMultipleRenderTargets ? texture : [ texture ];
  14260. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  14261. renderTargetProperties.__webglColorRenderbuffer = [];
  14262. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  14263. for ( let i = 0; i < textures.length; i ++ ) {
  14264. const texture = textures[ i ];
  14265. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  14266. _gl.bindRenderbuffer( 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14267. const glFormat = utils.convert( texture.format, texture.encoding );
  14268. const glType = utils.convert( texture.type );
  14269. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.encoding );
  14270. const samples = getRenderTargetSamples( renderTarget );
  14271. _gl.renderbufferStorageMultisample( 36161, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  14272. _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14273. }
  14274. _gl.bindRenderbuffer( 36161, null );
  14275. if ( renderTarget.depthBuffer ) {
  14276. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  14277. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  14278. }
  14279. state.bindFramebuffer( 36160, null );
  14280. }
  14281. }
  14282. // Setup color buffer
  14283. if ( isCube ) {
  14284. state.bindTexture( 34067, textureProperties.__webglTexture );
  14285. setTextureParameters( 34067, texture, supportsMips );
  14286. for ( let i = 0; i < 6; i ++ ) {
  14287. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, 36064, 34069 + i );
  14288. }
  14289. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14290. generateMipmap( 34067 );
  14291. }
  14292. state.unbindTexture();
  14293. } else if ( isMultipleRenderTargets ) {
  14294. const textures = renderTarget.texture;
  14295. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14296. const attachment = textures[ i ];
  14297. const attachmentProperties = properties.get( attachment );
  14298. state.bindTexture( 3553, attachmentProperties.__webglTexture );
  14299. setTextureParameters( 3553, attachment, supportsMips );
  14300. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, 36064 + i, 3553 );
  14301. if ( textureNeedsGenerateMipmaps( attachment, supportsMips ) ) {
  14302. generateMipmap( 3553 );
  14303. }
  14304. }
  14305. state.unbindTexture();
  14306. } else {
  14307. let glTextureType = 3553;
  14308. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  14309. if ( isWebGL2 ) {
  14310. glTextureType = renderTarget.isWebGL3DRenderTarget ? 32879 : 35866;
  14311. } else {
  14312. console.error( 'THREE.WebGLTextures: THREE.Data3DTexture and THREE.DataArrayTexture only supported with WebGL2.' );
  14313. }
  14314. }
  14315. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  14316. setTextureParameters( glTextureType, texture, supportsMips );
  14317. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, 36064, glTextureType );
  14318. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14319. generateMipmap( glTextureType );
  14320. }
  14321. state.unbindTexture();
  14322. }
  14323. // Setup depth and stencil buffers
  14324. if ( renderTarget.depthBuffer ) {
  14325. setupDepthRenderbuffer( renderTarget );
  14326. }
  14327. }
  14328. function updateRenderTargetMipmap( renderTarget ) {
  14329. const supportsMips = isPowerOfTwo$1( renderTarget ) || isWebGL2;
  14330. const textures = renderTarget.isWebGLMultipleRenderTargets === true ? renderTarget.texture : [ renderTarget.texture ];
  14331. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  14332. const texture = textures[ i ];
  14333. if ( textureNeedsGenerateMipmaps( texture, supportsMips ) ) {
  14334. const target = renderTarget.isWebGLCubeRenderTarget ? 34067 : 3553;
  14335. const webglTexture = properties.get( texture ).__webglTexture;
  14336. state.bindTexture( target, webglTexture );
  14337. generateMipmap( target );
  14338. state.unbindTexture();
  14339. }
  14340. }
  14341. }
  14342. function updateMultisampleRenderTarget( renderTarget ) {
  14343. if ( ( isWebGL2 && renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  14344. const textures = renderTarget.isWebGLMultipleRenderTargets ? renderTarget.texture : [ renderTarget.texture ];
  14345. const width = renderTarget.width;
  14346. const height = renderTarget.height;
  14347. let mask = 16384;
  14348. const invalidationArray = [];
  14349. const depthStyle = renderTarget.stencilBuffer ? 33306 : 36096;
  14350. const renderTargetProperties = properties.get( renderTarget );
  14351. const isMultipleRenderTargets = ( renderTarget.isWebGLMultipleRenderTargets === true );
  14352. // If MRT we need to remove FBO attachments
  14353. if ( isMultipleRenderTargets ) {
  14354. for ( let i = 0; i < textures.length; i ++ ) {
  14355. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  14356. _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, null );
  14357. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  14358. _gl.framebufferTexture2D( 36009, 36064 + i, 3553, null, 0 );
  14359. }
  14360. }
  14361. state.bindFramebuffer( 36008, renderTargetProperties.__webglMultisampledFramebuffer );
  14362. state.bindFramebuffer( 36009, renderTargetProperties.__webglFramebuffer );
  14363. for ( let i = 0; i < textures.length; i ++ ) {
  14364. invalidationArray.push( 36064 + i );
  14365. if ( renderTarget.depthBuffer ) {
  14366. invalidationArray.push( depthStyle );
  14367. }
  14368. const ignoreDepthValues = ( renderTargetProperties.__ignoreDepthValues !== undefined ) ? renderTargetProperties.__ignoreDepthValues : false;
  14369. if ( ignoreDepthValues === false ) {
  14370. if ( renderTarget.depthBuffer ) mask |= 256;
  14371. if ( renderTarget.stencilBuffer ) mask |= 1024;
  14372. }
  14373. if ( isMultipleRenderTargets ) {
  14374. _gl.framebufferRenderbuffer( 36008, 36064, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14375. }
  14376. if ( ignoreDepthValues === true ) {
  14377. _gl.invalidateFramebuffer( 36008, [ depthStyle ] );
  14378. _gl.invalidateFramebuffer( 36009, [ depthStyle ] );
  14379. }
  14380. if ( isMultipleRenderTargets ) {
  14381. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  14382. _gl.framebufferTexture2D( 36009, 36064, 3553, webglTexture, 0 );
  14383. }
  14384. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, 9728 );
  14385. if ( supportsInvalidateFramebuffer ) {
  14386. _gl.invalidateFramebuffer( 36008, invalidationArray );
  14387. }
  14388. }
  14389. state.bindFramebuffer( 36008, null );
  14390. state.bindFramebuffer( 36009, null );
  14391. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  14392. if ( isMultipleRenderTargets ) {
  14393. for ( let i = 0; i < textures.length; i ++ ) {
  14394. state.bindFramebuffer( 36160, renderTargetProperties.__webglMultisampledFramebuffer );
  14395. _gl.framebufferRenderbuffer( 36160, 36064 + i, 36161, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  14396. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  14397. state.bindFramebuffer( 36160, renderTargetProperties.__webglFramebuffer );
  14398. _gl.framebufferTexture2D( 36009, 36064 + i, 3553, webglTexture, 0 );
  14399. }
  14400. }
  14401. state.bindFramebuffer( 36009, renderTargetProperties.__webglMultisampledFramebuffer );
  14402. }
  14403. }
  14404. function getRenderTargetSamples( renderTarget ) {
  14405. return Math.min( maxSamples, renderTarget.samples );
  14406. }
  14407. function useMultisampledRTT( renderTarget ) {
  14408. const renderTargetProperties = properties.get( renderTarget );
  14409. return isWebGL2 && renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  14410. }
  14411. function updateVideoTexture( texture ) {
  14412. const frame = info.render.frame;
  14413. // Check the last frame we updated the VideoTexture
  14414. if ( _videoTextures.get( texture ) !== frame ) {
  14415. _videoTextures.set( texture, frame );
  14416. texture.update();
  14417. }
  14418. }
  14419. function verifyColorSpace( texture, image ) {
  14420. const encoding = texture.encoding;
  14421. const format = texture.format;
  14422. const type = texture.type;
  14423. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true || texture.format === _SRGBAFormat ) return image;
  14424. if ( encoding !== LinearEncoding ) {
  14425. // sRGB
  14426. if ( encoding === sRGBEncoding ) {
  14427. if ( isWebGL2 === false ) {
  14428. // in WebGL 1, try to use EXT_sRGB extension and unsized formats
  14429. if ( extensions.has( 'EXT_sRGB' ) === true && format === RGBAFormat ) {
  14430. texture.format = _SRGBAFormat;
  14431. // it's not possible to generate mips in WebGL 1 with this extension
  14432. texture.minFilter = LinearFilter;
  14433. texture.generateMipmaps = false;
  14434. } else {
  14435. // slow fallback (CPU decode)
  14436. image = ImageUtils.sRGBToLinear( image );
  14437. }
  14438. } else {
  14439. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  14440. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  14441. console.warn( 'THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  14442. }
  14443. }
  14444. } else {
  14445. console.error( 'THREE.WebGLTextures: Unsupported texture encoding:', encoding );
  14446. }
  14447. }
  14448. return image;
  14449. }
  14450. //
  14451. this.allocateTextureUnit = allocateTextureUnit;
  14452. this.resetTextureUnits = resetTextureUnits;
  14453. this.setTexture2D = setTexture2D;
  14454. this.setTexture2DArray = setTexture2DArray;
  14455. this.setTexture3D = setTexture3D;
  14456. this.setTextureCube = setTextureCube;
  14457. this.rebindTextures = rebindTextures;
  14458. this.setupRenderTarget = setupRenderTarget;
  14459. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  14460. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  14461. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  14462. this.setupFrameBufferTexture = setupFrameBufferTexture;
  14463. this.useMultisampledRTT = useMultisampledRTT;
  14464. }
  14465. function WebGLUtils( gl, extensions, capabilities ) {
  14466. const isWebGL2 = capabilities.isWebGL2;
  14467. function convert( p, encoding = null ) {
  14468. let extension;
  14469. if ( p === UnsignedByteType ) return 5121;
  14470. if ( p === UnsignedShort4444Type ) return 32819;
  14471. if ( p === UnsignedShort5551Type ) return 32820;
  14472. if ( p === ByteType ) return 5120;
  14473. if ( p === ShortType ) return 5122;
  14474. if ( p === UnsignedShortType ) return 5123;
  14475. if ( p === IntType ) return 5124;
  14476. if ( p === UnsignedIntType ) return 5125;
  14477. if ( p === FloatType ) return 5126;
  14478. if ( p === HalfFloatType ) {
  14479. if ( isWebGL2 ) return 5131;
  14480. extension = extensions.get( 'OES_texture_half_float' );
  14481. if ( extension !== null ) {
  14482. return extension.HALF_FLOAT_OES;
  14483. } else {
  14484. return null;
  14485. }
  14486. }
  14487. if ( p === AlphaFormat ) return 6406;
  14488. if ( p === RGBAFormat ) return 6408;
  14489. if ( p === LuminanceFormat ) return 6409;
  14490. if ( p === LuminanceAlphaFormat ) return 6410;
  14491. if ( p === DepthFormat ) return 6402;
  14492. if ( p === DepthStencilFormat ) return 34041;
  14493. if ( p === RedFormat ) return 6403;
  14494. // @deprecated since r137
  14495. if ( p === RGBFormat ) {
  14496. console.warn( 'THREE.WebGLRenderer: THREE.RGBFormat has been removed. Use THREE.RGBAFormat instead. https://github.com/mrdoob/three.js/pull/23228' );
  14497. return 6408;
  14498. }
  14499. // WebGL 1 sRGB fallback
  14500. if ( p === _SRGBAFormat ) {
  14501. extension = extensions.get( 'EXT_sRGB' );
  14502. if ( extension !== null ) {
  14503. return extension.SRGB_ALPHA_EXT;
  14504. } else {
  14505. return null;
  14506. }
  14507. }
  14508. // WebGL2 formats.
  14509. if ( p === RedIntegerFormat ) return 36244;
  14510. if ( p === RGFormat ) return 33319;
  14511. if ( p === RGIntegerFormat ) return 33320;
  14512. if ( p === RGBAIntegerFormat ) return 36249;
  14513. // S3TC
  14514. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  14515. if ( encoding === sRGBEncoding ) {
  14516. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  14517. if ( extension !== null ) {
  14518. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  14519. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  14520. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  14521. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  14522. } else {
  14523. return null;
  14524. }
  14525. } else {
  14526. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  14527. if ( extension !== null ) {
  14528. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14529. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14530. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14531. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14532. } else {
  14533. return null;
  14534. }
  14535. }
  14536. }
  14537. // PVRTC
  14538. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  14539. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  14540. if ( extension !== null ) {
  14541. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  14542. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  14543. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  14544. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  14545. } else {
  14546. return null;
  14547. }
  14548. }
  14549. // ETC1
  14550. if ( p === RGB_ETC1_Format ) {
  14551. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  14552. if ( extension !== null ) {
  14553. return extension.COMPRESSED_RGB_ETC1_WEBGL;
  14554. } else {
  14555. return null;
  14556. }
  14557. }
  14558. // ETC2
  14559. if ( p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  14560. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  14561. if ( extension !== null ) {
  14562. if ( p === RGB_ETC2_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  14563. if ( p === RGBA_ETC2_EAC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  14564. } else {
  14565. return null;
  14566. }
  14567. }
  14568. // ASTC
  14569. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  14570. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  14571. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  14572. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  14573. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  14574. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  14575. if ( extension !== null ) {
  14576. if ( p === RGBA_ASTC_4x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  14577. if ( p === RGBA_ASTC_5x4_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  14578. if ( p === RGBA_ASTC_5x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  14579. if ( p === RGBA_ASTC_6x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  14580. if ( p === RGBA_ASTC_6x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  14581. if ( p === RGBA_ASTC_8x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  14582. if ( p === RGBA_ASTC_8x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  14583. if ( p === RGBA_ASTC_8x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  14584. if ( p === RGBA_ASTC_10x5_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  14585. if ( p === RGBA_ASTC_10x6_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  14586. if ( p === RGBA_ASTC_10x8_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  14587. if ( p === RGBA_ASTC_10x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  14588. if ( p === RGBA_ASTC_12x10_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  14589. if ( p === RGBA_ASTC_12x12_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  14590. } else {
  14591. return null;
  14592. }
  14593. }
  14594. // BPTC
  14595. if ( p === RGBA_BPTC_Format ) {
  14596. extension = extensions.get( 'EXT_texture_compression_bptc' );
  14597. if ( extension !== null ) {
  14598. if ( p === RGBA_BPTC_Format ) return ( encoding === sRGBEncoding ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  14599. } else {
  14600. return null;
  14601. }
  14602. }
  14603. //
  14604. if ( p === UnsignedInt248Type ) {
  14605. if ( isWebGL2 ) return 34042;
  14606. extension = extensions.get( 'WEBGL_depth_texture' );
  14607. if ( extension !== null ) {
  14608. return extension.UNSIGNED_INT_24_8_WEBGL;
  14609. } else {
  14610. return null;
  14611. }
  14612. }
  14613. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  14614. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  14615. }
  14616. return { convert: convert };
  14617. }
  14618. class ArrayCamera extends PerspectiveCamera {
  14619. constructor( array = [] ) {
  14620. super();
  14621. this.isArrayCamera = true;
  14622. this.cameras = array;
  14623. }
  14624. }
  14625. class Group extends Object3D {
  14626. constructor() {
  14627. super();
  14628. this.isGroup = true;
  14629. this.type = 'Group';
  14630. }
  14631. }
  14632. const _moveEvent = { type: 'move' };
  14633. class WebXRController {
  14634. constructor() {
  14635. this._targetRay = null;
  14636. this._grip = null;
  14637. this._hand = null;
  14638. }
  14639. getHandSpace() {
  14640. if ( this._hand === null ) {
  14641. this._hand = new Group();
  14642. this._hand.matrixAutoUpdate = false;
  14643. this._hand.visible = false;
  14644. this._hand.joints = {};
  14645. this._hand.inputState = { pinching: false };
  14646. }
  14647. return this._hand;
  14648. }
  14649. getTargetRaySpace() {
  14650. if ( this._targetRay === null ) {
  14651. this._targetRay = new Group();
  14652. this._targetRay.matrixAutoUpdate = false;
  14653. this._targetRay.visible = false;
  14654. this._targetRay.hasLinearVelocity = false;
  14655. this._targetRay.linearVelocity = new Vector3();
  14656. this._targetRay.hasAngularVelocity = false;
  14657. this._targetRay.angularVelocity = new Vector3();
  14658. }
  14659. return this._targetRay;
  14660. }
  14661. getGripSpace() {
  14662. if ( this._grip === null ) {
  14663. this._grip = new Group();
  14664. this._grip.matrixAutoUpdate = false;
  14665. this._grip.visible = false;
  14666. this._grip.hasLinearVelocity = false;
  14667. this._grip.linearVelocity = new Vector3();
  14668. this._grip.hasAngularVelocity = false;
  14669. this._grip.angularVelocity = new Vector3();
  14670. }
  14671. return this._grip;
  14672. }
  14673. dispatchEvent( event ) {
  14674. if ( this._targetRay !== null ) {
  14675. this._targetRay.dispatchEvent( event );
  14676. }
  14677. if ( this._grip !== null ) {
  14678. this._grip.dispatchEvent( event );
  14679. }
  14680. if ( this._hand !== null ) {
  14681. this._hand.dispatchEvent( event );
  14682. }
  14683. return this;
  14684. }
  14685. disconnect( inputSource ) {
  14686. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  14687. if ( this._targetRay !== null ) {
  14688. this._targetRay.visible = false;
  14689. }
  14690. if ( this._grip !== null ) {
  14691. this._grip.visible = false;
  14692. }
  14693. if ( this._hand !== null ) {
  14694. this._hand.visible = false;
  14695. }
  14696. return this;
  14697. }
  14698. update( inputSource, frame, referenceSpace ) {
  14699. let inputPose = null;
  14700. let gripPose = null;
  14701. let handPose = null;
  14702. const targetRay = this._targetRay;
  14703. const grip = this._grip;
  14704. const hand = this._hand;
  14705. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  14706. if ( hand && inputSource.hand ) {
  14707. handPose = true;
  14708. for ( const inputjoint of inputSource.hand.values() ) {
  14709. // Update the joints groups with the XRJoint poses
  14710. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  14711. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  14712. // The transform of this joint will be updated with the joint pose on each frame
  14713. const joint = new Group();
  14714. joint.matrixAutoUpdate = false;
  14715. joint.visible = false;
  14716. hand.joints[ inputjoint.jointName ] = joint;
  14717. // ??
  14718. hand.add( joint );
  14719. }
  14720. const joint = hand.joints[ inputjoint.jointName ];
  14721. if ( jointPose !== null ) {
  14722. joint.matrix.fromArray( jointPose.transform.matrix );
  14723. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  14724. joint.jointRadius = jointPose.radius;
  14725. }
  14726. joint.visible = jointPose !== null;
  14727. }
  14728. // Custom events
  14729. // Check pinchz
  14730. const indexTip = hand.joints[ 'index-finger-tip' ];
  14731. const thumbTip = hand.joints[ 'thumb-tip' ];
  14732. const distance = indexTip.position.distanceTo( thumbTip.position );
  14733. const distanceToPinch = 0.02;
  14734. const threshold = 0.005;
  14735. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  14736. hand.inputState.pinching = false;
  14737. this.dispatchEvent( {
  14738. type: 'pinchend',
  14739. handedness: inputSource.handedness,
  14740. target: this
  14741. } );
  14742. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  14743. hand.inputState.pinching = true;
  14744. this.dispatchEvent( {
  14745. type: 'pinchstart',
  14746. handedness: inputSource.handedness,
  14747. target: this
  14748. } );
  14749. }
  14750. } else {
  14751. if ( grip !== null && inputSource.gripSpace ) {
  14752. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  14753. if ( gripPose !== null ) {
  14754. grip.matrix.fromArray( gripPose.transform.matrix );
  14755. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  14756. if ( gripPose.linearVelocity ) {
  14757. grip.hasLinearVelocity = true;
  14758. grip.linearVelocity.copy( gripPose.linearVelocity );
  14759. } else {
  14760. grip.hasLinearVelocity = false;
  14761. }
  14762. if ( gripPose.angularVelocity ) {
  14763. grip.hasAngularVelocity = true;
  14764. grip.angularVelocity.copy( gripPose.angularVelocity );
  14765. } else {
  14766. grip.hasAngularVelocity = false;
  14767. }
  14768. }
  14769. }
  14770. }
  14771. if ( targetRay !== null ) {
  14772. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  14773. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  14774. if ( inputPose === null && gripPose !== null ) {
  14775. inputPose = gripPose;
  14776. }
  14777. if ( inputPose !== null ) {
  14778. targetRay.matrix.fromArray( inputPose.transform.matrix );
  14779. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  14780. if ( inputPose.linearVelocity ) {
  14781. targetRay.hasLinearVelocity = true;
  14782. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  14783. } else {
  14784. targetRay.hasLinearVelocity = false;
  14785. }
  14786. if ( inputPose.angularVelocity ) {
  14787. targetRay.hasAngularVelocity = true;
  14788. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  14789. } else {
  14790. targetRay.hasAngularVelocity = false;
  14791. }
  14792. this.dispatchEvent( _moveEvent );
  14793. }
  14794. }
  14795. }
  14796. if ( targetRay !== null ) {
  14797. targetRay.visible = ( inputPose !== null );
  14798. }
  14799. if ( grip !== null ) {
  14800. grip.visible = ( gripPose !== null );
  14801. }
  14802. if ( hand !== null ) {
  14803. hand.visible = ( handPose !== null );
  14804. }
  14805. return this;
  14806. }
  14807. }
  14808. class DepthTexture extends Texture {
  14809. constructor( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  14810. format = format !== undefined ? format : DepthFormat;
  14811. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  14812. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  14813. }
  14814. if ( type === undefined && format === DepthFormat ) type = UnsignedIntType;
  14815. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  14816. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  14817. this.isDepthTexture = true;
  14818. this.image = { width: width, height: height };
  14819. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  14820. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  14821. this.flipY = false;
  14822. this.generateMipmaps = false;
  14823. }
  14824. }
  14825. class WebXRManager extends EventDispatcher {
  14826. constructor( renderer, gl ) {
  14827. super();
  14828. const scope = this;
  14829. let session = null;
  14830. let framebufferScaleFactor = 1.0;
  14831. let referenceSpace = null;
  14832. let referenceSpaceType = 'local-floor';
  14833. let customReferenceSpace = null;
  14834. let pose = null;
  14835. let glBinding = null;
  14836. let glProjLayer = null;
  14837. let glBaseLayer = null;
  14838. let xrFrame = null;
  14839. const attributes = gl.getContextAttributes();
  14840. let initialRenderTarget = null;
  14841. let newRenderTarget = null;
  14842. const controllers = [];
  14843. const controllerInputSources = [];
  14844. //
  14845. const cameraL = new PerspectiveCamera();
  14846. cameraL.layers.enable( 1 );
  14847. cameraL.viewport = new Vector4();
  14848. const cameraR = new PerspectiveCamera();
  14849. cameraR.layers.enable( 2 );
  14850. cameraR.viewport = new Vector4();
  14851. const cameras = [ cameraL, cameraR ];
  14852. const cameraVR = new ArrayCamera();
  14853. cameraVR.layers.enable( 1 );
  14854. cameraVR.layers.enable( 2 );
  14855. let _currentDepthNear = null;
  14856. let _currentDepthFar = null;
  14857. //
  14858. this.cameraAutoUpdate = true;
  14859. this.enabled = false;
  14860. this.isPresenting = false;
  14861. this.getController = function ( index ) {
  14862. let controller = controllers[ index ];
  14863. if ( controller === undefined ) {
  14864. controller = new WebXRController();
  14865. controllers[ index ] = controller;
  14866. }
  14867. return controller.getTargetRaySpace();
  14868. };
  14869. this.getControllerGrip = function ( index ) {
  14870. let controller = controllers[ index ];
  14871. if ( controller === undefined ) {
  14872. controller = new WebXRController();
  14873. controllers[ index ] = controller;
  14874. }
  14875. return controller.getGripSpace();
  14876. };
  14877. this.getHand = function ( index ) {
  14878. let controller = controllers[ index ];
  14879. if ( controller === undefined ) {
  14880. controller = new WebXRController();
  14881. controllers[ index ] = controller;
  14882. }
  14883. return controller.getHandSpace();
  14884. };
  14885. //
  14886. function onSessionEvent( event ) {
  14887. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  14888. if ( controllerIndex === - 1 ) {
  14889. return;
  14890. }
  14891. const controller = controllers[ controllerIndex ];
  14892. if ( controller !== undefined ) {
  14893. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  14894. }
  14895. }
  14896. function onSessionEnd() {
  14897. session.removeEventListener( 'select', onSessionEvent );
  14898. session.removeEventListener( 'selectstart', onSessionEvent );
  14899. session.removeEventListener( 'selectend', onSessionEvent );
  14900. session.removeEventListener( 'squeeze', onSessionEvent );
  14901. session.removeEventListener( 'squeezestart', onSessionEvent );
  14902. session.removeEventListener( 'squeezeend', onSessionEvent );
  14903. session.removeEventListener( 'end', onSessionEnd );
  14904. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  14905. for ( let i = 0; i < controllers.length; i ++ ) {
  14906. const inputSource = controllerInputSources[ i ];
  14907. if ( inputSource === null ) continue;
  14908. controllerInputSources[ i ] = null;
  14909. controllers[ i ].disconnect( inputSource );
  14910. }
  14911. _currentDepthNear = null;
  14912. _currentDepthFar = null;
  14913. // restore framebuffer/rendering state
  14914. renderer.setRenderTarget( initialRenderTarget );
  14915. glBaseLayer = null;
  14916. glProjLayer = null;
  14917. glBinding = null;
  14918. session = null;
  14919. newRenderTarget = null;
  14920. //
  14921. animation.stop();
  14922. scope.isPresenting = false;
  14923. scope.dispatchEvent( { type: 'sessionend' } );
  14924. }
  14925. this.setFramebufferScaleFactor = function ( value ) {
  14926. framebufferScaleFactor = value;
  14927. if ( scope.isPresenting === true ) {
  14928. console.warn( 'THREE.WebXRManager: Cannot change framebuffer scale while presenting.' );
  14929. }
  14930. };
  14931. this.setReferenceSpaceType = function ( value ) {
  14932. referenceSpaceType = value;
  14933. if ( scope.isPresenting === true ) {
  14934. console.warn( 'THREE.WebXRManager: Cannot change reference space type while presenting.' );
  14935. }
  14936. };
  14937. this.getReferenceSpace = function () {
  14938. return customReferenceSpace || referenceSpace;
  14939. };
  14940. this.setReferenceSpace = function ( space ) {
  14941. customReferenceSpace = space;
  14942. };
  14943. this.getBaseLayer = function () {
  14944. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  14945. };
  14946. this.getBinding = function () {
  14947. return glBinding;
  14948. };
  14949. this.getFrame = function () {
  14950. return xrFrame;
  14951. };
  14952. this.getSession = function () {
  14953. return session;
  14954. };
  14955. this.setSession = async function ( value ) {
  14956. session = value;
  14957. if ( session !== null ) {
  14958. initialRenderTarget = renderer.getRenderTarget();
  14959. session.addEventListener( 'select', onSessionEvent );
  14960. session.addEventListener( 'selectstart', onSessionEvent );
  14961. session.addEventListener( 'selectend', onSessionEvent );
  14962. session.addEventListener( 'squeeze', onSessionEvent );
  14963. session.addEventListener( 'squeezestart', onSessionEvent );
  14964. session.addEventListener( 'squeezeend', onSessionEvent );
  14965. session.addEventListener( 'end', onSessionEnd );
  14966. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  14967. if ( attributes.xrCompatible !== true ) {
  14968. await gl.makeXRCompatible();
  14969. }
  14970. if ( ( session.renderState.layers === undefined ) || ( renderer.capabilities.isWebGL2 === false ) ) {
  14971. const layerInit = {
  14972. antialias: ( session.renderState.layers === undefined ) ? attributes.antialias : true,
  14973. alpha: attributes.alpha,
  14974. depth: attributes.depth,
  14975. stencil: attributes.stencil,
  14976. framebufferScaleFactor: framebufferScaleFactor
  14977. };
  14978. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  14979. session.updateRenderState( { baseLayer: glBaseLayer } );
  14980. newRenderTarget = new WebGLRenderTarget(
  14981. glBaseLayer.framebufferWidth,
  14982. glBaseLayer.framebufferHeight,
  14983. {
  14984. format: RGBAFormat,
  14985. type: UnsignedByteType,
  14986. encoding: renderer.outputEncoding,
  14987. stencilBuffer: attributes.stencil
  14988. }
  14989. );
  14990. } else {
  14991. let depthFormat = null;
  14992. let depthType = null;
  14993. let glDepthFormat = null;
  14994. if ( attributes.depth ) {
  14995. glDepthFormat = attributes.stencil ? 35056 : 33190;
  14996. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  14997. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  14998. }
  14999. const projectionlayerInit = {
  15000. colorFormat: 32856,
  15001. depthFormat: glDepthFormat,
  15002. scaleFactor: framebufferScaleFactor
  15003. };
  15004. glBinding = new XRWebGLBinding( session, gl );
  15005. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  15006. session.updateRenderState( { layers: [ glProjLayer ] } );
  15007. newRenderTarget = new WebGLRenderTarget(
  15008. glProjLayer.textureWidth,
  15009. glProjLayer.textureHeight,
  15010. {
  15011. format: RGBAFormat,
  15012. type: UnsignedByteType,
  15013. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  15014. stencilBuffer: attributes.stencil,
  15015. encoding: renderer.outputEncoding,
  15016. samples: attributes.antialias ? 4 : 0
  15017. } );
  15018. const renderTargetProperties = renderer.properties.get( newRenderTarget );
  15019. renderTargetProperties.__ignoreDepthValues = glProjLayer.ignoreDepthValues;
  15020. }
  15021. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  15022. // Set foveation to maximum.
  15023. this.setFoveation( 1.0 );
  15024. customReferenceSpace = null;
  15025. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  15026. animation.setContext( session );
  15027. animation.start();
  15028. scope.isPresenting = true;
  15029. scope.dispatchEvent( { type: 'sessionstart' } );
  15030. }
  15031. };
  15032. function onInputSourcesChange( event ) {
  15033. // Notify disconnected
  15034. for ( let i = 0; i < event.removed.length; i ++ ) {
  15035. const inputSource = event.removed[ i ];
  15036. const index = controllerInputSources.indexOf( inputSource );
  15037. if ( index >= 0 ) {
  15038. controllerInputSources[ index ] = null;
  15039. controllers[ index ].dispatchEvent( { type: 'disconnected', data: inputSource } );
  15040. }
  15041. }
  15042. // Notify connected
  15043. for ( let i = 0; i < event.added.length; i ++ ) {
  15044. const inputSource = event.added[ i ];
  15045. let controllerIndex = controllerInputSources.indexOf( inputSource );
  15046. if ( controllerIndex === - 1 ) {
  15047. // Assign input source a controller that currently has no input source
  15048. for ( let i = 0; i < controllers.length; i ++ ) {
  15049. if ( i >= controllerInputSources.length ) {
  15050. controllerInputSources.push( inputSource );
  15051. controllerIndex = i;
  15052. break;
  15053. } else if ( controllerInputSources[ i ] === null ) {
  15054. controllerInputSources[ i ] = inputSource;
  15055. controllerIndex = i;
  15056. break;
  15057. }
  15058. }
  15059. // If all controllers do currently receive input we ignore new ones
  15060. if ( controllerIndex === - 1 ) break;
  15061. }
  15062. const controller = controllers[ controllerIndex ];
  15063. if ( controller ) {
  15064. controller.dispatchEvent( { type: 'connected', data: inputSource } );
  15065. }
  15066. }
  15067. }
  15068. //
  15069. const cameraLPos = new Vector3();
  15070. const cameraRPos = new Vector3();
  15071. /**
  15072. * Assumes 2 cameras that are parallel and share an X-axis, and that
  15073. * the cameras' projection and world matrices have already been set.
  15074. * And that near and far planes are identical for both cameras.
  15075. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  15076. */
  15077. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  15078. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  15079. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  15080. const ipd = cameraLPos.distanceTo( cameraRPos );
  15081. const projL = cameraL.projectionMatrix.elements;
  15082. const projR = cameraR.projectionMatrix.elements;
  15083. // VR systems will have identical far and near planes, and
  15084. // most likely identical top and bottom frustum extents.
  15085. // Use the left camera for these values.
  15086. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  15087. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  15088. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  15089. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  15090. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  15091. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  15092. const left = near * leftFov;
  15093. const right = near * rightFov;
  15094. // Calculate the new camera's position offset from the
  15095. // left camera. xOffset should be roughly half `ipd`.
  15096. const zOffset = ipd / ( - leftFov + rightFov );
  15097. const xOffset = zOffset * - leftFov;
  15098. // TODO: Better way to apply this offset?
  15099. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  15100. camera.translateX( xOffset );
  15101. camera.translateZ( zOffset );
  15102. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  15103. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15104. // Find the union of the frustum values of the cameras and scale
  15105. // the values so that the near plane's position does not change in world space,
  15106. // although must now be relative to the new union camera.
  15107. const near2 = near + zOffset;
  15108. const far2 = far + zOffset;
  15109. const left2 = left - xOffset;
  15110. const right2 = right + ( ipd - xOffset );
  15111. const top2 = topFov * far / far2 * near2;
  15112. const bottom2 = bottomFov * far / far2 * near2;
  15113. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  15114. }
  15115. function updateCamera( camera, parent ) {
  15116. if ( parent === null ) {
  15117. camera.matrixWorld.copy( camera.matrix );
  15118. } else {
  15119. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  15120. }
  15121. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  15122. }
  15123. this.updateCamera = function ( camera ) {
  15124. if ( session === null ) return;
  15125. cameraVR.near = cameraR.near = cameraL.near = camera.near;
  15126. cameraVR.far = cameraR.far = cameraL.far = camera.far;
  15127. if ( _currentDepthNear !== cameraVR.near || _currentDepthFar !== cameraVR.far ) {
  15128. // Note that the new renderState won't apply until the next frame. See #18320
  15129. session.updateRenderState( {
  15130. depthNear: cameraVR.near,
  15131. depthFar: cameraVR.far
  15132. } );
  15133. _currentDepthNear = cameraVR.near;
  15134. _currentDepthFar = cameraVR.far;
  15135. }
  15136. const parent = camera.parent;
  15137. const cameras = cameraVR.cameras;
  15138. updateCamera( cameraVR, parent );
  15139. for ( let i = 0; i < cameras.length; i ++ ) {
  15140. updateCamera( cameras[ i ], parent );
  15141. }
  15142. cameraVR.matrixWorld.decompose( cameraVR.position, cameraVR.quaternion, cameraVR.scale );
  15143. // update user camera and its children
  15144. camera.matrix.copy( cameraVR.matrix );
  15145. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  15146. const children = camera.children;
  15147. for ( let i = 0, l = children.length; i < l; i ++ ) {
  15148. children[ i ].updateMatrixWorld( true );
  15149. }
  15150. // update projection matrix for proper view frustum culling
  15151. if ( cameras.length === 2 ) {
  15152. setProjectionFromUnion( cameraVR, cameraL, cameraR );
  15153. } else {
  15154. // assume single camera setup (AR)
  15155. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  15156. }
  15157. };
  15158. this.getCamera = function () {
  15159. return cameraVR;
  15160. };
  15161. this.getFoveation = function () {
  15162. if ( glProjLayer !== null ) {
  15163. return glProjLayer.fixedFoveation;
  15164. }
  15165. if ( glBaseLayer !== null ) {
  15166. return glBaseLayer.fixedFoveation;
  15167. }
  15168. return undefined;
  15169. };
  15170. this.setFoveation = function ( foveation ) {
  15171. // 0 = no foveation = full resolution
  15172. // 1 = maximum foveation = the edges render at lower resolution
  15173. if ( glProjLayer !== null ) {
  15174. glProjLayer.fixedFoveation = foveation;
  15175. }
  15176. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  15177. glBaseLayer.fixedFoveation = foveation;
  15178. }
  15179. };
  15180. // Animation Loop
  15181. let onAnimationFrameCallback = null;
  15182. function onAnimationFrame( time, frame ) {
  15183. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  15184. xrFrame = frame;
  15185. if ( pose !== null ) {
  15186. const views = pose.views;
  15187. if ( glBaseLayer !== null ) {
  15188. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  15189. renderer.setRenderTarget( newRenderTarget );
  15190. }
  15191. let cameraVRNeedsUpdate = false;
  15192. // check if it's necessary to rebuild cameraVR's camera list
  15193. if ( views.length !== cameraVR.cameras.length ) {
  15194. cameraVR.cameras.length = 0;
  15195. cameraVRNeedsUpdate = true;
  15196. }
  15197. for ( let i = 0; i < views.length; i ++ ) {
  15198. const view = views[ i ];
  15199. let viewport = null;
  15200. if ( glBaseLayer !== null ) {
  15201. viewport = glBaseLayer.getViewport( view );
  15202. } else {
  15203. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  15204. viewport = glSubImage.viewport;
  15205. // For side-by-side projection, we only produce a single texture for both eyes.
  15206. if ( i === 0 ) {
  15207. renderer.setRenderTargetTextures(
  15208. newRenderTarget,
  15209. glSubImage.colorTexture,
  15210. glProjLayer.ignoreDepthValues ? undefined : glSubImage.depthStencilTexture );
  15211. renderer.setRenderTarget( newRenderTarget );
  15212. }
  15213. }
  15214. let camera = cameras[ i ];
  15215. if ( camera === undefined ) {
  15216. camera = new PerspectiveCamera();
  15217. camera.layers.enable( i );
  15218. camera.viewport = new Vector4();
  15219. cameras[ i ] = camera;
  15220. }
  15221. camera.matrix.fromArray( view.transform.matrix );
  15222. camera.projectionMatrix.fromArray( view.projectionMatrix );
  15223. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  15224. if ( i === 0 ) {
  15225. cameraVR.matrix.copy( camera.matrix );
  15226. }
  15227. if ( cameraVRNeedsUpdate === true ) {
  15228. cameraVR.cameras.push( camera );
  15229. }
  15230. }
  15231. }
  15232. //
  15233. for ( let i = 0; i < controllers.length; i ++ ) {
  15234. const inputSource = controllerInputSources[ i ];
  15235. const controller = controllers[ i ];
  15236. if ( inputSource !== null && controller !== undefined ) {
  15237. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  15238. }
  15239. }
  15240. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  15241. xrFrame = null;
  15242. }
  15243. const animation = new WebGLAnimation();
  15244. animation.setAnimationLoop( onAnimationFrame );
  15245. this.setAnimationLoop = function ( callback ) {
  15246. onAnimationFrameCallback = callback;
  15247. };
  15248. this.dispose = function () {};
  15249. }
  15250. }
  15251. function WebGLMaterials( renderer, properties ) {
  15252. function refreshFogUniforms( uniforms, fog ) {
  15253. uniforms.fogColor.value.copy( fog.color );
  15254. if ( fog.isFog ) {
  15255. uniforms.fogNear.value = fog.near;
  15256. uniforms.fogFar.value = fog.far;
  15257. } else if ( fog.isFogExp2 ) {
  15258. uniforms.fogDensity.value = fog.density;
  15259. }
  15260. }
  15261. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  15262. if ( material.isMeshBasicMaterial ) {
  15263. refreshUniformsCommon( uniforms, material );
  15264. } else if ( material.isMeshLambertMaterial ) {
  15265. refreshUniformsCommon( uniforms, material );
  15266. } else if ( material.isMeshToonMaterial ) {
  15267. refreshUniformsCommon( uniforms, material );
  15268. refreshUniformsToon( uniforms, material );
  15269. } else if ( material.isMeshPhongMaterial ) {
  15270. refreshUniformsCommon( uniforms, material );
  15271. refreshUniformsPhong( uniforms, material );
  15272. } else if ( material.isMeshStandardMaterial ) {
  15273. refreshUniformsCommon( uniforms, material );
  15274. refreshUniformsStandard( uniforms, material );
  15275. if ( material.isMeshPhysicalMaterial ) {
  15276. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  15277. }
  15278. } else if ( material.isMeshMatcapMaterial ) {
  15279. refreshUniformsCommon( uniforms, material );
  15280. refreshUniformsMatcap( uniforms, material );
  15281. } else if ( material.isMeshDepthMaterial ) {
  15282. refreshUniformsCommon( uniforms, material );
  15283. } else if ( material.isMeshDistanceMaterial ) {
  15284. refreshUniformsCommon( uniforms, material );
  15285. refreshUniformsDistance( uniforms, material );
  15286. } else if ( material.isMeshNormalMaterial ) {
  15287. refreshUniformsCommon( uniforms, material );
  15288. } else if ( material.isLineBasicMaterial ) {
  15289. refreshUniformsLine( uniforms, material );
  15290. if ( material.isLineDashedMaterial ) {
  15291. refreshUniformsDash( uniforms, material );
  15292. }
  15293. } else if ( material.isPointsMaterial ) {
  15294. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  15295. } else if ( material.isSpriteMaterial ) {
  15296. refreshUniformsSprites( uniforms, material );
  15297. } else if ( material.isShadowMaterial ) {
  15298. uniforms.color.value.copy( material.color );
  15299. uniforms.opacity.value = material.opacity;
  15300. } else if ( material.isShaderMaterial ) {
  15301. material.uniformsNeedUpdate = false; // #15581
  15302. }
  15303. }
  15304. function refreshUniformsCommon( uniforms, material ) {
  15305. uniforms.opacity.value = material.opacity;
  15306. if ( material.color ) {
  15307. uniforms.diffuse.value.copy( material.color );
  15308. }
  15309. if ( material.emissive ) {
  15310. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  15311. }
  15312. if ( material.map ) {
  15313. uniforms.map.value = material.map;
  15314. }
  15315. if ( material.alphaMap ) {
  15316. uniforms.alphaMap.value = material.alphaMap;
  15317. }
  15318. if ( material.bumpMap ) {
  15319. uniforms.bumpMap.value = material.bumpMap;
  15320. uniforms.bumpScale.value = material.bumpScale;
  15321. if ( material.side === BackSide ) uniforms.bumpScale.value *= - 1;
  15322. }
  15323. if ( material.displacementMap ) {
  15324. uniforms.displacementMap.value = material.displacementMap;
  15325. uniforms.displacementScale.value = material.displacementScale;
  15326. uniforms.displacementBias.value = material.displacementBias;
  15327. }
  15328. if ( material.emissiveMap ) {
  15329. uniforms.emissiveMap.value = material.emissiveMap;
  15330. }
  15331. if ( material.normalMap ) {
  15332. uniforms.normalMap.value = material.normalMap;
  15333. uniforms.normalScale.value.copy( material.normalScale );
  15334. if ( material.side === BackSide ) uniforms.normalScale.value.negate();
  15335. }
  15336. if ( material.specularMap ) {
  15337. uniforms.specularMap.value = material.specularMap;
  15338. }
  15339. if ( material.alphaTest > 0 ) {
  15340. uniforms.alphaTest.value = material.alphaTest;
  15341. }
  15342. const envMap = properties.get( material ).envMap;
  15343. if ( envMap ) {
  15344. uniforms.envMap.value = envMap;
  15345. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  15346. uniforms.reflectivity.value = material.reflectivity;
  15347. uniforms.ior.value = material.ior;
  15348. uniforms.refractionRatio.value = material.refractionRatio;
  15349. }
  15350. if ( material.lightMap ) {
  15351. uniforms.lightMap.value = material.lightMap;
  15352. // artist-friendly light intensity scaling factor
  15353. const scaleFactor = ( renderer.physicallyCorrectLights !== true ) ? Math.PI : 1;
  15354. uniforms.lightMapIntensity.value = material.lightMapIntensity * scaleFactor;
  15355. }
  15356. if ( material.aoMap ) {
  15357. uniforms.aoMap.value = material.aoMap;
  15358. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15359. }
  15360. // uv repeat and offset setting priorities
  15361. // 1. color map
  15362. // 2. specular map
  15363. // 3. displacementMap map
  15364. // 4. normal map
  15365. // 5. bump map
  15366. // 6. roughnessMap map
  15367. // 7. metalnessMap map
  15368. // 8. alphaMap map
  15369. // 9. emissiveMap map
  15370. // 10. clearcoat map
  15371. // 11. clearcoat normal map
  15372. // 12. clearcoat roughnessMap map
  15373. // 13. iridescence map
  15374. // 14. iridescence thickness map
  15375. // 15. specular intensity map
  15376. // 16. specular tint map
  15377. // 17. transmission map
  15378. // 18. thickness map
  15379. let uvScaleMap;
  15380. if ( material.map ) {
  15381. uvScaleMap = material.map;
  15382. } else if ( material.specularMap ) {
  15383. uvScaleMap = material.specularMap;
  15384. } else if ( material.displacementMap ) {
  15385. uvScaleMap = material.displacementMap;
  15386. } else if ( material.normalMap ) {
  15387. uvScaleMap = material.normalMap;
  15388. } else if ( material.bumpMap ) {
  15389. uvScaleMap = material.bumpMap;
  15390. } else if ( material.roughnessMap ) {
  15391. uvScaleMap = material.roughnessMap;
  15392. } else if ( material.metalnessMap ) {
  15393. uvScaleMap = material.metalnessMap;
  15394. } else if ( material.alphaMap ) {
  15395. uvScaleMap = material.alphaMap;
  15396. } else if ( material.emissiveMap ) {
  15397. uvScaleMap = material.emissiveMap;
  15398. } else if ( material.clearcoatMap ) {
  15399. uvScaleMap = material.clearcoatMap;
  15400. } else if ( material.clearcoatNormalMap ) {
  15401. uvScaleMap = material.clearcoatNormalMap;
  15402. } else if ( material.clearcoatRoughnessMap ) {
  15403. uvScaleMap = material.clearcoatRoughnessMap;
  15404. } else if ( material.iridescenceMap ) {
  15405. uvScaleMap = material.iridescenceMap;
  15406. } else if ( material.iridescenceThicknessMap ) {
  15407. uvScaleMap = material.iridescenceThicknessMap;
  15408. } else if ( material.specularIntensityMap ) {
  15409. uvScaleMap = material.specularIntensityMap;
  15410. } else if ( material.specularColorMap ) {
  15411. uvScaleMap = material.specularColorMap;
  15412. } else if ( material.transmissionMap ) {
  15413. uvScaleMap = material.transmissionMap;
  15414. } else if ( material.thicknessMap ) {
  15415. uvScaleMap = material.thicknessMap;
  15416. } else if ( material.sheenColorMap ) {
  15417. uvScaleMap = material.sheenColorMap;
  15418. } else if ( material.sheenRoughnessMap ) {
  15419. uvScaleMap = material.sheenRoughnessMap;
  15420. }
  15421. if ( uvScaleMap !== undefined ) {
  15422. // backwards compatibility
  15423. if ( uvScaleMap.isWebGLRenderTarget ) {
  15424. uvScaleMap = uvScaleMap.texture;
  15425. }
  15426. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15427. uvScaleMap.updateMatrix();
  15428. }
  15429. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15430. }
  15431. // uv repeat and offset setting priorities for uv2
  15432. // 1. ao map
  15433. // 2. light map
  15434. let uv2ScaleMap;
  15435. if ( material.aoMap ) {
  15436. uv2ScaleMap = material.aoMap;
  15437. } else if ( material.lightMap ) {
  15438. uv2ScaleMap = material.lightMap;
  15439. }
  15440. if ( uv2ScaleMap !== undefined ) {
  15441. // backwards compatibility
  15442. if ( uv2ScaleMap.isWebGLRenderTarget ) {
  15443. uv2ScaleMap = uv2ScaleMap.texture;
  15444. }
  15445. if ( uv2ScaleMap.matrixAutoUpdate === true ) {
  15446. uv2ScaleMap.updateMatrix();
  15447. }
  15448. uniforms.uv2Transform.value.copy( uv2ScaleMap.matrix );
  15449. }
  15450. }
  15451. function refreshUniformsLine( uniforms, material ) {
  15452. uniforms.diffuse.value.copy( material.color );
  15453. uniforms.opacity.value = material.opacity;
  15454. }
  15455. function refreshUniformsDash( uniforms, material ) {
  15456. uniforms.dashSize.value = material.dashSize;
  15457. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15458. uniforms.scale.value = material.scale;
  15459. }
  15460. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  15461. uniforms.diffuse.value.copy( material.color );
  15462. uniforms.opacity.value = material.opacity;
  15463. uniforms.size.value = material.size * pixelRatio;
  15464. uniforms.scale.value = height * 0.5;
  15465. if ( material.map ) {
  15466. uniforms.map.value = material.map;
  15467. }
  15468. if ( material.alphaMap ) {
  15469. uniforms.alphaMap.value = material.alphaMap;
  15470. }
  15471. if ( material.alphaTest > 0 ) {
  15472. uniforms.alphaTest.value = material.alphaTest;
  15473. }
  15474. // uv repeat and offset setting priorities
  15475. // 1. color map
  15476. // 2. alpha map
  15477. let uvScaleMap;
  15478. if ( material.map ) {
  15479. uvScaleMap = material.map;
  15480. } else if ( material.alphaMap ) {
  15481. uvScaleMap = material.alphaMap;
  15482. }
  15483. if ( uvScaleMap !== undefined ) {
  15484. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15485. uvScaleMap.updateMatrix();
  15486. }
  15487. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15488. }
  15489. }
  15490. function refreshUniformsSprites( uniforms, material ) {
  15491. uniforms.diffuse.value.copy( material.color );
  15492. uniforms.opacity.value = material.opacity;
  15493. uniforms.rotation.value = material.rotation;
  15494. if ( material.map ) {
  15495. uniforms.map.value = material.map;
  15496. }
  15497. if ( material.alphaMap ) {
  15498. uniforms.alphaMap.value = material.alphaMap;
  15499. }
  15500. if ( material.alphaTest > 0 ) {
  15501. uniforms.alphaTest.value = material.alphaTest;
  15502. }
  15503. // uv repeat and offset setting priorities
  15504. // 1. color map
  15505. // 2. alpha map
  15506. let uvScaleMap;
  15507. if ( material.map ) {
  15508. uvScaleMap = material.map;
  15509. } else if ( material.alphaMap ) {
  15510. uvScaleMap = material.alphaMap;
  15511. }
  15512. if ( uvScaleMap !== undefined ) {
  15513. if ( uvScaleMap.matrixAutoUpdate === true ) {
  15514. uvScaleMap.updateMatrix();
  15515. }
  15516. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  15517. }
  15518. }
  15519. function refreshUniformsPhong( uniforms, material ) {
  15520. uniforms.specular.value.copy( material.specular );
  15521. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15522. }
  15523. function refreshUniformsToon( uniforms, material ) {
  15524. if ( material.gradientMap ) {
  15525. uniforms.gradientMap.value = material.gradientMap;
  15526. }
  15527. }
  15528. function refreshUniformsStandard( uniforms, material ) {
  15529. uniforms.roughness.value = material.roughness;
  15530. uniforms.metalness.value = material.metalness;
  15531. if ( material.roughnessMap ) {
  15532. uniforms.roughnessMap.value = material.roughnessMap;
  15533. }
  15534. if ( material.metalnessMap ) {
  15535. uniforms.metalnessMap.value = material.metalnessMap;
  15536. }
  15537. const envMap = properties.get( material ).envMap;
  15538. if ( envMap ) {
  15539. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15540. uniforms.envMapIntensity.value = material.envMapIntensity;
  15541. }
  15542. }
  15543. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  15544. uniforms.ior.value = material.ior; // also part of uniforms common
  15545. if ( material.sheen > 0 ) {
  15546. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  15547. uniforms.sheenRoughness.value = material.sheenRoughness;
  15548. if ( material.sheenColorMap ) {
  15549. uniforms.sheenColorMap.value = material.sheenColorMap;
  15550. }
  15551. if ( material.sheenRoughnessMap ) {
  15552. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  15553. }
  15554. }
  15555. if ( material.clearcoat > 0 ) {
  15556. uniforms.clearcoat.value = material.clearcoat;
  15557. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  15558. if ( material.clearcoatMap ) {
  15559. uniforms.clearcoatMap.value = material.clearcoatMap;
  15560. }
  15561. if ( material.clearcoatRoughnessMap ) {
  15562. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  15563. }
  15564. if ( material.clearcoatNormalMap ) {
  15565. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  15566. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  15567. if ( material.side === BackSide ) {
  15568. uniforms.clearcoatNormalScale.value.negate();
  15569. }
  15570. }
  15571. }
  15572. if ( material.iridescence > 0 ) {
  15573. uniforms.iridescence.value = material.iridescence;
  15574. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  15575. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  15576. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  15577. if ( material.iridescenceMap ) {
  15578. uniforms.iridescenceMap.value = material.iridescenceMap;
  15579. }
  15580. if ( material.iridescenceThicknessMap ) {
  15581. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  15582. }
  15583. }
  15584. if ( material.transmission > 0 ) {
  15585. uniforms.transmission.value = material.transmission;
  15586. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  15587. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  15588. if ( material.transmissionMap ) {
  15589. uniforms.transmissionMap.value = material.transmissionMap;
  15590. }
  15591. uniforms.thickness.value = material.thickness;
  15592. if ( material.thicknessMap ) {
  15593. uniforms.thicknessMap.value = material.thicknessMap;
  15594. }
  15595. uniforms.attenuationDistance.value = material.attenuationDistance;
  15596. uniforms.attenuationColor.value.copy( material.attenuationColor );
  15597. }
  15598. uniforms.specularIntensity.value = material.specularIntensity;
  15599. uniforms.specularColor.value.copy( material.specularColor );
  15600. if ( material.specularIntensityMap ) {
  15601. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  15602. }
  15603. if ( material.specularColorMap ) {
  15604. uniforms.specularColorMap.value = material.specularColorMap;
  15605. }
  15606. }
  15607. function refreshUniformsMatcap( uniforms, material ) {
  15608. if ( material.matcap ) {
  15609. uniforms.matcap.value = material.matcap;
  15610. }
  15611. }
  15612. function refreshUniformsDistance( uniforms, material ) {
  15613. uniforms.referencePosition.value.copy( material.referencePosition );
  15614. uniforms.nearDistance.value = material.nearDistance;
  15615. uniforms.farDistance.value = material.farDistance;
  15616. }
  15617. return {
  15618. refreshFogUniforms: refreshFogUniforms,
  15619. refreshMaterialUniforms: refreshMaterialUniforms
  15620. };
  15621. }
  15622. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  15623. let buffers = {};
  15624. let updateList = {};
  15625. let allocatedBindingPoints = [];
  15626. const maxBindingPoints = ( capabilities.isWebGL2 ) ? gl.getParameter( 35375 ) : 0; // binding points are global whereas block indices are per shader program
  15627. function bind( uniformsGroup, program ) {
  15628. const webglProgram = program.program;
  15629. state.uniformBlockBinding( uniformsGroup, webglProgram );
  15630. }
  15631. function update( uniformsGroup, program ) {
  15632. let buffer = buffers[ uniformsGroup.id ];
  15633. if ( buffer === undefined ) {
  15634. prepareUniformsGroup( uniformsGroup );
  15635. buffer = createBuffer( uniformsGroup );
  15636. buffers[ uniformsGroup.id ] = buffer;
  15637. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  15638. }
  15639. // ensure to update the binding points/block indices mapping for this program
  15640. const webglProgram = program.program;
  15641. state.updateUBOMapping( uniformsGroup, webglProgram );
  15642. // update UBO once per frame
  15643. const frame = info.render.frame;
  15644. if ( updateList[ uniformsGroup.id ] !== frame ) {
  15645. updateBufferData( uniformsGroup );
  15646. updateList[ uniformsGroup.id ] = frame;
  15647. }
  15648. }
  15649. function createBuffer( uniformsGroup ) {
  15650. // the setup of an UBO is independent of a particular shader program but global
  15651. const bindingPointIndex = allocateBindingPointIndex();
  15652. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  15653. const buffer = gl.createBuffer();
  15654. const size = uniformsGroup.__size;
  15655. const usage = uniformsGroup.usage;
  15656. gl.bindBuffer( 35345, buffer );
  15657. gl.bufferData( 35345, size, usage );
  15658. gl.bindBuffer( 35345, null );
  15659. gl.bindBufferBase( 35345, bindingPointIndex, buffer );
  15660. return buffer;
  15661. }
  15662. function allocateBindingPointIndex() {
  15663. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  15664. if ( allocatedBindingPoints.indexOf( i ) === - 1 ) {
  15665. allocatedBindingPoints.push( i );
  15666. return i;
  15667. }
  15668. }
  15669. console.error( 'THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  15670. return 0;
  15671. }
  15672. function updateBufferData( uniformsGroup ) {
  15673. const buffer = buffers[ uniformsGroup.id ];
  15674. const uniforms = uniformsGroup.uniforms;
  15675. const cache = uniformsGroup.__cache;
  15676. gl.bindBuffer( 35345, buffer );
  15677. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  15678. const uniform = uniforms[ i ];
  15679. // partly update the buffer if necessary
  15680. if ( hasUniformChanged( uniform, i, cache ) === true ) {
  15681. const value = uniform.value;
  15682. const offset = uniform.__offset;
  15683. if ( typeof value === 'number' ) {
  15684. uniform.__data[ 0 ] = value;
  15685. gl.bufferSubData( 35345, offset, uniform.__data );
  15686. } else {
  15687. if ( uniform.value.isMatrix3 ) {
  15688. // manually converting 3x3 to 3x4
  15689. uniform.__data[ 0 ] = uniform.value.elements[ 0 ];
  15690. uniform.__data[ 1 ] = uniform.value.elements[ 1 ];
  15691. uniform.__data[ 2 ] = uniform.value.elements[ 2 ];
  15692. uniform.__data[ 3 ] = uniform.value.elements[ 0 ];
  15693. uniform.__data[ 4 ] = uniform.value.elements[ 3 ];
  15694. uniform.__data[ 5 ] = uniform.value.elements[ 4 ];
  15695. uniform.__data[ 6 ] = uniform.value.elements[ 5 ];
  15696. uniform.__data[ 7 ] = uniform.value.elements[ 0 ];
  15697. uniform.__data[ 8 ] = uniform.value.elements[ 6 ];
  15698. uniform.__data[ 9 ] = uniform.value.elements[ 7 ];
  15699. uniform.__data[ 10 ] = uniform.value.elements[ 8 ];
  15700. uniform.__data[ 11 ] = uniform.value.elements[ 0 ];
  15701. } else {
  15702. value.toArray( uniform.__data );
  15703. }
  15704. gl.bufferSubData( 35345, offset, uniform.__data );
  15705. }
  15706. }
  15707. }
  15708. gl.bindBuffer( 35345, null );
  15709. }
  15710. function hasUniformChanged( uniform, index, cache ) {
  15711. const value = uniform.value;
  15712. if ( cache[ index ] === undefined ) {
  15713. // cache entry does not exist so far
  15714. if ( typeof value === 'number' ) {
  15715. cache[ index ] = value;
  15716. } else {
  15717. cache[ index ] = value.clone();
  15718. }
  15719. return true;
  15720. } else {
  15721. // compare current value with cached entry
  15722. if ( typeof value === 'number' ) {
  15723. if ( cache[ index ] !== value ) {
  15724. cache[ index ] = value;
  15725. return true;
  15726. }
  15727. } else {
  15728. const cachedObject = cache[ index ];
  15729. if ( cachedObject.equals( value ) === false ) {
  15730. cachedObject.copy( value );
  15731. return true;
  15732. }
  15733. }
  15734. }
  15735. return false;
  15736. }
  15737. function prepareUniformsGroup( uniformsGroup ) {
  15738. // determine total buffer size according to the STD140 layout
  15739. // Hint: STD140 is the only supported layout in WebGL 2
  15740. const uniforms = uniformsGroup.uniforms;
  15741. let offset = 0; // global buffer offset in bytes
  15742. const chunkSize = 16; // size of a chunk in bytes
  15743. let chunkOffset = 0; // offset within a single chunk in bytes
  15744. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  15745. const uniform = uniforms[ i ];
  15746. const info = getUniformSize( uniform );
  15747. // the following two properties will be used for partial buffer updates
  15748. uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT );
  15749. uniform.__offset = offset;
  15750. //
  15751. if ( i > 0 ) {
  15752. chunkOffset = offset % chunkSize;
  15753. const remainingSizeInChunk = chunkSize - chunkOffset;
  15754. // check for chunk overflow
  15755. if ( chunkOffset !== 0 && ( remainingSizeInChunk - info.boundary ) < 0 ) {
  15756. // add padding and adjust offset
  15757. offset += ( chunkSize - chunkOffset );
  15758. uniform.__offset = offset;
  15759. }
  15760. }
  15761. offset += info.storage;
  15762. }
  15763. // ensure correct final padding
  15764. chunkOffset = offset % chunkSize;
  15765. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  15766. //
  15767. uniformsGroup.__size = offset;
  15768. uniformsGroup.__cache = {};
  15769. return this;
  15770. }
  15771. function getUniformSize( uniform ) {
  15772. const value = uniform.value;
  15773. const info = {
  15774. boundary: 0, // bytes
  15775. storage: 0 // bytes
  15776. };
  15777. // determine sizes according to STD140
  15778. if ( typeof value === 'number' ) {
  15779. // float/int
  15780. info.boundary = 4;
  15781. info.storage = 4;
  15782. } else if ( value.isVector2 ) {
  15783. // vec2
  15784. info.boundary = 8;
  15785. info.storage = 8;
  15786. } else if ( value.isVector3 || value.isColor ) {
  15787. // vec3
  15788. info.boundary = 16;
  15789. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  15790. } else if ( value.isVector4 ) {
  15791. // vec4
  15792. info.boundary = 16;
  15793. info.storage = 16;
  15794. } else if ( value.isMatrix3 ) {
  15795. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  15796. info.boundary = 48;
  15797. info.storage = 48;
  15798. } else if ( value.isMatrix4 ) {
  15799. // mat4
  15800. info.boundary = 64;
  15801. info.storage = 64;
  15802. } else if ( value.isTexture ) {
  15803. console.warn( 'THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  15804. } else {
  15805. console.warn( 'THREE.WebGLRenderer: Unsupported uniform value type.', value );
  15806. }
  15807. return info;
  15808. }
  15809. function onUniformsGroupsDispose( event ) {
  15810. const uniformsGroup = event.target;
  15811. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  15812. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  15813. allocatedBindingPoints.splice( index, 1 );
  15814. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  15815. delete buffers[ uniformsGroup.id ];
  15816. delete updateList[ uniformsGroup.id ];
  15817. }
  15818. function dispose() {
  15819. for ( const id in buffers ) {
  15820. gl.deleteBuffer( buffers[ id ] );
  15821. }
  15822. allocatedBindingPoints = [];
  15823. buffers = {};
  15824. updateList = {};
  15825. }
  15826. return {
  15827. bind: bind,
  15828. update: update,
  15829. dispose: dispose
  15830. };
  15831. }
  15832. function createCanvasElement() {
  15833. const canvas = createElementNS( 'canvas' );
  15834. canvas.style.display = 'block';
  15835. return canvas;
  15836. }
  15837. function WebGLRenderer( parameters = {} ) {
  15838. this.isWebGLRenderer = true;
  15839. const _canvas = parameters.canvas !== undefined ? parameters.canvas : createCanvasElement(),
  15840. _context = parameters.context !== undefined ? parameters.context : null,
  15841. _depth = parameters.depth !== undefined ? parameters.depth : true,
  15842. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  15843. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  15844. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  15845. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  15846. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default',
  15847. _failIfMajorPerformanceCaveat = parameters.failIfMajorPerformanceCaveat !== undefined ? parameters.failIfMajorPerformanceCaveat : false;
  15848. let _alpha;
  15849. if ( _context !== null ) {
  15850. _alpha = _context.getContextAttributes().alpha;
  15851. } else {
  15852. _alpha = parameters.alpha !== undefined ? parameters.alpha : false;
  15853. }
  15854. let currentRenderList = null;
  15855. let currentRenderState = null;
  15856. // render() can be called from within a callback triggered by another render.
  15857. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  15858. const renderListStack = [];
  15859. const renderStateStack = [];
  15860. // public properties
  15861. this.domElement = _canvas;
  15862. // Debug configuration container
  15863. this.debug = {
  15864. /**
  15865. * Enables error checking and reporting when shader programs are being compiled
  15866. * @type {boolean}
  15867. */
  15868. checkShaderErrors: true
  15869. };
  15870. // clearing
  15871. this.autoClear = true;
  15872. this.autoClearColor = true;
  15873. this.autoClearDepth = true;
  15874. this.autoClearStencil = true;
  15875. // scene graph
  15876. this.sortObjects = true;
  15877. // user-defined clipping
  15878. this.clippingPlanes = [];
  15879. this.localClippingEnabled = false;
  15880. // physically based shading
  15881. this.outputEncoding = LinearEncoding;
  15882. // physical lights
  15883. this.physicallyCorrectLights = false;
  15884. // tone mapping
  15885. this.toneMapping = NoToneMapping;
  15886. this.toneMappingExposure = 1.0;
  15887. //
  15888. Object.defineProperties( this, {
  15889. // @deprecated since r136, 0e21088102b4de7e0a0a33140620b7a3424b9e6d
  15890. gammaFactor: {
  15891. get: function () {
  15892. console.warn( 'THREE.WebGLRenderer: .gammaFactor has been removed.' );
  15893. return 2;
  15894. },
  15895. set: function () {
  15896. console.warn( 'THREE.WebGLRenderer: .gammaFactor has been removed.' );
  15897. }
  15898. }
  15899. } );
  15900. // internal properties
  15901. const _this = this;
  15902. let _isContextLost = false;
  15903. // internal state cache
  15904. let _currentActiveCubeFace = 0;
  15905. let _currentActiveMipmapLevel = 0;
  15906. let _currentRenderTarget = null;
  15907. let _currentMaterialId = - 1;
  15908. let _currentCamera = null;
  15909. const _currentViewport = new Vector4();
  15910. const _currentScissor = new Vector4();
  15911. let _currentScissorTest = null;
  15912. //
  15913. let _width = _canvas.width;
  15914. let _height = _canvas.height;
  15915. let _pixelRatio = 1;
  15916. let _opaqueSort = null;
  15917. let _transparentSort = null;
  15918. const _viewport = new Vector4( 0, 0, _width, _height );
  15919. const _scissor = new Vector4( 0, 0, _width, _height );
  15920. let _scissorTest = false;
  15921. // frustum
  15922. const _frustum = new Frustum();
  15923. // clipping
  15924. let _clippingEnabled = false;
  15925. let _localClippingEnabled = false;
  15926. // transmission
  15927. let _transmissionRenderTarget = null;
  15928. // camera matrices cache
  15929. const _projScreenMatrix = new Matrix4();
  15930. const _vector2 = new Vector2();
  15931. const _vector3 = new Vector3();
  15932. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  15933. function getTargetPixelRatio() {
  15934. return _currentRenderTarget === null ? _pixelRatio : 1;
  15935. }
  15936. // initialize
  15937. let _gl = _context;
  15938. function getContext( contextNames, contextAttributes ) {
  15939. for ( let i = 0; i < contextNames.length; i ++ ) {
  15940. const contextName = contextNames[ i ];
  15941. const context = _canvas.getContext( contextName, contextAttributes );
  15942. if ( context !== null ) return context;
  15943. }
  15944. return null;
  15945. }
  15946. try {
  15947. const contextAttributes = {
  15948. alpha: true,
  15949. depth: _depth,
  15950. stencil: _stencil,
  15951. antialias: _antialias,
  15952. premultipliedAlpha: _premultipliedAlpha,
  15953. preserveDrawingBuffer: _preserveDrawingBuffer,
  15954. powerPreference: _powerPreference,
  15955. failIfMajorPerformanceCaveat: _failIfMajorPerformanceCaveat
  15956. };
  15957. // OffscreenCanvas does not have setAttribute, see #22811
  15958. if ( 'setAttribute' in _canvas ) _canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  15959. // event listeners must be registered before WebGL context is created, see #12753
  15960. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  15961. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  15962. _canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  15963. if ( _gl === null ) {
  15964. const contextNames = [ 'webgl2', 'webgl', 'experimental-webgl' ];
  15965. if ( _this.isWebGL1Renderer === true ) {
  15966. contextNames.shift();
  15967. }
  15968. _gl = getContext( contextNames, contextAttributes );
  15969. if ( _gl === null ) {
  15970. if ( getContext( contextNames ) ) {
  15971. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  15972. } else {
  15973. throw new Error( 'Error creating WebGL context.' );
  15974. }
  15975. }
  15976. }
  15977. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  15978. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15979. _gl.getShaderPrecisionFormat = function () {
  15980. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  15981. };
  15982. }
  15983. } catch ( error ) {
  15984. console.error( 'THREE.WebGLRenderer: ' + error.message );
  15985. throw error;
  15986. }
  15987. let extensions, capabilities, state, info;
  15988. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  15989. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  15990. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  15991. let utils, bindingStates, uniformsGroups;
  15992. function initGLContext() {
  15993. extensions = new WebGLExtensions( _gl );
  15994. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  15995. extensions.init( capabilities );
  15996. utils = new WebGLUtils( _gl, extensions, capabilities );
  15997. state = new WebGLState( _gl, extensions, capabilities );
  15998. info = new WebGLInfo();
  15999. properties = new WebGLProperties();
  16000. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  16001. cubemaps = new WebGLCubeMaps( _this );
  16002. cubeuvmaps = new WebGLCubeUVMaps( _this );
  16003. attributes = new WebGLAttributes( _gl, capabilities );
  16004. bindingStates = new WebGLBindingStates( _gl, extensions, attributes, capabilities );
  16005. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  16006. objects = new WebGLObjects( _gl, geometries, attributes, info );
  16007. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  16008. clipping = new WebGLClipping( properties );
  16009. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  16010. materials = new WebGLMaterials( _this, properties );
  16011. renderLists = new WebGLRenderLists();
  16012. renderStates = new WebGLRenderStates( extensions, capabilities );
  16013. background = new WebGLBackground( _this, cubemaps, state, objects, _alpha, _premultipliedAlpha );
  16014. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  16015. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  16016. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info, capabilities );
  16017. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info, capabilities );
  16018. info.programs = programCache.programs;
  16019. _this.capabilities = capabilities;
  16020. _this.extensions = extensions;
  16021. _this.properties = properties;
  16022. _this.renderLists = renderLists;
  16023. _this.shadowMap = shadowMap;
  16024. _this.state = state;
  16025. _this.info = info;
  16026. }
  16027. initGLContext();
  16028. // xr
  16029. const xr = new WebXRManager( _this, _gl );
  16030. this.xr = xr;
  16031. // API
  16032. this.getContext = function () {
  16033. return _gl;
  16034. };
  16035. this.getContextAttributes = function () {
  16036. return _gl.getContextAttributes();
  16037. };
  16038. this.forceContextLoss = function () {
  16039. const extension = extensions.get( 'WEBGL_lose_context' );
  16040. if ( extension ) extension.loseContext();
  16041. };
  16042. this.forceContextRestore = function () {
  16043. const extension = extensions.get( 'WEBGL_lose_context' );
  16044. if ( extension ) extension.restoreContext();
  16045. };
  16046. this.getPixelRatio = function () {
  16047. return _pixelRatio;
  16048. };
  16049. this.setPixelRatio = function ( value ) {
  16050. if ( value === undefined ) return;
  16051. _pixelRatio = value;
  16052. this.setSize( _width, _height, false );
  16053. };
  16054. this.getSize = function ( target ) {
  16055. return target.set( _width, _height );
  16056. };
  16057. this.setSize = function ( width, height, updateStyle ) {
  16058. if ( xr.isPresenting ) {
  16059. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  16060. return;
  16061. }
  16062. _width = width;
  16063. _height = height;
  16064. _canvas.width = Math.floor( width * _pixelRatio );
  16065. _canvas.height = Math.floor( height * _pixelRatio );
  16066. if ( updateStyle !== false ) {
  16067. _canvas.style.width = width + 'px';
  16068. _canvas.style.height = height + 'px';
  16069. }
  16070. this.setViewport( 0, 0, width, height );
  16071. };
  16072. this.getDrawingBufferSize = function ( target ) {
  16073. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  16074. };
  16075. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  16076. _width = width;
  16077. _height = height;
  16078. _pixelRatio = pixelRatio;
  16079. _canvas.width = Math.floor( width * pixelRatio );
  16080. _canvas.height = Math.floor( height * pixelRatio );
  16081. this.setViewport( 0, 0, width, height );
  16082. };
  16083. this.getCurrentViewport = function ( target ) {
  16084. return target.copy( _currentViewport );
  16085. };
  16086. this.getViewport = function ( target ) {
  16087. return target.copy( _viewport );
  16088. };
  16089. this.setViewport = function ( x, y, width, height ) {
  16090. if ( x.isVector4 ) {
  16091. _viewport.set( x.x, x.y, x.z, x.w );
  16092. } else {
  16093. _viewport.set( x, y, width, height );
  16094. }
  16095. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor() );
  16096. };
  16097. this.getScissor = function ( target ) {
  16098. return target.copy( _scissor );
  16099. };
  16100. this.setScissor = function ( x, y, width, height ) {
  16101. if ( x.isVector4 ) {
  16102. _scissor.set( x.x, x.y, x.z, x.w );
  16103. } else {
  16104. _scissor.set( x, y, width, height );
  16105. }
  16106. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor() );
  16107. };
  16108. this.getScissorTest = function () {
  16109. return _scissorTest;
  16110. };
  16111. this.setScissorTest = function ( boolean ) {
  16112. state.setScissorTest( _scissorTest = boolean );
  16113. };
  16114. this.setOpaqueSort = function ( method ) {
  16115. _opaqueSort = method;
  16116. };
  16117. this.setTransparentSort = function ( method ) {
  16118. _transparentSort = method;
  16119. };
  16120. // Clearing
  16121. this.getClearColor = function ( target ) {
  16122. return target.copy( background.getClearColor() );
  16123. };
  16124. this.setClearColor = function () {
  16125. background.setClearColor.apply( background, arguments );
  16126. };
  16127. this.getClearAlpha = function () {
  16128. return background.getClearAlpha();
  16129. };
  16130. this.setClearAlpha = function () {
  16131. background.setClearAlpha.apply( background, arguments );
  16132. };
  16133. this.clear = function ( color = true, depth = true, stencil = true ) {
  16134. let bits = 0;
  16135. if ( color ) bits |= 16384;
  16136. if ( depth ) bits |= 256;
  16137. if ( stencil ) bits |= 1024;
  16138. _gl.clear( bits );
  16139. };
  16140. this.clearColor = function () {
  16141. this.clear( true, false, false );
  16142. };
  16143. this.clearDepth = function () {
  16144. this.clear( false, true, false );
  16145. };
  16146. this.clearStencil = function () {
  16147. this.clear( false, false, true );
  16148. };
  16149. //
  16150. this.dispose = function () {
  16151. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  16152. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  16153. _canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  16154. renderLists.dispose();
  16155. renderStates.dispose();
  16156. properties.dispose();
  16157. cubemaps.dispose();
  16158. cubeuvmaps.dispose();
  16159. objects.dispose();
  16160. bindingStates.dispose();
  16161. uniformsGroups.dispose();
  16162. programCache.dispose();
  16163. xr.dispose();
  16164. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  16165. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  16166. if ( _transmissionRenderTarget ) {
  16167. _transmissionRenderTarget.dispose();
  16168. _transmissionRenderTarget = null;
  16169. }
  16170. animation.stop();
  16171. };
  16172. // Events
  16173. function onContextLost( event ) {
  16174. event.preventDefault();
  16175. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  16176. _isContextLost = true;
  16177. }
  16178. function onContextRestore( /* event */ ) {
  16179. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  16180. _isContextLost = false;
  16181. const infoAutoReset = info.autoReset;
  16182. const shadowMapEnabled = shadowMap.enabled;
  16183. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  16184. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  16185. const shadowMapType = shadowMap.type;
  16186. initGLContext();
  16187. info.autoReset = infoAutoReset;
  16188. shadowMap.enabled = shadowMapEnabled;
  16189. shadowMap.autoUpdate = shadowMapAutoUpdate;
  16190. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  16191. shadowMap.type = shadowMapType;
  16192. }
  16193. function onContextCreationError( event ) {
  16194. console.error( 'THREE.WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  16195. }
  16196. function onMaterialDispose( event ) {
  16197. const material = event.target;
  16198. material.removeEventListener( 'dispose', onMaterialDispose );
  16199. deallocateMaterial( material );
  16200. }
  16201. // Buffer deallocation
  16202. function deallocateMaterial( material ) {
  16203. releaseMaterialProgramReferences( material );
  16204. properties.remove( material );
  16205. }
  16206. function releaseMaterialProgramReferences( material ) {
  16207. const programs = properties.get( material ).programs;
  16208. if ( programs !== undefined ) {
  16209. programs.forEach( function ( program ) {
  16210. programCache.releaseProgram( program );
  16211. } );
  16212. if ( material.isShaderMaterial ) {
  16213. programCache.releaseShaderCache( material );
  16214. }
  16215. }
  16216. }
  16217. // Buffer rendering
  16218. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  16219. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  16220. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  16221. const program = setProgram( camera, scene, geometry, material, object );
  16222. state.setMaterial( material, frontFaceCW );
  16223. //
  16224. let index = geometry.index;
  16225. const position = geometry.attributes.position;
  16226. //
  16227. if ( index === null ) {
  16228. if ( position === undefined || position.count === 0 ) return;
  16229. } else if ( index.count === 0 ) {
  16230. return;
  16231. }
  16232. //
  16233. let rangeFactor = 1;
  16234. if ( material.wireframe === true ) {
  16235. index = geometries.getWireframeAttribute( geometry );
  16236. rangeFactor = 2;
  16237. }
  16238. bindingStates.setup( object, material, program, geometry, index );
  16239. let attribute;
  16240. let renderer = bufferRenderer;
  16241. if ( index !== null ) {
  16242. attribute = attributes.get( index );
  16243. renderer = indexedBufferRenderer;
  16244. renderer.setIndex( attribute );
  16245. }
  16246. //
  16247. const dataCount = ( index !== null ) ? index.count : position.count;
  16248. const rangeStart = geometry.drawRange.start * rangeFactor;
  16249. const rangeCount = geometry.drawRange.count * rangeFactor;
  16250. const groupStart = group !== null ? group.start * rangeFactor : 0;
  16251. const groupCount = group !== null ? group.count * rangeFactor : Infinity;
  16252. const drawStart = Math.max( rangeStart, groupStart );
  16253. const drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  16254. const drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  16255. if ( drawCount === 0 ) return;
  16256. //
  16257. if ( object.isMesh ) {
  16258. if ( material.wireframe === true ) {
  16259. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  16260. renderer.setMode( 1 );
  16261. } else {
  16262. renderer.setMode( 4 );
  16263. }
  16264. } else if ( object.isLine ) {
  16265. let lineWidth = material.linewidth;
  16266. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  16267. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  16268. if ( object.isLineSegments ) {
  16269. renderer.setMode( 1 );
  16270. } else if ( object.isLineLoop ) {
  16271. renderer.setMode( 2 );
  16272. } else {
  16273. renderer.setMode( 3 );
  16274. }
  16275. } else if ( object.isPoints ) {
  16276. renderer.setMode( 0 );
  16277. } else if ( object.isSprite ) {
  16278. renderer.setMode( 4 );
  16279. }
  16280. if ( object.isInstancedMesh ) {
  16281. renderer.renderInstances( drawStart, drawCount, object.count );
  16282. } else if ( geometry.isInstancedBufferGeometry ) {
  16283. const instanceCount = Math.min( geometry.instanceCount, geometry._maxInstanceCount );
  16284. renderer.renderInstances( drawStart, drawCount, instanceCount );
  16285. } else {
  16286. renderer.render( drawStart, drawCount );
  16287. }
  16288. };
  16289. // Compile
  16290. this.compile = function ( scene, camera ) {
  16291. currentRenderState = renderStates.get( scene );
  16292. currentRenderState.init();
  16293. renderStateStack.push( currentRenderState );
  16294. scene.traverseVisible( function ( object ) {
  16295. if ( object.isLight && object.layers.test( camera.layers ) ) {
  16296. currentRenderState.pushLight( object );
  16297. if ( object.castShadow ) {
  16298. currentRenderState.pushShadow( object );
  16299. }
  16300. }
  16301. } );
  16302. currentRenderState.setupLights( _this.physicallyCorrectLights );
  16303. scene.traverse( function ( object ) {
  16304. const material = object.material;
  16305. if ( material ) {
  16306. if ( Array.isArray( material ) ) {
  16307. for ( let i = 0; i < material.length; i ++ ) {
  16308. const material2 = material[ i ];
  16309. getProgram( material2, scene, object );
  16310. }
  16311. } else {
  16312. getProgram( material, scene, object );
  16313. }
  16314. }
  16315. } );
  16316. renderStateStack.pop();
  16317. currentRenderState = null;
  16318. };
  16319. // Animation Loop
  16320. let onAnimationFrameCallback = null;
  16321. function onAnimationFrame( time ) {
  16322. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  16323. }
  16324. function onXRSessionStart() {
  16325. animation.stop();
  16326. }
  16327. function onXRSessionEnd() {
  16328. animation.start();
  16329. }
  16330. const animation = new WebGLAnimation();
  16331. animation.setAnimationLoop( onAnimationFrame );
  16332. if ( typeof self !== 'undefined' ) animation.setContext( self );
  16333. this.setAnimationLoop = function ( callback ) {
  16334. onAnimationFrameCallback = callback;
  16335. xr.setAnimationLoop( callback );
  16336. ( callback === null ) ? animation.stop() : animation.start();
  16337. };
  16338. xr.addEventListener( 'sessionstart', onXRSessionStart );
  16339. xr.addEventListener( 'sessionend', onXRSessionEnd );
  16340. // Rendering
  16341. this.render = function ( scene, camera ) {
  16342. if ( camera !== undefined && camera.isCamera !== true ) {
  16343. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  16344. return;
  16345. }
  16346. if ( _isContextLost === true ) return;
  16347. // update scene graph
  16348. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  16349. // update camera matrices and frustum
  16350. if ( camera.parent === null ) camera.updateMatrixWorld();
  16351. if ( xr.enabled === true && xr.isPresenting === true ) {
  16352. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  16353. camera = xr.getCamera(); // use XR camera for rendering
  16354. }
  16355. //
  16356. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  16357. currentRenderState = renderStates.get( scene, renderStateStack.length );
  16358. currentRenderState.init();
  16359. renderStateStack.push( currentRenderState );
  16360. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16361. _frustum.setFromProjectionMatrix( _projScreenMatrix );
  16362. _localClippingEnabled = this.localClippingEnabled;
  16363. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  16364. currentRenderList = renderLists.get( scene, renderListStack.length );
  16365. currentRenderList.init();
  16366. renderListStack.push( currentRenderList );
  16367. projectObject( scene, camera, 0, _this.sortObjects );
  16368. currentRenderList.finish();
  16369. if ( _this.sortObjects === true ) {
  16370. currentRenderList.sort( _opaqueSort, _transparentSort );
  16371. }
  16372. //
  16373. if ( _clippingEnabled === true ) clipping.beginShadows();
  16374. const shadowsArray = currentRenderState.state.shadowsArray;
  16375. shadowMap.render( shadowsArray, scene, camera );
  16376. if ( _clippingEnabled === true ) clipping.endShadows();
  16377. //
  16378. if ( this.info.autoReset === true ) this.info.reset();
  16379. //
  16380. background.render( currentRenderList, scene );
  16381. // render scene
  16382. currentRenderState.setupLights( _this.physicallyCorrectLights );
  16383. if ( camera.isArrayCamera ) {
  16384. const cameras = camera.cameras;
  16385. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  16386. const camera2 = cameras[ i ];
  16387. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  16388. }
  16389. } else {
  16390. renderScene( currentRenderList, scene, camera );
  16391. }
  16392. //
  16393. if ( _currentRenderTarget !== null ) {
  16394. // resolve multisample renderbuffers to a single-sample texture if necessary
  16395. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  16396. // Generate mipmap if we're using any kind of mipmap filtering
  16397. textures.updateRenderTargetMipmap( _currentRenderTarget );
  16398. }
  16399. //
  16400. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  16401. // _gl.finish();
  16402. bindingStates.resetDefaultState();
  16403. _currentMaterialId = - 1;
  16404. _currentCamera = null;
  16405. renderStateStack.pop();
  16406. if ( renderStateStack.length > 0 ) {
  16407. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  16408. } else {
  16409. currentRenderState = null;
  16410. }
  16411. renderListStack.pop();
  16412. if ( renderListStack.length > 0 ) {
  16413. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  16414. } else {
  16415. currentRenderList = null;
  16416. }
  16417. };
  16418. function projectObject( object, camera, groupOrder, sortObjects ) {
  16419. if ( object.visible === false ) return;
  16420. const visible = object.layers.test( camera.layers );
  16421. if ( visible ) {
  16422. if ( object.isGroup ) {
  16423. groupOrder = object.renderOrder;
  16424. } else if ( object.isLOD ) {
  16425. if ( object.autoUpdate === true ) object.update( camera );
  16426. } else if ( object.isLight ) {
  16427. currentRenderState.pushLight( object );
  16428. if ( object.castShadow ) {
  16429. currentRenderState.pushShadow( object );
  16430. }
  16431. } else if ( object.isSprite ) {
  16432. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  16433. if ( sortObjects ) {
  16434. _vector3.setFromMatrixPosition( object.matrixWorld )
  16435. .applyMatrix4( _projScreenMatrix );
  16436. }
  16437. const geometry = objects.update( object );
  16438. const material = object.material;
  16439. if ( material.visible ) {
  16440. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  16441. }
  16442. }
  16443. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  16444. if ( object.isSkinnedMesh ) {
  16445. // update skeleton only once in a frame
  16446. if ( object.skeleton.frame !== info.render.frame ) {
  16447. object.skeleton.update();
  16448. object.skeleton.frame = info.render.frame;
  16449. }
  16450. }
  16451. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  16452. if ( sortObjects ) {
  16453. _vector3.setFromMatrixPosition( object.matrixWorld )
  16454. .applyMatrix4( _projScreenMatrix );
  16455. }
  16456. const geometry = objects.update( object );
  16457. const material = object.material;
  16458. if ( Array.isArray( material ) ) {
  16459. const groups = geometry.groups;
  16460. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  16461. const group = groups[ i ];
  16462. const groupMaterial = material[ group.materialIndex ];
  16463. if ( groupMaterial && groupMaterial.visible ) {
  16464. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector3.z, group );
  16465. }
  16466. }
  16467. } else if ( material.visible ) {
  16468. currentRenderList.push( object, geometry, material, groupOrder, _vector3.z, null );
  16469. }
  16470. }
  16471. }
  16472. }
  16473. const children = object.children;
  16474. for ( let i = 0, l = children.length; i < l; i ++ ) {
  16475. projectObject( children[ i ], camera, groupOrder, sortObjects );
  16476. }
  16477. }
  16478. function renderScene( currentRenderList, scene, camera, viewport ) {
  16479. const opaqueObjects = currentRenderList.opaque;
  16480. const transmissiveObjects = currentRenderList.transmissive;
  16481. const transparentObjects = currentRenderList.transparent;
  16482. currentRenderState.setupLightsView( camera );
  16483. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, scene, camera );
  16484. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  16485. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  16486. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  16487. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  16488. // Ensure depth buffer writing is enabled so it can be cleared on next render
  16489. state.buffers.depth.setTest( true );
  16490. state.buffers.depth.setMask( true );
  16491. state.buffers.color.setMask( true );
  16492. state.setPolygonOffset( false );
  16493. }
  16494. function renderTransmissionPass( opaqueObjects, scene, camera ) {
  16495. const isWebGL2 = capabilities.isWebGL2;
  16496. if ( _transmissionRenderTarget === null ) {
  16497. _transmissionRenderTarget = new WebGLRenderTarget( 1, 1, {
  16498. generateMipmaps: true,
  16499. type: extensions.has( 'EXT_color_buffer_half_float' ) ? HalfFloatType : UnsignedByteType,
  16500. minFilter: LinearMipmapLinearFilter,
  16501. samples: ( isWebGL2 && _antialias === true ) ? 4 : 0
  16502. } );
  16503. }
  16504. _this.getDrawingBufferSize( _vector2 );
  16505. if ( isWebGL2 ) {
  16506. _transmissionRenderTarget.setSize( _vector2.x, _vector2.y );
  16507. } else {
  16508. _transmissionRenderTarget.setSize( floorPowerOfTwo( _vector2.x ), floorPowerOfTwo( _vector2.y ) );
  16509. }
  16510. //
  16511. const currentRenderTarget = _this.getRenderTarget();
  16512. _this.setRenderTarget( _transmissionRenderTarget );
  16513. _this.clear();
  16514. // Turn off the features which can affect the frag color for opaque objects pass.
  16515. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  16516. const currentToneMapping = _this.toneMapping;
  16517. _this.toneMapping = NoToneMapping;
  16518. renderObjects( opaqueObjects, scene, camera );
  16519. _this.toneMapping = currentToneMapping;
  16520. textures.updateMultisampleRenderTarget( _transmissionRenderTarget );
  16521. textures.updateRenderTargetMipmap( _transmissionRenderTarget );
  16522. _this.setRenderTarget( currentRenderTarget );
  16523. }
  16524. function renderObjects( renderList, scene, camera ) {
  16525. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  16526. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  16527. const renderItem = renderList[ i ];
  16528. const object = renderItem.object;
  16529. const geometry = renderItem.geometry;
  16530. const material = overrideMaterial === null ? renderItem.material : overrideMaterial;
  16531. const group = renderItem.group;
  16532. if ( object.layers.test( camera.layers ) ) {
  16533. renderObject( object, scene, camera, geometry, material, group );
  16534. }
  16535. }
  16536. }
  16537. function renderObject( object, scene, camera, geometry, material, group ) {
  16538. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  16539. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  16540. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  16541. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  16542. if ( material.transparent === true && material.side === DoubleSide ) {
  16543. material.side = BackSide;
  16544. material.needsUpdate = true;
  16545. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16546. material.side = FrontSide;
  16547. material.needsUpdate = true;
  16548. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16549. material.side = DoubleSide;
  16550. } else {
  16551. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  16552. }
  16553. object.onAfterRender( _this, scene, camera, geometry, material, group );
  16554. }
  16555. function getProgram( material, scene, object ) {
  16556. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16557. const materialProperties = properties.get( material );
  16558. const lights = currentRenderState.state.lights;
  16559. const shadowsArray = currentRenderState.state.shadowsArray;
  16560. const lightsStateVersion = lights.state.version;
  16561. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  16562. const programCacheKey = programCache.getProgramCacheKey( parameters );
  16563. let programs = materialProperties.programs;
  16564. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  16565. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  16566. materialProperties.fog = scene.fog;
  16567. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  16568. if ( programs === undefined ) {
  16569. // new material
  16570. material.addEventListener( 'dispose', onMaterialDispose );
  16571. programs = new Map();
  16572. materialProperties.programs = programs;
  16573. }
  16574. let program = programs.get( programCacheKey );
  16575. if ( program !== undefined ) {
  16576. // early out if program and light state is identical
  16577. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  16578. updateCommonMaterialProperties( material, parameters );
  16579. return program;
  16580. }
  16581. } else {
  16582. parameters.uniforms = programCache.getUniforms( material );
  16583. material.onBuild( object, parameters, _this );
  16584. material.onBeforeCompile( parameters, _this );
  16585. program = programCache.acquireProgram( parameters, programCacheKey );
  16586. programs.set( programCacheKey, program );
  16587. materialProperties.uniforms = parameters.uniforms;
  16588. }
  16589. const uniforms = materialProperties.uniforms;
  16590. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  16591. uniforms.clippingPlanes = clipping.uniform;
  16592. }
  16593. updateCommonMaterialProperties( material, parameters );
  16594. // store the light setup it was created for
  16595. materialProperties.needsLights = materialNeedsLights( material );
  16596. materialProperties.lightsStateVersion = lightsStateVersion;
  16597. if ( materialProperties.needsLights ) {
  16598. // wire up the material to this renderer's lighting state
  16599. uniforms.ambientLightColor.value = lights.state.ambient;
  16600. uniforms.lightProbe.value = lights.state.probe;
  16601. uniforms.directionalLights.value = lights.state.directional;
  16602. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  16603. uniforms.spotLights.value = lights.state.spot;
  16604. uniforms.spotLightShadows.value = lights.state.spotShadow;
  16605. uniforms.rectAreaLights.value = lights.state.rectArea;
  16606. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  16607. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  16608. uniforms.pointLights.value = lights.state.point;
  16609. uniforms.pointLightShadows.value = lights.state.pointShadow;
  16610. uniforms.hemisphereLights.value = lights.state.hemi;
  16611. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  16612. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  16613. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  16614. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  16615. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  16616. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  16617. // TODO (abelnation): add area lights shadow info to uniforms
  16618. }
  16619. const progUniforms = program.getUniforms();
  16620. const uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  16621. materialProperties.currentProgram = program;
  16622. materialProperties.uniformsList = uniformsList;
  16623. return program;
  16624. }
  16625. function updateCommonMaterialProperties( material, parameters ) {
  16626. const materialProperties = properties.get( material );
  16627. materialProperties.outputEncoding = parameters.outputEncoding;
  16628. materialProperties.instancing = parameters.instancing;
  16629. materialProperties.skinning = parameters.skinning;
  16630. materialProperties.morphTargets = parameters.morphTargets;
  16631. materialProperties.morphNormals = parameters.morphNormals;
  16632. materialProperties.morphColors = parameters.morphColors;
  16633. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  16634. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  16635. materialProperties.numIntersection = parameters.numClipIntersection;
  16636. materialProperties.vertexAlphas = parameters.vertexAlphas;
  16637. materialProperties.vertexTangents = parameters.vertexTangents;
  16638. materialProperties.toneMapping = parameters.toneMapping;
  16639. }
  16640. function setProgram( camera, scene, geometry, material, object ) {
  16641. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  16642. textures.resetTextureUnits();
  16643. const fog = scene.fog;
  16644. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  16645. const encoding = ( _currentRenderTarget === null ) ? _this.outputEncoding : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.encoding : LinearEncoding );
  16646. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  16647. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  16648. const vertexTangents = !! material.normalMap && !! geometry.attributes.tangent;
  16649. const morphTargets = !! geometry.morphAttributes.position;
  16650. const morphNormals = !! geometry.morphAttributes.normal;
  16651. const morphColors = !! geometry.morphAttributes.color;
  16652. const toneMapping = material.toneMapped ? _this.toneMapping : NoToneMapping;
  16653. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  16654. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  16655. const materialProperties = properties.get( material );
  16656. const lights = currentRenderState.state.lights;
  16657. if ( _clippingEnabled === true ) {
  16658. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  16659. const useCache =
  16660. camera === _currentCamera &&
  16661. material.id === _currentMaterialId;
  16662. // we might want to call this function with some ClippingGroup
  16663. // object instead of the material, once it becomes feasible
  16664. // (#8465, #8379)
  16665. clipping.setState( material, camera, useCache );
  16666. }
  16667. }
  16668. //
  16669. let needsProgramChange = false;
  16670. if ( material.version === materialProperties.__version ) {
  16671. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  16672. needsProgramChange = true;
  16673. } else if ( materialProperties.outputEncoding !== encoding ) {
  16674. needsProgramChange = true;
  16675. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  16676. needsProgramChange = true;
  16677. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  16678. needsProgramChange = true;
  16679. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  16680. needsProgramChange = true;
  16681. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  16682. needsProgramChange = true;
  16683. } else if ( materialProperties.envMap !== envMap ) {
  16684. needsProgramChange = true;
  16685. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  16686. needsProgramChange = true;
  16687. } else if ( materialProperties.numClippingPlanes !== undefined &&
  16688. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  16689. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  16690. needsProgramChange = true;
  16691. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  16692. needsProgramChange = true;
  16693. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  16694. needsProgramChange = true;
  16695. } else if ( materialProperties.morphTargets !== morphTargets ) {
  16696. needsProgramChange = true;
  16697. } else if ( materialProperties.morphNormals !== morphNormals ) {
  16698. needsProgramChange = true;
  16699. } else if ( materialProperties.morphColors !== morphColors ) {
  16700. needsProgramChange = true;
  16701. } else if ( materialProperties.toneMapping !== toneMapping ) {
  16702. needsProgramChange = true;
  16703. } else if ( capabilities.isWebGL2 === true && materialProperties.morphTargetsCount !== morphTargetsCount ) {
  16704. needsProgramChange = true;
  16705. }
  16706. } else {
  16707. needsProgramChange = true;
  16708. materialProperties.__version = material.version;
  16709. }
  16710. //
  16711. let program = materialProperties.currentProgram;
  16712. if ( needsProgramChange === true ) {
  16713. program = getProgram( material, scene, object );
  16714. }
  16715. let refreshProgram = false;
  16716. let refreshMaterial = false;
  16717. let refreshLights = false;
  16718. const p_uniforms = program.getUniforms(),
  16719. m_uniforms = materialProperties.uniforms;
  16720. if ( state.useProgram( program.program ) ) {
  16721. refreshProgram = true;
  16722. refreshMaterial = true;
  16723. refreshLights = true;
  16724. }
  16725. if ( material.id !== _currentMaterialId ) {
  16726. _currentMaterialId = material.id;
  16727. refreshMaterial = true;
  16728. }
  16729. if ( refreshProgram || _currentCamera !== camera ) {
  16730. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  16731. if ( capabilities.logarithmicDepthBuffer ) {
  16732. p_uniforms.setValue( _gl, 'logDepthBufFC',
  16733. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  16734. }
  16735. if ( _currentCamera !== camera ) {
  16736. _currentCamera = camera;
  16737. // lighting uniforms depend on the camera so enforce an update
  16738. // now, in case this material supports lights - or later, when
  16739. // the next material that does gets activated:
  16740. refreshMaterial = true; // set to true on material change
  16741. refreshLights = true; // remains set until update done
  16742. }
  16743. // load material specific uniforms
  16744. // (shader material also gets them for the sake of genericity)
  16745. if ( material.isShaderMaterial ||
  16746. material.isMeshPhongMaterial ||
  16747. material.isMeshToonMaterial ||
  16748. material.isMeshStandardMaterial ||
  16749. material.envMap ) {
  16750. const uCamPos = p_uniforms.map.cameraPosition;
  16751. if ( uCamPos !== undefined ) {
  16752. uCamPos.setValue( _gl,
  16753. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  16754. }
  16755. }
  16756. if ( material.isMeshPhongMaterial ||
  16757. material.isMeshToonMaterial ||
  16758. material.isMeshLambertMaterial ||
  16759. material.isMeshBasicMaterial ||
  16760. material.isMeshStandardMaterial ||
  16761. material.isShaderMaterial ) {
  16762. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  16763. }
  16764. if ( material.isMeshPhongMaterial ||
  16765. material.isMeshToonMaterial ||
  16766. material.isMeshLambertMaterial ||
  16767. material.isMeshBasicMaterial ||
  16768. material.isMeshStandardMaterial ||
  16769. material.isShaderMaterial ||
  16770. material.isShadowMaterial ||
  16771. object.isSkinnedMesh ) {
  16772. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  16773. }
  16774. }
  16775. // skinning and morph target uniforms must be set even if material didn't change
  16776. // auto-setting of texture unit for bone and morph texture must go before other textures
  16777. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  16778. if ( object.isSkinnedMesh ) {
  16779. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  16780. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  16781. const skeleton = object.skeleton;
  16782. if ( skeleton ) {
  16783. if ( capabilities.floatVertexTextures ) {
  16784. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  16785. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  16786. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  16787. } else {
  16788. console.warn( 'THREE.WebGLRenderer: SkinnedMesh can only be used with WebGL 2. With WebGL 1 OES_texture_float and vertex textures support is required.' );
  16789. }
  16790. }
  16791. }
  16792. const morphAttributes = geometry.morphAttributes;
  16793. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined && capabilities.isWebGL2 === true ) ) {
  16794. morphtargets.update( object, geometry, material, program );
  16795. }
  16796. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  16797. materialProperties.receiveShadow = object.receiveShadow;
  16798. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  16799. }
  16800. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  16801. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  16802. m_uniforms.envMap.value = envMap;
  16803. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? - 1 : 1;
  16804. }
  16805. if ( refreshMaterial ) {
  16806. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  16807. if ( materialProperties.needsLights ) {
  16808. // the current material requires lighting info
  16809. // note: all lighting uniforms are always set correctly
  16810. // they simply reference the renderer's state for their
  16811. // values
  16812. //
  16813. // use the current material's .needsUpdate flags to set
  16814. // the GL state when required
  16815. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  16816. }
  16817. // refresh uniforms common to several materials
  16818. if ( fog && material.fog === true ) {
  16819. materials.refreshFogUniforms( m_uniforms, fog );
  16820. }
  16821. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, _transmissionRenderTarget );
  16822. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  16823. }
  16824. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  16825. WebGLUniforms.upload( _gl, materialProperties.uniformsList, m_uniforms, textures );
  16826. material.uniformsNeedUpdate = false;
  16827. }
  16828. if ( material.isSpriteMaterial ) {
  16829. p_uniforms.setValue( _gl, 'center', object.center );
  16830. }
  16831. // common matrices
  16832. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  16833. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  16834. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  16835. // UBOs
  16836. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  16837. const groups = material.uniformsGroups;
  16838. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  16839. if ( capabilities.isWebGL2 ) {
  16840. const group = groups[ i ];
  16841. uniformsGroups.update( group, program );
  16842. uniformsGroups.bind( group, program );
  16843. } else {
  16844. console.warn( 'THREE.WebGLRenderer: Uniform Buffer Objects can only be used with WebGL 2.' );
  16845. }
  16846. }
  16847. }
  16848. return program;
  16849. }
  16850. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  16851. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  16852. uniforms.ambientLightColor.needsUpdate = value;
  16853. uniforms.lightProbe.needsUpdate = value;
  16854. uniforms.directionalLights.needsUpdate = value;
  16855. uniforms.directionalLightShadows.needsUpdate = value;
  16856. uniforms.pointLights.needsUpdate = value;
  16857. uniforms.pointLightShadows.needsUpdate = value;
  16858. uniforms.spotLights.needsUpdate = value;
  16859. uniforms.spotLightShadows.needsUpdate = value;
  16860. uniforms.rectAreaLights.needsUpdate = value;
  16861. uniforms.hemisphereLights.needsUpdate = value;
  16862. }
  16863. function materialNeedsLights( material ) {
  16864. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  16865. material.isMeshStandardMaterial || material.isShadowMaterial ||
  16866. ( material.isShaderMaterial && material.lights === true );
  16867. }
  16868. this.getActiveCubeFace = function () {
  16869. return _currentActiveCubeFace;
  16870. };
  16871. this.getActiveMipmapLevel = function () {
  16872. return _currentActiveMipmapLevel;
  16873. };
  16874. this.getRenderTarget = function () {
  16875. return _currentRenderTarget;
  16876. };
  16877. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  16878. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  16879. properties.get( renderTarget.depthTexture ).__webglTexture = depthTexture;
  16880. const renderTargetProperties = properties.get( renderTarget );
  16881. renderTargetProperties.__hasExternalTextures = true;
  16882. if ( renderTargetProperties.__hasExternalTextures ) {
  16883. renderTargetProperties.__autoAllocateDepthBuffer = depthTexture === undefined;
  16884. if ( ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  16885. // The multisample_render_to_texture extension doesn't work properly if there
  16886. // are midframe flushes and an external depth buffer. Disable use of the extension.
  16887. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) {
  16888. console.warn( 'THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided' );
  16889. renderTargetProperties.__useRenderToTexture = false;
  16890. }
  16891. }
  16892. }
  16893. };
  16894. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  16895. const renderTargetProperties = properties.get( renderTarget );
  16896. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  16897. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  16898. };
  16899. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  16900. _currentRenderTarget = renderTarget;
  16901. _currentActiveCubeFace = activeCubeFace;
  16902. _currentActiveMipmapLevel = activeMipmapLevel;
  16903. let useDefaultFramebuffer = true;
  16904. if ( renderTarget ) {
  16905. const renderTargetProperties = properties.get( renderTarget );
  16906. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  16907. // We need to make sure to rebind the framebuffer.
  16908. state.bindFramebuffer( 36160, null );
  16909. useDefaultFramebuffer = false;
  16910. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  16911. textures.setupRenderTarget( renderTarget );
  16912. } else if ( renderTargetProperties.__hasExternalTextures ) {
  16913. // Color and depth texture must be rebound in order for the swapchain to update.
  16914. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  16915. }
  16916. }
  16917. let framebuffer = null;
  16918. let isCube = false;
  16919. let isRenderTarget3D = false;
  16920. if ( renderTarget ) {
  16921. const texture = renderTarget.texture;
  16922. if ( texture.isData3DTexture || texture.isDataArrayTexture ) {
  16923. isRenderTarget3D = true;
  16924. }
  16925. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  16926. if ( renderTarget.isWebGLCubeRenderTarget ) {
  16927. framebuffer = __webglFramebuffer[ activeCubeFace ];
  16928. isCube = true;
  16929. } else if ( ( capabilities.isWebGL2 && renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  16930. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  16931. } else {
  16932. framebuffer = __webglFramebuffer;
  16933. }
  16934. _currentViewport.copy( renderTarget.viewport );
  16935. _currentScissor.copy( renderTarget.scissor );
  16936. _currentScissorTest = renderTarget.scissorTest;
  16937. } else {
  16938. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  16939. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  16940. _currentScissorTest = _scissorTest;
  16941. }
  16942. const framebufferBound = state.bindFramebuffer( 36160, framebuffer );
  16943. if ( framebufferBound && capabilities.drawBuffers && useDefaultFramebuffer ) {
  16944. state.drawBuffers( renderTarget, framebuffer );
  16945. }
  16946. state.viewport( _currentViewport );
  16947. state.scissor( _currentScissor );
  16948. state.setScissorTest( _currentScissorTest );
  16949. if ( isCube ) {
  16950. const textureProperties = properties.get( renderTarget.texture );
  16951. _gl.framebufferTexture2D( 36160, 36064, 34069 + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  16952. } else if ( isRenderTarget3D ) {
  16953. const textureProperties = properties.get( renderTarget.texture );
  16954. const layer = activeCubeFace || 0;
  16955. _gl.framebufferTextureLayer( 36160, 36064, textureProperties.__webglTexture, activeMipmapLevel || 0, layer );
  16956. }
  16957. _currentMaterialId = - 1; // reset current material to ensure correct uniform bindings
  16958. };
  16959. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex ) {
  16960. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  16961. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  16962. return;
  16963. }
  16964. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  16965. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  16966. framebuffer = framebuffer[ activeCubeFaceIndex ];
  16967. }
  16968. if ( framebuffer ) {
  16969. state.bindFramebuffer( 36160, framebuffer );
  16970. try {
  16971. const texture = renderTarget.texture;
  16972. const textureFormat = texture.format;
  16973. const textureType = texture.type;
  16974. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( 35739 ) ) {
  16975. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  16976. return;
  16977. }
  16978. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || ( capabilities.isWebGL2 && extensions.has( 'EXT_color_buffer_float' ) ) );
  16979. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( 35738 ) && // Edge and Chrome Mac < 52 (#9513)
  16980. ! ( textureType === FloatType && ( capabilities.isWebGL2 || extensions.has( 'OES_texture_float' ) || extensions.has( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  16981. ! halfFloatSupportedByExt ) {
  16982. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  16983. return;
  16984. }
  16985. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  16986. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  16987. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  16988. }
  16989. } finally {
  16990. // restore framebuffer of current render target if necessary
  16991. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  16992. state.bindFramebuffer( 36160, framebuffer );
  16993. }
  16994. }
  16995. };
  16996. this.copyFramebufferToTexture = function ( position, texture, level = 0 ) {
  16997. const levelScale = Math.pow( 2, - level );
  16998. const width = Math.floor( texture.image.width * levelScale );
  16999. const height = Math.floor( texture.image.height * levelScale );
  17000. textures.setTexture2D( texture, 0 );
  17001. _gl.copyTexSubImage2D( 3553, level, 0, 0, position.x, position.y, width, height );
  17002. state.unbindTexture();
  17003. };
  17004. this.copyTextureToTexture = function ( position, srcTexture, dstTexture, level = 0 ) {
  17005. const width = srcTexture.image.width;
  17006. const height = srcTexture.image.height;
  17007. const glFormat = utils.convert( dstTexture.format );
  17008. const glType = utils.convert( dstTexture.type );
  17009. textures.setTexture2D( dstTexture, 0 );
  17010. // As another texture upload may have changed pixelStorei
  17011. // parameters, make sure they are correct for the dstTexture
  17012. _gl.pixelStorei( 37440, dstTexture.flipY );
  17013. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  17014. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  17015. if ( srcTexture.isDataTexture ) {
  17016. _gl.texSubImage2D( 3553, level, position.x, position.y, width, height, glFormat, glType, srcTexture.image.data );
  17017. } else {
  17018. if ( srcTexture.isCompressedTexture ) {
  17019. _gl.compressedTexSubImage2D( 3553, level, position.x, position.y, srcTexture.mipmaps[ 0 ].width, srcTexture.mipmaps[ 0 ].height, glFormat, srcTexture.mipmaps[ 0 ].data );
  17020. } else {
  17021. _gl.texSubImage2D( 3553, level, position.x, position.y, glFormat, glType, srcTexture.image );
  17022. }
  17023. }
  17024. // Generate mipmaps only when copying level 0
  17025. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( 3553 );
  17026. state.unbindTexture();
  17027. };
  17028. this.copyTextureToTexture3D = function ( sourceBox, position, srcTexture, dstTexture, level = 0 ) {
  17029. if ( _this.isWebGL1Renderer ) {
  17030. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: can only be used with WebGL2.' );
  17031. return;
  17032. }
  17033. const width = sourceBox.max.x - sourceBox.min.x + 1;
  17034. const height = sourceBox.max.y - sourceBox.min.y + 1;
  17035. const depth = sourceBox.max.z - sourceBox.min.z + 1;
  17036. const glFormat = utils.convert( dstTexture.format );
  17037. const glType = utils.convert( dstTexture.type );
  17038. let glTarget;
  17039. if ( dstTexture.isData3DTexture ) {
  17040. textures.setTexture3D( dstTexture, 0 );
  17041. glTarget = 32879;
  17042. } else if ( dstTexture.isDataArrayTexture ) {
  17043. textures.setTexture2DArray( dstTexture, 0 );
  17044. glTarget = 35866;
  17045. } else {
  17046. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: only supports THREE.DataTexture3D and THREE.DataTexture2DArray.' );
  17047. return;
  17048. }
  17049. _gl.pixelStorei( 37440, dstTexture.flipY );
  17050. _gl.pixelStorei( 37441, dstTexture.premultiplyAlpha );
  17051. _gl.pixelStorei( 3317, dstTexture.unpackAlignment );
  17052. const unpackRowLen = _gl.getParameter( 3314 );
  17053. const unpackImageHeight = _gl.getParameter( 32878 );
  17054. const unpackSkipPixels = _gl.getParameter( 3316 );
  17055. const unpackSkipRows = _gl.getParameter( 3315 );
  17056. const unpackSkipImages = _gl.getParameter( 32877 );
  17057. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ 0 ] : srcTexture.image;
  17058. _gl.pixelStorei( 3314, image.width );
  17059. _gl.pixelStorei( 32878, image.height );
  17060. _gl.pixelStorei( 3316, sourceBox.min.x );
  17061. _gl.pixelStorei( 3315, sourceBox.min.y );
  17062. _gl.pixelStorei( 32877, sourceBox.min.z );
  17063. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  17064. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image.data );
  17065. } else {
  17066. if ( srcTexture.isCompressedTexture ) {
  17067. console.warn( 'THREE.WebGLRenderer.copyTextureToTexture3D: untested support for compressed srcTexture.' );
  17068. _gl.compressedTexSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, image.data );
  17069. } else {
  17070. _gl.texSubImage3D( glTarget, level, position.x, position.y, position.z, width, height, depth, glFormat, glType, image );
  17071. }
  17072. }
  17073. _gl.pixelStorei( 3314, unpackRowLen );
  17074. _gl.pixelStorei( 32878, unpackImageHeight );
  17075. _gl.pixelStorei( 3316, unpackSkipPixels );
  17076. _gl.pixelStorei( 3315, unpackSkipRows );
  17077. _gl.pixelStorei( 32877, unpackSkipImages );
  17078. // Generate mipmaps only when copying level 0
  17079. if ( level === 0 && dstTexture.generateMipmaps ) _gl.generateMipmap( glTarget );
  17080. state.unbindTexture();
  17081. };
  17082. this.initTexture = function ( texture ) {
  17083. if ( texture.isCubeTexture ) {
  17084. textures.setTextureCube( texture, 0 );
  17085. } else if ( texture.isData3DTexture ) {
  17086. textures.setTexture3D( texture, 0 );
  17087. } else if ( texture.isDataArrayTexture ) {
  17088. textures.setTexture2DArray( texture, 0 );
  17089. } else {
  17090. textures.setTexture2D( texture, 0 );
  17091. }
  17092. state.unbindTexture();
  17093. };
  17094. this.resetState = function () {
  17095. _currentActiveCubeFace = 0;
  17096. _currentActiveMipmapLevel = 0;
  17097. _currentRenderTarget = null;
  17098. state.reset();
  17099. bindingStates.reset();
  17100. };
  17101. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17102. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17103. }
  17104. }
  17105. class WebGL1Renderer extends WebGLRenderer {}
  17106. WebGL1Renderer.prototype.isWebGL1Renderer = true;
  17107. class FogExp2 {
  17108. constructor( color, density = 0.00025 ) {
  17109. this.isFogExp2 = true;
  17110. this.name = '';
  17111. this.color = new Color( color );
  17112. this.density = density;
  17113. }
  17114. clone() {
  17115. return new FogExp2( this.color, this.density );
  17116. }
  17117. toJSON( /* meta */ ) {
  17118. return {
  17119. type: 'FogExp2',
  17120. color: this.color.getHex(),
  17121. density: this.density
  17122. };
  17123. }
  17124. }
  17125. class Fog {
  17126. constructor( color, near = 1, far = 1000 ) {
  17127. this.isFog = true;
  17128. this.name = '';
  17129. this.color = new Color( color );
  17130. this.near = near;
  17131. this.far = far;
  17132. }
  17133. clone() {
  17134. return new Fog( this.color, this.near, this.far );
  17135. }
  17136. toJSON( /* meta */ ) {
  17137. return {
  17138. type: 'Fog',
  17139. color: this.color.getHex(),
  17140. near: this.near,
  17141. far: this.far
  17142. };
  17143. }
  17144. }
  17145. class Scene extends Object3D {
  17146. constructor() {
  17147. super();
  17148. this.isScene = true;
  17149. this.type = 'Scene';
  17150. this.background = null;
  17151. this.environment = null;
  17152. this.fog = null;
  17153. this.overrideMaterial = null;
  17154. this.autoUpdate = true; // checked by the renderer
  17155. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17156. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17157. }
  17158. }
  17159. copy( source, recursive ) {
  17160. super.copy( source, recursive );
  17161. if ( source.background !== null ) this.background = source.background.clone();
  17162. if ( source.environment !== null ) this.environment = source.environment.clone();
  17163. if ( source.fog !== null ) this.fog = source.fog.clone();
  17164. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17165. this.autoUpdate = source.autoUpdate;
  17166. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17167. return this;
  17168. }
  17169. toJSON( meta ) {
  17170. const data = super.toJSON( meta );
  17171. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17172. return data;
  17173. }
  17174. }
  17175. class InterleavedBuffer {
  17176. constructor( array, stride ) {
  17177. this.isInterleavedBuffer = true;
  17178. this.array = array;
  17179. this.stride = stride;
  17180. this.count = array !== undefined ? array.length / stride : 0;
  17181. this.usage = StaticDrawUsage;
  17182. this.updateRange = { offset: 0, count: - 1 };
  17183. this.version = 0;
  17184. this.uuid = generateUUID();
  17185. }
  17186. onUploadCallback() {}
  17187. set needsUpdate( value ) {
  17188. if ( value === true ) this.version ++;
  17189. }
  17190. setUsage( value ) {
  17191. this.usage = value;
  17192. return this;
  17193. }
  17194. copy( source ) {
  17195. this.array = new source.array.constructor( source.array );
  17196. this.count = source.count;
  17197. this.stride = source.stride;
  17198. this.usage = source.usage;
  17199. return this;
  17200. }
  17201. copyAt( index1, attribute, index2 ) {
  17202. index1 *= this.stride;
  17203. index2 *= attribute.stride;
  17204. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17205. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  17206. }
  17207. return this;
  17208. }
  17209. set( value, offset = 0 ) {
  17210. this.array.set( value, offset );
  17211. return this;
  17212. }
  17213. clone( data ) {
  17214. if ( data.arrayBuffers === undefined ) {
  17215. data.arrayBuffers = {};
  17216. }
  17217. if ( this.array.buffer._uuid === undefined ) {
  17218. this.array.buffer._uuid = generateUUID();
  17219. }
  17220. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17221. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17222. }
  17223. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17224. const ib = new this.constructor( array, this.stride );
  17225. ib.setUsage( this.usage );
  17226. return ib;
  17227. }
  17228. onUpload( callback ) {
  17229. this.onUploadCallback = callback;
  17230. return this;
  17231. }
  17232. toJSON( data ) {
  17233. if ( data.arrayBuffers === undefined ) {
  17234. data.arrayBuffers = {};
  17235. }
  17236. // generate UUID for array buffer if necessary
  17237. if ( this.array.buffer._uuid === undefined ) {
  17238. this.array.buffer._uuid = generateUUID();
  17239. }
  17240. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17241. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17242. }
  17243. //
  17244. return {
  17245. uuid: this.uuid,
  17246. buffer: this.array.buffer._uuid,
  17247. type: this.array.constructor.name,
  17248. stride: this.stride
  17249. };
  17250. }
  17251. }
  17252. const _vector$6 = /*@__PURE__*/ new Vector3();
  17253. class InterleavedBufferAttribute {
  17254. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17255. this.isInterleavedBufferAttribute = true;
  17256. this.name = '';
  17257. this.data = interleavedBuffer;
  17258. this.itemSize = itemSize;
  17259. this.offset = offset;
  17260. this.normalized = normalized === true;
  17261. }
  17262. get count() {
  17263. return this.data.count;
  17264. }
  17265. get array() {
  17266. return this.data.array;
  17267. }
  17268. set needsUpdate( value ) {
  17269. this.data.needsUpdate = value;
  17270. }
  17271. applyMatrix4( m ) {
  17272. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17273. _vector$6.fromBufferAttribute( this, i );
  17274. _vector$6.applyMatrix4( m );
  17275. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17276. }
  17277. return this;
  17278. }
  17279. applyNormalMatrix( m ) {
  17280. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17281. _vector$6.fromBufferAttribute( this, i );
  17282. _vector$6.applyNormalMatrix( m );
  17283. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17284. }
  17285. return this;
  17286. }
  17287. transformDirection( m ) {
  17288. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17289. _vector$6.fromBufferAttribute( this, i );
  17290. _vector$6.transformDirection( m );
  17291. this.setXYZ( i, _vector$6.x, _vector$6.y, _vector$6.z );
  17292. }
  17293. return this;
  17294. }
  17295. setX( index, x ) {
  17296. this.data.array[ index * this.data.stride + this.offset ] = x;
  17297. return this;
  17298. }
  17299. setY( index, y ) {
  17300. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17301. return this;
  17302. }
  17303. setZ( index, z ) {
  17304. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17305. return this;
  17306. }
  17307. setW( index, w ) {
  17308. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17309. return this;
  17310. }
  17311. getX( index ) {
  17312. return this.data.array[ index * this.data.stride + this.offset ];
  17313. }
  17314. getY( index ) {
  17315. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  17316. }
  17317. getZ( index ) {
  17318. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  17319. }
  17320. getW( index ) {
  17321. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  17322. }
  17323. setXY( index, x, y ) {
  17324. index = index * this.data.stride + this.offset;
  17325. this.data.array[ index + 0 ] = x;
  17326. this.data.array[ index + 1 ] = y;
  17327. return this;
  17328. }
  17329. setXYZ( index, x, y, z ) {
  17330. index = index * this.data.stride + this.offset;
  17331. this.data.array[ index + 0 ] = x;
  17332. this.data.array[ index + 1 ] = y;
  17333. this.data.array[ index + 2 ] = z;
  17334. return this;
  17335. }
  17336. setXYZW( index, x, y, z, w ) {
  17337. index = index * this.data.stride + this.offset;
  17338. this.data.array[ index + 0 ] = x;
  17339. this.data.array[ index + 1 ] = y;
  17340. this.data.array[ index + 2 ] = z;
  17341. this.data.array[ index + 3 ] = w;
  17342. return this;
  17343. }
  17344. clone( data ) {
  17345. if ( data === undefined ) {
  17346. console.log( 'THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will deinterleave buffer data.' );
  17347. const array = [];
  17348. for ( let i = 0; i < this.count; i ++ ) {
  17349. const index = i * this.data.stride + this.offset;
  17350. for ( let j = 0; j < this.itemSize; j ++ ) {
  17351. array.push( this.data.array[ index + j ] );
  17352. }
  17353. }
  17354. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17355. } else {
  17356. if ( data.interleavedBuffers === undefined ) {
  17357. data.interleavedBuffers = {};
  17358. }
  17359. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17360. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17361. }
  17362. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17363. }
  17364. }
  17365. toJSON( data ) {
  17366. if ( data === undefined ) {
  17367. console.log( 'THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will deinterleave buffer data.' );
  17368. const array = [];
  17369. for ( let i = 0; i < this.count; i ++ ) {
  17370. const index = i * this.data.stride + this.offset;
  17371. for ( let j = 0; j < this.itemSize; j ++ ) {
  17372. array.push( this.data.array[ index + j ] );
  17373. }
  17374. }
  17375. // deinterleave data and save it as an ordinary buffer attribute for now
  17376. return {
  17377. itemSize: this.itemSize,
  17378. type: this.array.constructor.name,
  17379. array: array,
  17380. normalized: this.normalized
  17381. };
  17382. } else {
  17383. // save as true interleaved attribtue
  17384. if ( data.interleavedBuffers === undefined ) {
  17385. data.interleavedBuffers = {};
  17386. }
  17387. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17388. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17389. }
  17390. return {
  17391. isInterleavedBufferAttribute: true,
  17392. itemSize: this.itemSize,
  17393. data: this.data.uuid,
  17394. offset: this.offset,
  17395. normalized: this.normalized
  17396. };
  17397. }
  17398. }
  17399. }
  17400. class SpriteMaterial extends Material {
  17401. constructor( parameters ) {
  17402. super();
  17403. this.isSpriteMaterial = true;
  17404. this.type = 'SpriteMaterial';
  17405. this.color = new Color( 0xffffff );
  17406. this.map = null;
  17407. this.alphaMap = null;
  17408. this.rotation = 0;
  17409. this.sizeAttenuation = true;
  17410. this.transparent = true;
  17411. this.fog = true;
  17412. this.setValues( parameters );
  17413. }
  17414. copy( source ) {
  17415. super.copy( source );
  17416. this.color.copy( source.color );
  17417. this.map = source.map;
  17418. this.alphaMap = source.alphaMap;
  17419. this.rotation = source.rotation;
  17420. this.sizeAttenuation = source.sizeAttenuation;
  17421. this.fog = source.fog;
  17422. return this;
  17423. }
  17424. }
  17425. let _geometry;
  17426. const _intersectPoint = /*@__PURE__*/ new Vector3();
  17427. const _worldScale = /*@__PURE__*/ new Vector3();
  17428. const _mvPosition = /*@__PURE__*/ new Vector3();
  17429. const _alignedPosition = /*@__PURE__*/ new Vector2();
  17430. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  17431. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  17432. const _vA = /*@__PURE__*/ new Vector3();
  17433. const _vB = /*@__PURE__*/ new Vector3();
  17434. const _vC = /*@__PURE__*/ new Vector3();
  17435. const _uvA = /*@__PURE__*/ new Vector2();
  17436. const _uvB = /*@__PURE__*/ new Vector2();
  17437. const _uvC = /*@__PURE__*/ new Vector2();
  17438. class Sprite extends Object3D {
  17439. constructor( material ) {
  17440. super();
  17441. this.isSprite = true;
  17442. this.type = 'Sprite';
  17443. if ( _geometry === undefined ) {
  17444. _geometry = new BufferGeometry();
  17445. const float32Array = new Float32Array( [
  17446. - 0.5, - 0.5, 0, 0, 0,
  17447. 0.5, - 0.5, 0, 1, 0,
  17448. 0.5, 0.5, 0, 1, 1,
  17449. - 0.5, 0.5, 0, 0, 1
  17450. ] );
  17451. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  17452. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  17453. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  17454. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  17455. }
  17456. this.geometry = _geometry;
  17457. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  17458. this.center = new Vector2( 0.5, 0.5 );
  17459. }
  17460. raycast( raycaster, intersects ) {
  17461. if ( raycaster.camera === null ) {
  17462. console.error( 'THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  17463. }
  17464. _worldScale.setFromMatrixScale( this.matrixWorld );
  17465. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  17466. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  17467. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  17468. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  17469. _worldScale.multiplyScalar( - _mvPosition.z );
  17470. }
  17471. const rotation = this.material.rotation;
  17472. let sin, cos;
  17473. if ( rotation !== 0 ) {
  17474. cos = Math.cos( rotation );
  17475. sin = Math.sin( rotation );
  17476. }
  17477. const center = this.center;
  17478. transformVertex( _vA.set( - 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17479. transformVertex( _vB.set( 0.5, - 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17480. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17481. _uvA.set( 0, 0 );
  17482. _uvB.set( 1, 0 );
  17483. _uvC.set( 1, 1 );
  17484. // check first triangle
  17485. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  17486. if ( intersect === null ) {
  17487. // check second triangle
  17488. transformVertex( _vB.set( - 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  17489. _uvB.set( 0, 1 );
  17490. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  17491. if ( intersect === null ) {
  17492. return;
  17493. }
  17494. }
  17495. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  17496. if ( distance < raycaster.near || distance > raycaster.far ) return;
  17497. intersects.push( {
  17498. distance: distance,
  17499. point: _intersectPoint.clone(),
  17500. uv: Triangle.getUV( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  17501. face: null,
  17502. object: this
  17503. } );
  17504. }
  17505. copy( source, recursive ) {
  17506. super.copy( source, recursive );
  17507. if ( source.center !== undefined ) this.center.copy( source.center );
  17508. this.material = source.material;
  17509. return this;
  17510. }
  17511. }
  17512. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  17513. // compute position in camera space
  17514. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  17515. // to check if rotation is not zero
  17516. if ( sin !== undefined ) {
  17517. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  17518. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  17519. } else {
  17520. _rotatedPosition.copy( _alignedPosition );
  17521. }
  17522. vertexPosition.copy( mvPosition );
  17523. vertexPosition.x += _rotatedPosition.x;
  17524. vertexPosition.y += _rotatedPosition.y;
  17525. // transform to world space
  17526. vertexPosition.applyMatrix4( _viewWorldMatrix );
  17527. }
  17528. const _v1$2 = /*@__PURE__*/ new Vector3();
  17529. const _v2$1 = /*@__PURE__*/ new Vector3();
  17530. class LOD extends Object3D {
  17531. constructor() {
  17532. super();
  17533. this._currentLevel = 0;
  17534. this.type = 'LOD';
  17535. Object.defineProperties( this, {
  17536. levels: {
  17537. enumerable: true,
  17538. value: []
  17539. },
  17540. isLOD: {
  17541. value: true,
  17542. }
  17543. } );
  17544. this.autoUpdate = true;
  17545. }
  17546. copy( source ) {
  17547. super.copy( source, false );
  17548. const levels = source.levels;
  17549. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  17550. const level = levels[ i ];
  17551. this.addLevel( level.object.clone(), level.distance );
  17552. }
  17553. this.autoUpdate = source.autoUpdate;
  17554. return this;
  17555. }
  17556. addLevel( object, distance = 0 ) {
  17557. distance = Math.abs( distance );
  17558. const levels = this.levels;
  17559. let l;
  17560. for ( l = 0; l < levels.length; l ++ ) {
  17561. if ( distance < levels[ l ].distance ) {
  17562. break;
  17563. }
  17564. }
  17565. levels.splice( l, 0, { distance: distance, object: object } );
  17566. this.add( object );
  17567. return this;
  17568. }
  17569. getCurrentLevel() {
  17570. return this._currentLevel;
  17571. }
  17572. getObjectForDistance( distance ) {
  17573. const levels = this.levels;
  17574. if ( levels.length > 0 ) {
  17575. let i, l;
  17576. for ( i = 1, l = levels.length; i < l; i ++ ) {
  17577. if ( distance < levels[ i ].distance ) {
  17578. break;
  17579. }
  17580. }
  17581. return levels[ i - 1 ].object;
  17582. }
  17583. return null;
  17584. }
  17585. raycast( raycaster, intersects ) {
  17586. const levels = this.levels;
  17587. if ( levels.length > 0 ) {
  17588. _v1$2.setFromMatrixPosition( this.matrixWorld );
  17589. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  17590. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  17591. }
  17592. }
  17593. update( camera ) {
  17594. const levels = this.levels;
  17595. if ( levels.length > 1 ) {
  17596. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  17597. _v2$1.setFromMatrixPosition( this.matrixWorld );
  17598. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  17599. levels[ 0 ].object.visible = true;
  17600. let i, l;
  17601. for ( i = 1, l = levels.length; i < l; i ++ ) {
  17602. if ( distance >= levels[ i ].distance ) {
  17603. levels[ i - 1 ].object.visible = false;
  17604. levels[ i ].object.visible = true;
  17605. } else {
  17606. break;
  17607. }
  17608. }
  17609. this._currentLevel = i - 1;
  17610. for ( ; i < l; i ++ ) {
  17611. levels[ i ].object.visible = false;
  17612. }
  17613. }
  17614. }
  17615. toJSON( meta ) {
  17616. const data = super.toJSON( meta );
  17617. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  17618. data.object.levels = [];
  17619. const levels = this.levels;
  17620. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  17621. const level = levels[ i ];
  17622. data.object.levels.push( {
  17623. object: level.object.uuid,
  17624. distance: level.distance
  17625. } );
  17626. }
  17627. return data;
  17628. }
  17629. }
  17630. const _basePosition = /*@__PURE__*/ new Vector3();
  17631. const _skinIndex = /*@__PURE__*/ new Vector4();
  17632. const _skinWeight = /*@__PURE__*/ new Vector4();
  17633. const _vector$5 = /*@__PURE__*/ new Vector3();
  17634. const _matrix = /*@__PURE__*/ new Matrix4();
  17635. class SkinnedMesh extends Mesh {
  17636. constructor( geometry, material ) {
  17637. super( geometry, material );
  17638. this.isSkinnedMesh = true;
  17639. this.type = 'SkinnedMesh';
  17640. this.bindMode = 'attached';
  17641. this.bindMatrix = new Matrix4();
  17642. this.bindMatrixInverse = new Matrix4();
  17643. }
  17644. copy( source, recursive ) {
  17645. super.copy( source, recursive );
  17646. this.bindMode = source.bindMode;
  17647. this.bindMatrix.copy( source.bindMatrix );
  17648. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  17649. this.skeleton = source.skeleton;
  17650. return this;
  17651. }
  17652. bind( skeleton, bindMatrix ) {
  17653. this.skeleton = skeleton;
  17654. if ( bindMatrix === undefined ) {
  17655. this.updateMatrixWorld( true );
  17656. this.skeleton.calculateInverses();
  17657. bindMatrix = this.matrixWorld;
  17658. }
  17659. this.bindMatrix.copy( bindMatrix );
  17660. this.bindMatrixInverse.copy( bindMatrix ).invert();
  17661. }
  17662. pose() {
  17663. this.skeleton.pose();
  17664. }
  17665. normalizeSkinWeights() {
  17666. const vector = new Vector4();
  17667. const skinWeight = this.geometry.attributes.skinWeight;
  17668. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  17669. vector.fromBufferAttribute( skinWeight, i );
  17670. const scale = 1.0 / vector.manhattanLength();
  17671. if ( scale !== Infinity ) {
  17672. vector.multiplyScalar( scale );
  17673. } else {
  17674. vector.set( 1, 0, 0, 0 ); // do something reasonable
  17675. }
  17676. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  17677. }
  17678. }
  17679. updateMatrixWorld( force ) {
  17680. super.updateMatrixWorld( force );
  17681. if ( this.bindMode === 'attached' ) {
  17682. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  17683. } else if ( this.bindMode === 'detached' ) {
  17684. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  17685. } else {
  17686. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  17687. }
  17688. }
  17689. boneTransform( index, target ) {
  17690. const skeleton = this.skeleton;
  17691. const geometry = this.geometry;
  17692. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  17693. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  17694. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  17695. target.set( 0, 0, 0 );
  17696. for ( let i = 0; i < 4; i ++ ) {
  17697. const weight = _skinWeight.getComponent( i );
  17698. if ( weight !== 0 ) {
  17699. const boneIndex = _skinIndex.getComponent( i );
  17700. _matrix.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  17701. target.addScaledVector( _vector$5.copy( _basePosition ).applyMatrix4( _matrix ), weight );
  17702. }
  17703. }
  17704. return target.applyMatrix4( this.bindMatrixInverse );
  17705. }
  17706. }
  17707. class Bone extends Object3D {
  17708. constructor() {
  17709. super();
  17710. this.isBone = true;
  17711. this.type = 'Bone';
  17712. }
  17713. }
  17714. class DataTexture extends Texture {
  17715. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, encoding ) {
  17716. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  17717. this.isDataTexture = true;
  17718. this.image = { data: data, width: width, height: height };
  17719. this.generateMipmaps = false;
  17720. this.flipY = false;
  17721. this.unpackAlignment = 1;
  17722. }
  17723. }
  17724. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  17725. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  17726. class Skeleton {
  17727. constructor( bones = [], boneInverses = [] ) {
  17728. this.uuid = generateUUID();
  17729. this.bones = bones.slice( 0 );
  17730. this.boneInverses = boneInverses;
  17731. this.boneMatrices = null;
  17732. this.boneTexture = null;
  17733. this.boneTextureSize = 0;
  17734. this.frame = - 1;
  17735. this.init();
  17736. }
  17737. init() {
  17738. const bones = this.bones;
  17739. const boneInverses = this.boneInverses;
  17740. this.boneMatrices = new Float32Array( bones.length * 16 );
  17741. // calculate inverse bone matrices if necessary
  17742. if ( boneInverses.length === 0 ) {
  17743. this.calculateInverses();
  17744. } else {
  17745. // handle special case
  17746. if ( bones.length !== boneInverses.length ) {
  17747. console.warn( 'THREE.Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  17748. this.boneInverses = [];
  17749. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17750. this.boneInverses.push( new Matrix4() );
  17751. }
  17752. }
  17753. }
  17754. }
  17755. calculateInverses() {
  17756. this.boneInverses.length = 0;
  17757. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17758. const inverse = new Matrix4();
  17759. if ( this.bones[ i ] ) {
  17760. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  17761. }
  17762. this.boneInverses.push( inverse );
  17763. }
  17764. }
  17765. pose() {
  17766. // recover the bind-time world matrices
  17767. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17768. const bone = this.bones[ i ];
  17769. if ( bone ) {
  17770. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  17771. }
  17772. }
  17773. // compute the local matrices, positions, rotations and scales
  17774. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17775. const bone = this.bones[ i ];
  17776. if ( bone ) {
  17777. if ( bone.parent && bone.parent.isBone ) {
  17778. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  17779. bone.matrix.multiply( bone.matrixWorld );
  17780. } else {
  17781. bone.matrix.copy( bone.matrixWorld );
  17782. }
  17783. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  17784. }
  17785. }
  17786. }
  17787. update() {
  17788. const bones = this.bones;
  17789. const boneInverses = this.boneInverses;
  17790. const boneMatrices = this.boneMatrices;
  17791. const boneTexture = this.boneTexture;
  17792. // flatten bone matrices to array
  17793. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  17794. // compute the offset between the current and the original transform
  17795. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  17796. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  17797. _offsetMatrix.toArray( boneMatrices, i * 16 );
  17798. }
  17799. if ( boneTexture !== null ) {
  17800. boneTexture.needsUpdate = true;
  17801. }
  17802. }
  17803. clone() {
  17804. return new Skeleton( this.bones, this.boneInverses );
  17805. }
  17806. computeBoneTexture() {
  17807. // layout (1 matrix = 4 pixels)
  17808. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  17809. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  17810. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  17811. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  17812. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  17813. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  17814. size = ceilPowerOfTwo( size );
  17815. size = Math.max( size, 4 );
  17816. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  17817. boneMatrices.set( this.boneMatrices ); // copy current values
  17818. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  17819. boneTexture.needsUpdate = true;
  17820. this.boneMatrices = boneMatrices;
  17821. this.boneTexture = boneTexture;
  17822. this.boneTextureSize = size;
  17823. return this;
  17824. }
  17825. getBoneByName( name ) {
  17826. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  17827. const bone = this.bones[ i ];
  17828. if ( bone.name === name ) {
  17829. return bone;
  17830. }
  17831. }
  17832. return undefined;
  17833. }
  17834. dispose( ) {
  17835. if ( this.boneTexture !== null ) {
  17836. this.boneTexture.dispose();
  17837. this.boneTexture = null;
  17838. }
  17839. }
  17840. fromJSON( json, bones ) {
  17841. this.uuid = json.uuid;
  17842. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  17843. const uuid = json.bones[ i ];
  17844. let bone = bones[ uuid ];
  17845. if ( bone === undefined ) {
  17846. console.warn( 'THREE.Skeleton: No bone found with UUID:', uuid );
  17847. bone = new Bone();
  17848. }
  17849. this.bones.push( bone );
  17850. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  17851. }
  17852. this.init();
  17853. return this;
  17854. }
  17855. toJSON() {
  17856. const data = {
  17857. metadata: {
  17858. version: 4.5,
  17859. type: 'Skeleton',
  17860. generator: 'Skeleton.toJSON'
  17861. },
  17862. bones: [],
  17863. boneInverses: []
  17864. };
  17865. data.uuid = this.uuid;
  17866. const bones = this.bones;
  17867. const boneInverses = this.boneInverses;
  17868. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  17869. const bone = bones[ i ];
  17870. data.bones.push( bone.uuid );
  17871. const boneInverse = boneInverses[ i ];
  17872. data.boneInverses.push( boneInverse.toArray() );
  17873. }
  17874. return data;
  17875. }
  17876. }
  17877. class InstancedBufferAttribute extends BufferAttribute {
  17878. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  17879. super( array, itemSize, normalized );
  17880. this.isInstancedBufferAttribute = true;
  17881. this.meshPerAttribute = meshPerAttribute;
  17882. }
  17883. copy( source ) {
  17884. super.copy( source );
  17885. this.meshPerAttribute = source.meshPerAttribute;
  17886. return this;
  17887. }
  17888. toJSON() {
  17889. const data = super.toJSON();
  17890. data.meshPerAttribute = this.meshPerAttribute;
  17891. data.isInstancedBufferAttribute = true;
  17892. return data;
  17893. }
  17894. }
  17895. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  17896. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  17897. const _instanceIntersects = [];
  17898. const _mesh = /*@__PURE__*/ new Mesh();
  17899. class InstancedMesh extends Mesh {
  17900. constructor( geometry, material, count ) {
  17901. super( geometry, material );
  17902. this.isInstancedMesh = true;
  17903. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  17904. this.instanceColor = null;
  17905. this.count = count;
  17906. this.frustumCulled = false;
  17907. }
  17908. copy( source, recursive ) {
  17909. super.copy( source, recursive );
  17910. this.instanceMatrix.copy( source.instanceMatrix );
  17911. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  17912. this.count = source.count;
  17913. return this;
  17914. }
  17915. getColorAt( index, color ) {
  17916. color.fromArray( this.instanceColor.array, index * 3 );
  17917. }
  17918. getMatrixAt( index, matrix ) {
  17919. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  17920. }
  17921. raycast( raycaster, intersects ) {
  17922. const matrixWorld = this.matrixWorld;
  17923. const raycastTimes = this.count;
  17924. _mesh.geometry = this.geometry;
  17925. _mesh.material = this.material;
  17926. if ( _mesh.material === undefined ) return;
  17927. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  17928. // calculate the world matrix for each instance
  17929. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  17930. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  17931. // the mesh represents this single instance
  17932. _mesh.matrixWorld = _instanceWorldMatrix;
  17933. _mesh.raycast( raycaster, _instanceIntersects );
  17934. // process the result of raycast
  17935. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  17936. const intersect = _instanceIntersects[ i ];
  17937. intersect.instanceId = instanceId;
  17938. intersect.object = this;
  17939. intersects.push( intersect );
  17940. }
  17941. _instanceIntersects.length = 0;
  17942. }
  17943. }
  17944. setColorAt( index, color ) {
  17945. if ( this.instanceColor === null ) {
  17946. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ), 3 );
  17947. }
  17948. color.toArray( this.instanceColor.array, index * 3 );
  17949. }
  17950. setMatrixAt( index, matrix ) {
  17951. matrix.toArray( this.instanceMatrix.array, index * 16 );
  17952. }
  17953. updateMorphTargets() {
  17954. }
  17955. dispose() {
  17956. this.dispatchEvent( { type: 'dispose' } );
  17957. }
  17958. }
  17959. class LineBasicMaterial extends Material {
  17960. constructor( parameters ) {
  17961. super();
  17962. this.isLineBasicMaterial = true;
  17963. this.type = 'LineBasicMaterial';
  17964. this.color = new Color( 0xffffff );
  17965. this.linewidth = 1;
  17966. this.linecap = 'round';
  17967. this.linejoin = 'round';
  17968. this.fog = true;
  17969. this.setValues( parameters );
  17970. }
  17971. copy( source ) {
  17972. super.copy( source );
  17973. this.color.copy( source.color );
  17974. this.linewidth = source.linewidth;
  17975. this.linecap = source.linecap;
  17976. this.linejoin = source.linejoin;
  17977. this.fog = source.fog;
  17978. return this;
  17979. }
  17980. }
  17981. const _start$1 = /*@__PURE__*/ new Vector3();
  17982. const _end$1 = /*@__PURE__*/ new Vector3();
  17983. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  17984. const _ray$1 = /*@__PURE__*/ new Ray();
  17985. const _sphere$1 = /*@__PURE__*/ new Sphere();
  17986. class Line extends Object3D {
  17987. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  17988. super();
  17989. this.isLine = true;
  17990. this.type = 'Line';
  17991. this.geometry = geometry;
  17992. this.material = material;
  17993. this.updateMorphTargets();
  17994. }
  17995. copy( source, recursive ) {
  17996. super.copy( source, recursive );
  17997. this.material = source.material;
  17998. this.geometry = source.geometry;
  17999. return this;
  18000. }
  18001. computeLineDistances() {
  18002. const geometry = this.geometry;
  18003. // we assume non-indexed geometry
  18004. if ( geometry.index === null ) {
  18005. const positionAttribute = geometry.attributes.position;
  18006. const lineDistances = [ 0 ];
  18007. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  18008. _start$1.fromBufferAttribute( positionAttribute, i - 1 );
  18009. _end$1.fromBufferAttribute( positionAttribute, i );
  18010. lineDistances[ i ] = lineDistances[ i - 1 ];
  18011. lineDistances[ i ] += _start$1.distanceTo( _end$1 );
  18012. }
  18013. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18014. } else {
  18015. console.warn( 'THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18016. }
  18017. return this;
  18018. }
  18019. raycast( raycaster, intersects ) {
  18020. const geometry = this.geometry;
  18021. const matrixWorld = this.matrixWorld;
  18022. const threshold = raycaster.params.Line.threshold;
  18023. const drawRange = geometry.drawRange;
  18024. // Checking boundingSphere distance to ray
  18025. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18026. _sphere$1.copy( geometry.boundingSphere );
  18027. _sphere$1.applyMatrix4( matrixWorld );
  18028. _sphere$1.radius += threshold;
  18029. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  18030. //
  18031. _inverseMatrix$1.copy( matrixWorld ).invert();
  18032. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  18033. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18034. const localThresholdSq = localThreshold * localThreshold;
  18035. const vStart = new Vector3();
  18036. const vEnd = new Vector3();
  18037. const interSegment = new Vector3();
  18038. const interRay = new Vector3();
  18039. const step = this.isLineSegments ? 2 : 1;
  18040. const index = geometry.index;
  18041. const attributes = geometry.attributes;
  18042. const positionAttribute = attributes.position;
  18043. if ( index !== null ) {
  18044. const start = Math.max( 0, drawRange.start );
  18045. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  18046. for ( let i = start, l = end - 1; i < l; i += step ) {
  18047. const a = index.getX( i );
  18048. const b = index.getX( i + 1 );
  18049. vStart.fromBufferAttribute( positionAttribute, a );
  18050. vEnd.fromBufferAttribute( positionAttribute, b );
  18051. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18052. if ( distSq > localThresholdSq ) continue;
  18053. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18054. const distance = raycaster.ray.origin.distanceTo( interRay );
  18055. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18056. intersects.push( {
  18057. distance: distance,
  18058. // What do we want? intersection point on the ray or on the segment??
  18059. // point: raycaster.ray.at( distance ),
  18060. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18061. index: i,
  18062. face: null,
  18063. faceIndex: null,
  18064. object: this
  18065. } );
  18066. }
  18067. } else {
  18068. const start = Math.max( 0, drawRange.start );
  18069. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  18070. for ( let i = start, l = end - 1; i < l; i += step ) {
  18071. vStart.fromBufferAttribute( positionAttribute, i );
  18072. vEnd.fromBufferAttribute( positionAttribute, i + 1 );
  18073. const distSq = _ray$1.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18074. if ( distSq > localThresholdSq ) continue;
  18075. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18076. const distance = raycaster.ray.origin.distanceTo( interRay );
  18077. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18078. intersects.push( {
  18079. distance: distance,
  18080. // What do we want? intersection point on the ray or on the segment??
  18081. // point: raycaster.ray.at( distance ),
  18082. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18083. index: i,
  18084. face: null,
  18085. faceIndex: null,
  18086. object: this
  18087. } );
  18088. }
  18089. }
  18090. }
  18091. updateMorphTargets() {
  18092. const geometry = this.geometry;
  18093. const morphAttributes = geometry.morphAttributes;
  18094. const keys = Object.keys( morphAttributes );
  18095. if ( keys.length > 0 ) {
  18096. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  18097. if ( morphAttribute !== undefined ) {
  18098. this.morphTargetInfluences = [];
  18099. this.morphTargetDictionary = {};
  18100. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  18101. const name = morphAttribute[ m ].name || String( m );
  18102. this.morphTargetInfluences.push( 0 );
  18103. this.morphTargetDictionary[ name ] = m;
  18104. }
  18105. }
  18106. }
  18107. }
  18108. }
  18109. const _start = /*@__PURE__*/ new Vector3();
  18110. const _end = /*@__PURE__*/ new Vector3();
  18111. class LineSegments extends Line {
  18112. constructor( geometry, material ) {
  18113. super( geometry, material );
  18114. this.isLineSegments = true;
  18115. this.type = 'LineSegments';
  18116. }
  18117. computeLineDistances() {
  18118. const geometry = this.geometry;
  18119. // we assume non-indexed geometry
  18120. if ( geometry.index === null ) {
  18121. const positionAttribute = geometry.attributes.position;
  18122. const lineDistances = [];
  18123. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  18124. _start.fromBufferAttribute( positionAttribute, i );
  18125. _end.fromBufferAttribute( positionAttribute, i + 1 );
  18126. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  18127. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  18128. }
  18129. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  18130. } else {
  18131. console.warn( 'THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  18132. }
  18133. return this;
  18134. }
  18135. }
  18136. class LineLoop extends Line {
  18137. constructor( geometry, material ) {
  18138. super( geometry, material );
  18139. this.isLineLoop = true;
  18140. this.type = 'LineLoop';
  18141. }
  18142. }
  18143. class PointsMaterial extends Material {
  18144. constructor( parameters ) {
  18145. super();
  18146. this.isPointsMaterial = true;
  18147. this.type = 'PointsMaterial';
  18148. this.color = new Color( 0xffffff );
  18149. this.map = null;
  18150. this.alphaMap = null;
  18151. this.size = 1;
  18152. this.sizeAttenuation = true;
  18153. this.fog = true;
  18154. this.setValues( parameters );
  18155. }
  18156. copy( source ) {
  18157. super.copy( source );
  18158. this.color.copy( source.color );
  18159. this.map = source.map;
  18160. this.alphaMap = source.alphaMap;
  18161. this.size = source.size;
  18162. this.sizeAttenuation = source.sizeAttenuation;
  18163. this.fog = source.fog;
  18164. return this;
  18165. }
  18166. }
  18167. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  18168. const _ray = /*@__PURE__*/ new Ray();
  18169. const _sphere = /*@__PURE__*/ new Sphere();
  18170. const _position$2 = /*@__PURE__*/ new Vector3();
  18171. class Points extends Object3D {
  18172. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  18173. super();
  18174. this.isPoints = true;
  18175. this.type = 'Points';
  18176. this.geometry = geometry;
  18177. this.material = material;
  18178. this.updateMorphTargets();
  18179. }
  18180. copy( source, recursive ) {
  18181. super.copy( source, recursive );
  18182. this.material = source.material;
  18183. this.geometry = source.geometry;
  18184. return this;
  18185. }
  18186. raycast( raycaster, intersects ) {
  18187. const geometry = this.geometry;
  18188. const matrixWorld = this.matrixWorld;
  18189. const threshold = raycaster.params.Points.threshold;
  18190. const drawRange = geometry.drawRange;
  18191. // Checking boundingSphere distance to ray
  18192. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18193. _sphere.copy( geometry.boundingSphere );
  18194. _sphere.applyMatrix4( matrixWorld );
  18195. _sphere.radius += threshold;
  18196. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  18197. //
  18198. _inverseMatrix.copy( matrixWorld ).invert();
  18199. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  18200. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18201. const localThresholdSq = localThreshold * localThreshold;
  18202. const index = geometry.index;
  18203. const attributes = geometry.attributes;
  18204. const positionAttribute = attributes.position;
  18205. if ( index !== null ) {
  18206. const start = Math.max( 0, drawRange.start );
  18207. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  18208. for ( let i = start, il = end; i < il; i ++ ) {
  18209. const a = index.getX( i );
  18210. _position$2.fromBufferAttribute( positionAttribute, a );
  18211. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  18212. }
  18213. } else {
  18214. const start = Math.max( 0, drawRange.start );
  18215. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  18216. for ( let i = start, l = end; i < l; i ++ ) {
  18217. _position$2.fromBufferAttribute( positionAttribute, i );
  18218. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  18219. }
  18220. }
  18221. }
  18222. updateMorphTargets() {
  18223. const geometry = this.geometry;
  18224. const morphAttributes = geometry.morphAttributes;
  18225. const keys = Object.keys( morphAttributes );
  18226. if ( keys.length > 0 ) {
  18227. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  18228. if ( morphAttribute !== undefined ) {
  18229. this.morphTargetInfluences = [];
  18230. this.morphTargetDictionary = {};
  18231. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  18232. const name = morphAttribute[ m ].name || String( m );
  18233. this.morphTargetInfluences.push( 0 );
  18234. this.morphTargetDictionary[ name ] = m;
  18235. }
  18236. }
  18237. }
  18238. }
  18239. }
  18240. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  18241. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  18242. if ( rayPointDistanceSq < localThresholdSq ) {
  18243. const intersectPoint = new Vector3();
  18244. _ray.closestPointToPoint( point, intersectPoint );
  18245. intersectPoint.applyMatrix4( matrixWorld );
  18246. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  18247. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18248. intersects.push( {
  18249. distance: distance,
  18250. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  18251. point: intersectPoint,
  18252. index: index,
  18253. face: null,
  18254. object: object
  18255. } );
  18256. }
  18257. }
  18258. class VideoTexture extends Texture {
  18259. constructor( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18260. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18261. this.isVideoTexture = true;
  18262. this.minFilter = minFilter !== undefined ? minFilter : LinearFilter;
  18263. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  18264. this.generateMipmaps = false;
  18265. const scope = this;
  18266. function updateVideo() {
  18267. scope.needsUpdate = true;
  18268. video.requestVideoFrameCallback( updateVideo );
  18269. }
  18270. if ( 'requestVideoFrameCallback' in video ) {
  18271. video.requestVideoFrameCallback( updateVideo );
  18272. }
  18273. }
  18274. clone() {
  18275. return new this.constructor( this.image ).copy( this );
  18276. }
  18277. update() {
  18278. const video = this.image;
  18279. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  18280. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  18281. this.needsUpdate = true;
  18282. }
  18283. }
  18284. }
  18285. class FramebufferTexture extends Texture {
  18286. constructor( width, height, format ) {
  18287. super( { width, height } );
  18288. this.isFramebufferTexture = true;
  18289. this.format = format;
  18290. this.magFilter = NearestFilter;
  18291. this.minFilter = NearestFilter;
  18292. this.generateMipmaps = false;
  18293. this.needsUpdate = true;
  18294. }
  18295. }
  18296. class CompressedTexture extends Texture {
  18297. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  18298. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  18299. this.isCompressedTexture = true;
  18300. this.image = { width: width, height: height };
  18301. this.mipmaps = mipmaps;
  18302. // no flipping for cube textures
  18303. // (also flipping doesn't work for compressed textures )
  18304. this.flipY = false;
  18305. // can't generate mipmaps for compressed textures
  18306. // mips must be embedded in DDS files
  18307. this.generateMipmaps = false;
  18308. }
  18309. }
  18310. class CanvasTexture extends Texture {
  18311. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18312. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18313. this.isCanvasTexture = true;
  18314. this.needsUpdate = true;
  18315. }
  18316. }
  18317. /**
  18318. * Extensible curve object.
  18319. *
  18320. * Some common of curve methods:
  18321. * .getPoint( t, optionalTarget ), .getTangent( t, optionalTarget )
  18322. * .getPointAt( u, optionalTarget ), .getTangentAt( u, optionalTarget )
  18323. * .getPoints(), .getSpacedPoints()
  18324. * .getLength()
  18325. * .updateArcLengths()
  18326. *
  18327. * This following curves inherit from THREE.Curve:
  18328. *
  18329. * -- 2D curves --
  18330. * THREE.ArcCurve
  18331. * THREE.CubicBezierCurve
  18332. * THREE.EllipseCurve
  18333. * THREE.LineCurve
  18334. * THREE.QuadraticBezierCurve
  18335. * THREE.SplineCurve
  18336. *
  18337. * -- 3D curves --
  18338. * THREE.CatmullRomCurve3
  18339. * THREE.CubicBezierCurve3
  18340. * THREE.LineCurve3
  18341. * THREE.QuadraticBezierCurve3
  18342. *
  18343. * A series of curves can be represented as a THREE.CurvePath.
  18344. *
  18345. **/
  18346. class Curve {
  18347. constructor() {
  18348. this.type = 'Curve';
  18349. this.arcLengthDivisions = 200;
  18350. }
  18351. // Virtual base class method to overwrite and implement in subclasses
  18352. // - t [0 .. 1]
  18353. getPoint( /* t, optionalTarget */ ) {
  18354. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  18355. return null;
  18356. }
  18357. // Get point at relative position in curve according to arc length
  18358. // - u [0 .. 1]
  18359. getPointAt( u, optionalTarget ) {
  18360. const t = this.getUtoTmapping( u );
  18361. return this.getPoint( t, optionalTarget );
  18362. }
  18363. // Get sequence of points using getPoint( t )
  18364. getPoints( divisions = 5 ) {
  18365. const points = [];
  18366. for ( let d = 0; d <= divisions; d ++ ) {
  18367. points.push( this.getPoint( d / divisions ) );
  18368. }
  18369. return points;
  18370. }
  18371. // Get sequence of points using getPointAt( u )
  18372. getSpacedPoints( divisions = 5 ) {
  18373. const points = [];
  18374. for ( let d = 0; d <= divisions; d ++ ) {
  18375. points.push( this.getPointAt( d / divisions ) );
  18376. }
  18377. return points;
  18378. }
  18379. // Get total curve arc length
  18380. getLength() {
  18381. const lengths = this.getLengths();
  18382. return lengths[ lengths.length - 1 ];
  18383. }
  18384. // Get list of cumulative segment lengths
  18385. getLengths( divisions = this.arcLengthDivisions ) {
  18386. if ( this.cacheArcLengths &&
  18387. ( this.cacheArcLengths.length === divisions + 1 ) &&
  18388. ! this.needsUpdate ) {
  18389. return this.cacheArcLengths;
  18390. }
  18391. this.needsUpdate = false;
  18392. const cache = [];
  18393. let current, last = this.getPoint( 0 );
  18394. let sum = 0;
  18395. cache.push( 0 );
  18396. for ( let p = 1; p <= divisions; p ++ ) {
  18397. current = this.getPoint( p / divisions );
  18398. sum += current.distanceTo( last );
  18399. cache.push( sum );
  18400. last = current;
  18401. }
  18402. this.cacheArcLengths = cache;
  18403. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  18404. }
  18405. updateArcLengths() {
  18406. this.needsUpdate = true;
  18407. this.getLengths();
  18408. }
  18409. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  18410. getUtoTmapping( u, distance ) {
  18411. const arcLengths = this.getLengths();
  18412. let i = 0;
  18413. const il = arcLengths.length;
  18414. let targetArcLength; // The targeted u distance value to get
  18415. if ( distance ) {
  18416. targetArcLength = distance;
  18417. } else {
  18418. targetArcLength = u * arcLengths[ il - 1 ];
  18419. }
  18420. // binary search for the index with largest value smaller than target u distance
  18421. let low = 0, high = il - 1, comparison;
  18422. while ( low <= high ) {
  18423. 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
  18424. comparison = arcLengths[ i ] - targetArcLength;
  18425. if ( comparison < 0 ) {
  18426. low = i + 1;
  18427. } else if ( comparison > 0 ) {
  18428. high = i - 1;
  18429. } else {
  18430. high = i;
  18431. break;
  18432. // DONE
  18433. }
  18434. }
  18435. i = high;
  18436. if ( arcLengths[ i ] === targetArcLength ) {
  18437. return i / ( il - 1 );
  18438. }
  18439. // we could get finer grain at lengths, or use simple interpolation between two points
  18440. const lengthBefore = arcLengths[ i ];
  18441. const lengthAfter = arcLengths[ i + 1 ];
  18442. const segmentLength = lengthAfter - lengthBefore;
  18443. // determine where we are between the 'before' and 'after' points
  18444. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  18445. // add that fractional amount to t
  18446. const t = ( i + segmentFraction ) / ( il - 1 );
  18447. return t;
  18448. }
  18449. // Returns a unit vector tangent at t
  18450. // In case any sub curve does not implement its tangent derivation,
  18451. // 2 points a small delta apart will be used to find its gradient
  18452. // which seems to give a reasonable approximation
  18453. getTangent( t, optionalTarget ) {
  18454. const delta = 0.0001;
  18455. let t1 = t - delta;
  18456. let t2 = t + delta;
  18457. // Capping in case of danger
  18458. if ( t1 < 0 ) t1 = 0;
  18459. if ( t2 > 1 ) t2 = 1;
  18460. const pt1 = this.getPoint( t1 );
  18461. const pt2 = this.getPoint( t2 );
  18462. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  18463. tangent.copy( pt2 ).sub( pt1 ).normalize();
  18464. return tangent;
  18465. }
  18466. getTangentAt( u, optionalTarget ) {
  18467. const t = this.getUtoTmapping( u );
  18468. return this.getTangent( t, optionalTarget );
  18469. }
  18470. computeFrenetFrames( segments, closed ) {
  18471. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18472. const normal = new Vector3();
  18473. const tangents = [];
  18474. const normals = [];
  18475. const binormals = [];
  18476. const vec = new Vector3();
  18477. const mat = new Matrix4();
  18478. // compute the tangent vectors for each segment on the curve
  18479. for ( let i = 0; i <= segments; i ++ ) {
  18480. const u = i / segments;
  18481. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  18482. }
  18483. // select an initial normal vector perpendicular to the first tangent vector,
  18484. // and in the direction of the minimum tangent xyz component
  18485. normals[ 0 ] = new Vector3();
  18486. binormals[ 0 ] = new Vector3();
  18487. let min = Number.MAX_VALUE;
  18488. const tx = Math.abs( tangents[ 0 ].x );
  18489. const ty = Math.abs( tangents[ 0 ].y );
  18490. const tz = Math.abs( tangents[ 0 ].z );
  18491. if ( tx <= min ) {
  18492. min = tx;
  18493. normal.set( 1, 0, 0 );
  18494. }
  18495. if ( ty <= min ) {
  18496. min = ty;
  18497. normal.set( 0, 1, 0 );
  18498. }
  18499. if ( tz <= min ) {
  18500. normal.set( 0, 0, 1 );
  18501. }
  18502. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  18503. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  18504. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  18505. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  18506. for ( let i = 1; i <= segments; i ++ ) {
  18507. normals[ i ] = normals[ i - 1 ].clone();
  18508. binormals[ i ] = binormals[ i - 1 ].clone();
  18509. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  18510. if ( vec.length() > Number.EPSILON ) {
  18511. vec.normalize();
  18512. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  18513. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  18514. }
  18515. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18516. }
  18517. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18518. if ( closed === true ) {
  18519. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  18520. theta /= segments;
  18521. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  18522. theta = - theta;
  18523. }
  18524. for ( let i = 1; i <= segments; i ++ ) {
  18525. // twist a little...
  18526. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  18527. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  18528. }
  18529. }
  18530. return {
  18531. tangents: tangents,
  18532. normals: normals,
  18533. binormals: binormals
  18534. };
  18535. }
  18536. clone() {
  18537. return new this.constructor().copy( this );
  18538. }
  18539. copy( source ) {
  18540. this.arcLengthDivisions = source.arcLengthDivisions;
  18541. return this;
  18542. }
  18543. toJSON() {
  18544. const data = {
  18545. metadata: {
  18546. version: 4.5,
  18547. type: 'Curve',
  18548. generator: 'Curve.toJSON'
  18549. }
  18550. };
  18551. data.arcLengthDivisions = this.arcLengthDivisions;
  18552. data.type = this.type;
  18553. return data;
  18554. }
  18555. fromJSON( json ) {
  18556. this.arcLengthDivisions = json.arcLengthDivisions;
  18557. return this;
  18558. }
  18559. }
  18560. class EllipseCurve extends Curve {
  18561. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  18562. super();
  18563. this.isEllipseCurve = true;
  18564. this.type = 'EllipseCurve';
  18565. this.aX = aX;
  18566. this.aY = aY;
  18567. this.xRadius = xRadius;
  18568. this.yRadius = yRadius;
  18569. this.aStartAngle = aStartAngle;
  18570. this.aEndAngle = aEndAngle;
  18571. this.aClockwise = aClockwise;
  18572. this.aRotation = aRotation;
  18573. }
  18574. getPoint( t, optionalTarget ) {
  18575. const point = optionalTarget || new Vector2();
  18576. const twoPi = Math.PI * 2;
  18577. let deltaAngle = this.aEndAngle - this.aStartAngle;
  18578. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  18579. // ensures that deltaAngle is 0 .. 2 PI
  18580. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  18581. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  18582. if ( deltaAngle < Number.EPSILON ) {
  18583. if ( samePoints ) {
  18584. deltaAngle = 0;
  18585. } else {
  18586. deltaAngle = twoPi;
  18587. }
  18588. }
  18589. if ( this.aClockwise === true && ! samePoints ) {
  18590. if ( deltaAngle === twoPi ) {
  18591. deltaAngle = - twoPi;
  18592. } else {
  18593. deltaAngle = deltaAngle - twoPi;
  18594. }
  18595. }
  18596. const angle = this.aStartAngle + t * deltaAngle;
  18597. let x = this.aX + this.xRadius * Math.cos( angle );
  18598. let y = this.aY + this.yRadius * Math.sin( angle );
  18599. if ( this.aRotation !== 0 ) {
  18600. const cos = Math.cos( this.aRotation );
  18601. const sin = Math.sin( this.aRotation );
  18602. const tx = x - this.aX;
  18603. const ty = y - this.aY;
  18604. // Rotate the point about the center of the ellipse.
  18605. x = tx * cos - ty * sin + this.aX;
  18606. y = tx * sin + ty * cos + this.aY;
  18607. }
  18608. return point.set( x, y );
  18609. }
  18610. copy( source ) {
  18611. super.copy( source );
  18612. this.aX = source.aX;
  18613. this.aY = source.aY;
  18614. this.xRadius = source.xRadius;
  18615. this.yRadius = source.yRadius;
  18616. this.aStartAngle = source.aStartAngle;
  18617. this.aEndAngle = source.aEndAngle;
  18618. this.aClockwise = source.aClockwise;
  18619. this.aRotation = source.aRotation;
  18620. return this;
  18621. }
  18622. toJSON() {
  18623. const data = super.toJSON();
  18624. data.aX = this.aX;
  18625. data.aY = this.aY;
  18626. data.xRadius = this.xRadius;
  18627. data.yRadius = this.yRadius;
  18628. data.aStartAngle = this.aStartAngle;
  18629. data.aEndAngle = this.aEndAngle;
  18630. data.aClockwise = this.aClockwise;
  18631. data.aRotation = this.aRotation;
  18632. return data;
  18633. }
  18634. fromJSON( json ) {
  18635. super.fromJSON( json );
  18636. this.aX = json.aX;
  18637. this.aY = json.aY;
  18638. this.xRadius = json.xRadius;
  18639. this.yRadius = json.yRadius;
  18640. this.aStartAngle = json.aStartAngle;
  18641. this.aEndAngle = json.aEndAngle;
  18642. this.aClockwise = json.aClockwise;
  18643. this.aRotation = json.aRotation;
  18644. return this;
  18645. }
  18646. }
  18647. class ArcCurve extends EllipseCurve {
  18648. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18649. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18650. this.isArcCurve = true;
  18651. this.type = 'ArcCurve';
  18652. }
  18653. }
  18654. /**
  18655. * Centripetal CatmullRom Curve - which is useful for avoiding
  18656. * cusps and self-intersections in non-uniform catmull rom curves.
  18657. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  18658. *
  18659. * curve.type accepts centripetal(default), chordal and catmullrom
  18660. * curve.tension is used for catmullrom which defaults to 0.5
  18661. */
  18662. /*
  18663. Based on an optimized c++ solution in
  18664. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  18665. - http://ideone.com/NoEbVM
  18666. This CubicPoly class could be used for reusing some variables and calculations,
  18667. but for three.js curve use, it could be possible inlined and flatten into a single function call
  18668. which can be placed in CurveUtils.
  18669. */
  18670. function CubicPoly() {
  18671. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  18672. /*
  18673. * Compute coefficients for a cubic polynomial
  18674. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  18675. * such that
  18676. * p(0) = x0, p(1) = x1
  18677. * and
  18678. * p'(0) = t0, p'(1) = t1.
  18679. */
  18680. function init( x0, x1, t0, t1 ) {
  18681. c0 = x0;
  18682. c1 = t0;
  18683. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  18684. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  18685. }
  18686. return {
  18687. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  18688. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  18689. },
  18690. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  18691. // compute tangents when parameterized in [t1,t2]
  18692. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  18693. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  18694. // rescale tangents for parametrization in [0,1]
  18695. t1 *= dt1;
  18696. t2 *= dt1;
  18697. init( x1, x2, t1, t2 );
  18698. },
  18699. calc: function ( t ) {
  18700. const t2 = t * t;
  18701. const t3 = t2 * t;
  18702. return c0 + c1 * t + c2 * t2 + c3 * t3;
  18703. }
  18704. };
  18705. }
  18706. //
  18707. const tmp = /*@__PURE__*/ new Vector3();
  18708. const px = /*@__PURE__*/ new CubicPoly();
  18709. const py = /*@__PURE__*/ new CubicPoly();
  18710. const pz = /*@__PURE__*/ new CubicPoly();
  18711. class CatmullRomCurve3 extends Curve {
  18712. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  18713. super();
  18714. this.isCatmullRomCurve3 = true;
  18715. this.type = 'CatmullRomCurve3';
  18716. this.points = points;
  18717. this.closed = closed;
  18718. this.curveType = curveType;
  18719. this.tension = tension;
  18720. }
  18721. getPoint( t, optionalTarget = new Vector3() ) {
  18722. const point = optionalTarget;
  18723. const points = this.points;
  18724. const l = points.length;
  18725. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  18726. let intPoint = Math.floor( p );
  18727. let weight = p - intPoint;
  18728. if ( this.closed ) {
  18729. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  18730. } else if ( weight === 0 && intPoint === l - 1 ) {
  18731. intPoint = l - 2;
  18732. weight = 1;
  18733. }
  18734. let p0, p3; // 4 points (p1 & p2 defined below)
  18735. if ( this.closed || intPoint > 0 ) {
  18736. p0 = points[ ( intPoint - 1 ) % l ];
  18737. } else {
  18738. // extrapolate first point
  18739. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  18740. p0 = tmp;
  18741. }
  18742. const p1 = points[ intPoint % l ];
  18743. const p2 = points[ ( intPoint + 1 ) % l ];
  18744. if ( this.closed || intPoint + 2 < l ) {
  18745. p3 = points[ ( intPoint + 2 ) % l ];
  18746. } else {
  18747. // extrapolate last point
  18748. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  18749. p3 = tmp;
  18750. }
  18751. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  18752. // init Centripetal / Chordal Catmull-Rom
  18753. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  18754. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  18755. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  18756. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  18757. // safety check for repeated points
  18758. if ( dt1 < 1e-4 ) dt1 = 1.0;
  18759. if ( dt0 < 1e-4 ) dt0 = dt1;
  18760. if ( dt2 < 1e-4 ) dt2 = dt1;
  18761. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  18762. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  18763. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  18764. } else if ( this.curveType === 'catmullrom' ) {
  18765. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  18766. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  18767. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  18768. }
  18769. point.set(
  18770. px.calc( weight ),
  18771. py.calc( weight ),
  18772. pz.calc( weight )
  18773. );
  18774. return point;
  18775. }
  18776. copy( source ) {
  18777. super.copy( source );
  18778. this.points = [];
  18779. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  18780. const point = source.points[ i ];
  18781. this.points.push( point.clone() );
  18782. }
  18783. this.closed = source.closed;
  18784. this.curveType = source.curveType;
  18785. this.tension = source.tension;
  18786. return this;
  18787. }
  18788. toJSON() {
  18789. const data = super.toJSON();
  18790. data.points = [];
  18791. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  18792. const point = this.points[ i ];
  18793. data.points.push( point.toArray() );
  18794. }
  18795. data.closed = this.closed;
  18796. data.curveType = this.curveType;
  18797. data.tension = this.tension;
  18798. return data;
  18799. }
  18800. fromJSON( json ) {
  18801. super.fromJSON( json );
  18802. this.points = [];
  18803. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  18804. const point = json.points[ i ];
  18805. this.points.push( new Vector3().fromArray( point ) );
  18806. }
  18807. this.closed = json.closed;
  18808. this.curveType = json.curveType;
  18809. this.tension = json.tension;
  18810. return this;
  18811. }
  18812. }
  18813. /**
  18814. * Bezier Curves formulas obtained from
  18815. * https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  18816. */
  18817. function CatmullRom( t, p0, p1, p2, p3 ) {
  18818. const v0 = ( p2 - p0 ) * 0.5;
  18819. const v1 = ( p3 - p1 ) * 0.5;
  18820. const t2 = t * t;
  18821. const t3 = t * t2;
  18822. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18823. }
  18824. //
  18825. function QuadraticBezierP0( t, p ) {
  18826. const k = 1 - t;
  18827. return k * k * p;
  18828. }
  18829. function QuadraticBezierP1( t, p ) {
  18830. return 2 * ( 1 - t ) * t * p;
  18831. }
  18832. function QuadraticBezierP2( t, p ) {
  18833. return t * t * p;
  18834. }
  18835. function QuadraticBezier( t, p0, p1, p2 ) {
  18836. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  18837. QuadraticBezierP2( t, p2 );
  18838. }
  18839. //
  18840. function CubicBezierP0( t, p ) {
  18841. const k = 1 - t;
  18842. return k * k * k * p;
  18843. }
  18844. function CubicBezierP1( t, p ) {
  18845. const k = 1 - t;
  18846. return 3 * k * k * t * p;
  18847. }
  18848. function CubicBezierP2( t, p ) {
  18849. return 3 * ( 1 - t ) * t * t * p;
  18850. }
  18851. function CubicBezierP3( t, p ) {
  18852. return t * t * t * p;
  18853. }
  18854. function CubicBezier( t, p0, p1, p2, p3 ) {
  18855. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  18856. CubicBezierP3( t, p3 );
  18857. }
  18858. class CubicBezierCurve extends Curve {
  18859. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  18860. super();
  18861. this.isCubicBezierCurve = true;
  18862. this.type = 'CubicBezierCurve';
  18863. this.v0 = v0;
  18864. this.v1 = v1;
  18865. this.v2 = v2;
  18866. this.v3 = v3;
  18867. }
  18868. getPoint( t, optionalTarget = new Vector2() ) {
  18869. const point = optionalTarget;
  18870. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  18871. point.set(
  18872. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  18873. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  18874. );
  18875. return point;
  18876. }
  18877. copy( source ) {
  18878. super.copy( source );
  18879. this.v0.copy( source.v0 );
  18880. this.v1.copy( source.v1 );
  18881. this.v2.copy( source.v2 );
  18882. this.v3.copy( source.v3 );
  18883. return this;
  18884. }
  18885. toJSON() {
  18886. const data = super.toJSON();
  18887. data.v0 = this.v0.toArray();
  18888. data.v1 = this.v1.toArray();
  18889. data.v2 = this.v2.toArray();
  18890. data.v3 = this.v3.toArray();
  18891. return data;
  18892. }
  18893. fromJSON( json ) {
  18894. super.fromJSON( json );
  18895. this.v0.fromArray( json.v0 );
  18896. this.v1.fromArray( json.v1 );
  18897. this.v2.fromArray( json.v2 );
  18898. this.v3.fromArray( json.v3 );
  18899. return this;
  18900. }
  18901. }
  18902. class CubicBezierCurve3 extends Curve {
  18903. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  18904. super();
  18905. this.isCubicBezierCurve3 = true;
  18906. this.type = 'CubicBezierCurve3';
  18907. this.v0 = v0;
  18908. this.v1 = v1;
  18909. this.v2 = v2;
  18910. this.v3 = v3;
  18911. }
  18912. getPoint( t, optionalTarget = new Vector3() ) {
  18913. const point = optionalTarget;
  18914. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  18915. point.set(
  18916. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  18917. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  18918. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  18919. );
  18920. return point;
  18921. }
  18922. copy( source ) {
  18923. super.copy( source );
  18924. this.v0.copy( source.v0 );
  18925. this.v1.copy( source.v1 );
  18926. this.v2.copy( source.v2 );
  18927. this.v3.copy( source.v3 );
  18928. return this;
  18929. }
  18930. toJSON() {
  18931. const data = super.toJSON();
  18932. data.v0 = this.v0.toArray();
  18933. data.v1 = this.v1.toArray();
  18934. data.v2 = this.v2.toArray();
  18935. data.v3 = this.v3.toArray();
  18936. return data;
  18937. }
  18938. fromJSON( json ) {
  18939. super.fromJSON( json );
  18940. this.v0.fromArray( json.v0 );
  18941. this.v1.fromArray( json.v1 );
  18942. this.v2.fromArray( json.v2 );
  18943. this.v3.fromArray( json.v3 );
  18944. return this;
  18945. }
  18946. }
  18947. class LineCurve extends Curve {
  18948. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  18949. super();
  18950. this.isLineCurve = true;
  18951. this.type = 'LineCurve';
  18952. this.v1 = v1;
  18953. this.v2 = v2;
  18954. }
  18955. getPoint( t, optionalTarget = new Vector2() ) {
  18956. const point = optionalTarget;
  18957. if ( t === 1 ) {
  18958. point.copy( this.v2 );
  18959. } else {
  18960. point.copy( this.v2 ).sub( this.v1 );
  18961. point.multiplyScalar( t ).add( this.v1 );
  18962. }
  18963. return point;
  18964. }
  18965. // Line curve is linear, so we can overwrite default getPointAt
  18966. getPointAt( u, optionalTarget ) {
  18967. return this.getPoint( u, optionalTarget );
  18968. }
  18969. getTangent( t, optionalTarget ) {
  18970. const tangent = optionalTarget || new Vector2();
  18971. tangent.copy( this.v2 ).sub( this.v1 ).normalize();
  18972. return tangent;
  18973. }
  18974. copy( source ) {
  18975. super.copy( source );
  18976. this.v1.copy( source.v1 );
  18977. this.v2.copy( source.v2 );
  18978. return this;
  18979. }
  18980. toJSON() {
  18981. const data = super.toJSON();
  18982. data.v1 = this.v1.toArray();
  18983. data.v2 = this.v2.toArray();
  18984. return data;
  18985. }
  18986. fromJSON( json ) {
  18987. super.fromJSON( json );
  18988. this.v1.fromArray( json.v1 );
  18989. this.v2.fromArray( json.v2 );
  18990. return this;
  18991. }
  18992. }
  18993. class LineCurve3 extends Curve {
  18994. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  18995. super();
  18996. this.isLineCurve3 = true;
  18997. this.type = 'LineCurve3';
  18998. this.v1 = v1;
  18999. this.v2 = v2;
  19000. }
  19001. getPoint( t, optionalTarget = new Vector3() ) {
  19002. const point = optionalTarget;
  19003. if ( t === 1 ) {
  19004. point.copy( this.v2 );
  19005. } else {
  19006. point.copy( this.v2 ).sub( this.v1 );
  19007. point.multiplyScalar( t ).add( this.v1 );
  19008. }
  19009. return point;
  19010. }
  19011. // Line curve is linear, so we can overwrite default getPointAt
  19012. getPointAt( u, optionalTarget ) {
  19013. return this.getPoint( u, optionalTarget );
  19014. }
  19015. copy( source ) {
  19016. super.copy( source );
  19017. this.v1.copy( source.v1 );
  19018. this.v2.copy( source.v2 );
  19019. return this;
  19020. }
  19021. toJSON() {
  19022. const data = super.toJSON();
  19023. data.v1 = this.v1.toArray();
  19024. data.v2 = this.v2.toArray();
  19025. return data;
  19026. }
  19027. fromJSON( json ) {
  19028. super.fromJSON( json );
  19029. this.v1.fromArray( json.v1 );
  19030. this.v2.fromArray( json.v2 );
  19031. return this;
  19032. }
  19033. }
  19034. class QuadraticBezierCurve extends Curve {
  19035. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  19036. super();
  19037. this.isQuadraticBezierCurve = true;
  19038. this.type = 'QuadraticBezierCurve';
  19039. this.v0 = v0;
  19040. this.v1 = v1;
  19041. this.v2 = v2;
  19042. }
  19043. getPoint( t, optionalTarget = new Vector2() ) {
  19044. const point = optionalTarget;
  19045. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19046. point.set(
  19047. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19048. QuadraticBezier( t, v0.y, v1.y, v2.y )
  19049. );
  19050. return point;
  19051. }
  19052. copy( source ) {
  19053. super.copy( source );
  19054. this.v0.copy( source.v0 );
  19055. this.v1.copy( source.v1 );
  19056. this.v2.copy( source.v2 );
  19057. return this;
  19058. }
  19059. toJSON() {
  19060. const data = super.toJSON();
  19061. data.v0 = this.v0.toArray();
  19062. data.v1 = this.v1.toArray();
  19063. data.v2 = this.v2.toArray();
  19064. return data;
  19065. }
  19066. fromJSON( json ) {
  19067. super.fromJSON( json );
  19068. this.v0.fromArray( json.v0 );
  19069. this.v1.fromArray( json.v1 );
  19070. this.v2.fromArray( json.v2 );
  19071. return this;
  19072. }
  19073. }
  19074. class QuadraticBezierCurve3 extends Curve {
  19075. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  19076. super();
  19077. this.isQuadraticBezierCurve3 = true;
  19078. this.type = 'QuadraticBezierCurve3';
  19079. this.v0 = v0;
  19080. this.v1 = v1;
  19081. this.v2 = v2;
  19082. }
  19083. getPoint( t, optionalTarget = new Vector3() ) {
  19084. const point = optionalTarget;
  19085. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  19086. point.set(
  19087. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  19088. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  19089. QuadraticBezier( t, v0.z, v1.z, v2.z )
  19090. );
  19091. return point;
  19092. }
  19093. copy( source ) {
  19094. super.copy( source );
  19095. this.v0.copy( source.v0 );
  19096. this.v1.copy( source.v1 );
  19097. this.v2.copy( source.v2 );
  19098. return this;
  19099. }
  19100. toJSON() {
  19101. const data = super.toJSON();
  19102. data.v0 = this.v0.toArray();
  19103. data.v1 = this.v1.toArray();
  19104. data.v2 = this.v2.toArray();
  19105. return data;
  19106. }
  19107. fromJSON( json ) {
  19108. super.fromJSON( json );
  19109. this.v0.fromArray( json.v0 );
  19110. this.v1.fromArray( json.v1 );
  19111. this.v2.fromArray( json.v2 );
  19112. return this;
  19113. }
  19114. }
  19115. class SplineCurve extends Curve {
  19116. constructor( points = [] ) {
  19117. super();
  19118. this.isSplineCurve = true;
  19119. this.type = 'SplineCurve';
  19120. this.points = points;
  19121. }
  19122. getPoint( t, optionalTarget = new Vector2() ) {
  19123. const point = optionalTarget;
  19124. const points = this.points;
  19125. const p = ( points.length - 1 ) * t;
  19126. const intPoint = Math.floor( p );
  19127. const weight = p - intPoint;
  19128. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  19129. const p1 = points[ intPoint ];
  19130. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  19131. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  19132. point.set(
  19133. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  19134. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  19135. );
  19136. return point;
  19137. }
  19138. copy( source ) {
  19139. super.copy( source );
  19140. this.points = [];
  19141. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  19142. const point = source.points[ i ];
  19143. this.points.push( point.clone() );
  19144. }
  19145. return this;
  19146. }
  19147. toJSON() {
  19148. const data = super.toJSON();
  19149. data.points = [];
  19150. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  19151. const point = this.points[ i ];
  19152. data.points.push( point.toArray() );
  19153. }
  19154. return data;
  19155. }
  19156. fromJSON( json ) {
  19157. super.fromJSON( json );
  19158. this.points = [];
  19159. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  19160. const point = json.points[ i ];
  19161. this.points.push( new Vector2().fromArray( point ) );
  19162. }
  19163. return this;
  19164. }
  19165. }
  19166. var Curves = /*#__PURE__*/Object.freeze({
  19167. __proto__: null,
  19168. ArcCurve: ArcCurve,
  19169. CatmullRomCurve3: CatmullRomCurve3,
  19170. CubicBezierCurve: CubicBezierCurve,
  19171. CubicBezierCurve3: CubicBezierCurve3,
  19172. EllipseCurve: EllipseCurve,
  19173. LineCurve: LineCurve,
  19174. LineCurve3: LineCurve3,
  19175. QuadraticBezierCurve: QuadraticBezierCurve,
  19176. QuadraticBezierCurve3: QuadraticBezierCurve3,
  19177. SplineCurve: SplineCurve
  19178. });
  19179. /**************************************************************
  19180. * Curved Path - a curve path is simply a array of connected
  19181. * curves, but retains the api of a curve
  19182. **************************************************************/
  19183. class CurvePath extends Curve {
  19184. constructor() {
  19185. super();
  19186. this.type = 'CurvePath';
  19187. this.curves = [];
  19188. this.autoClose = false; // Automatically closes the path
  19189. }
  19190. add( curve ) {
  19191. this.curves.push( curve );
  19192. }
  19193. closePath() {
  19194. // Add a line curve if start and end of lines are not connected
  19195. const startPoint = this.curves[ 0 ].getPoint( 0 );
  19196. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  19197. if ( ! startPoint.equals( endPoint ) ) {
  19198. this.curves.push( new LineCurve( endPoint, startPoint ) );
  19199. }
  19200. }
  19201. // To get accurate point with reference to
  19202. // entire path distance at time t,
  19203. // following has to be done:
  19204. // 1. Length of each sub path have to be known
  19205. // 2. Locate and identify type of curve
  19206. // 3. Get t for the curve
  19207. // 4. Return curve.getPointAt(t')
  19208. getPoint( t, optionalTarget ) {
  19209. const d = t * this.getLength();
  19210. const curveLengths = this.getCurveLengths();
  19211. let i = 0;
  19212. // To think about boundaries points.
  19213. while ( i < curveLengths.length ) {
  19214. if ( curveLengths[ i ] >= d ) {
  19215. const diff = curveLengths[ i ] - d;
  19216. const curve = this.curves[ i ];
  19217. const segmentLength = curve.getLength();
  19218. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  19219. return curve.getPointAt( u, optionalTarget );
  19220. }
  19221. i ++;
  19222. }
  19223. return null;
  19224. // loop where sum != 0, sum > d , sum+1 <d
  19225. }
  19226. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  19227. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  19228. // getPoint() depends on getLength
  19229. getLength() {
  19230. const lens = this.getCurveLengths();
  19231. return lens[ lens.length - 1 ];
  19232. }
  19233. // cacheLengths must be recalculated.
  19234. updateArcLengths() {
  19235. this.needsUpdate = true;
  19236. this.cacheLengths = null;
  19237. this.getCurveLengths();
  19238. }
  19239. // Compute lengths and cache them
  19240. // We cannot overwrite getLengths() because UtoT mapping uses it.
  19241. getCurveLengths() {
  19242. // We use cache values if curves and cache array are same length
  19243. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  19244. return this.cacheLengths;
  19245. }
  19246. // Get length of sub-curve
  19247. // Push sums into cached array
  19248. const lengths = [];
  19249. let sums = 0;
  19250. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19251. sums += this.curves[ i ].getLength();
  19252. lengths.push( sums );
  19253. }
  19254. this.cacheLengths = lengths;
  19255. return lengths;
  19256. }
  19257. getSpacedPoints( divisions = 40 ) {
  19258. const points = [];
  19259. for ( let i = 0; i <= divisions; i ++ ) {
  19260. points.push( this.getPoint( i / divisions ) );
  19261. }
  19262. if ( this.autoClose ) {
  19263. points.push( points[ 0 ] );
  19264. }
  19265. return points;
  19266. }
  19267. getPoints( divisions = 12 ) {
  19268. const points = [];
  19269. let last;
  19270. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  19271. const curve = curves[ i ];
  19272. const resolution = curve.isEllipseCurve ? divisions * 2
  19273. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  19274. : curve.isSplineCurve ? divisions * curve.points.length
  19275. : divisions;
  19276. const pts = curve.getPoints( resolution );
  19277. for ( let j = 0; j < pts.length; j ++ ) {
  19278. const point = pts[ j ];
  19279. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  19280. points.push( point );
  19281. last = point;
  19282. }
  19283. }
  19284. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  19285. points.push( points[ 0 ] );
  19286. }
  19287. return points;
  19288. }
  19289. copy( source ) {
  19290. super.copy( source );
  19291. this.curves = [];
  19292. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  19293. const curve = source.curves[ i ];
  19294. this.curves.push( curve.clone() );
  19295. }
  19296. this.autoClose = source.autoClose;
  19297. return this;
  19298. }
  19299. toJSON() {
  19300. const data = super.toJSON();
  19301. data.autoClose = this.autoClose;
  19302. data.curves = [];
  19303. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  19304. const curve = this.curves[ i ];
  19305. data.curves.push( curve.toJSON() );
  19306. }
  19307. return data;
  19308. }
  19309. fromJSON( json ) {
  19310. super.fromJSON( json );
  19311. this.autoClose = json.autoClose;
  19312. this.curves = [];
  19313. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  19314. const curve = json.curves[ i ];
  19315. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  19316. }
  19317. return this;
  19318. }
  19319. }
  19320. class Path extends CurvePath {
  19321. constructor( points ) {
  19322. super();
  19323. this.type = 'Path';
  19324. this.currentPoint = new Vector2();
  19325. if ( points ) {
  19326. this.setFromPoints( points );
  19327. }
  19328. }
  19329. setFromPoints( points ) {
  19330. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  19331. for ( let i = 1, l = points.length; i < l; i ++ ) {
  19332. this.lineTo( points[ i ].x, points[ i ].y );
  19333. }
  19334. return this;
  19335. }
  19336. moveTo( x, y ) {
  19337. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  19338. return this;
  19339. }
  19340. lineTo( x, y ) {
  19341. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  19342. this.curves.push( curve );
  19343. this.currentPoint.set( x, y );
  19344. return this;
  19345. }
  19346. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  19347. const curve = new QuadraticBezierCurve(
  19348. this.currentPoint.clone(),
  19349. new Vector2( aCPx, aCPy ),
  19350. new Vector2( aX, aY )
  19351. );
  19352. this.curves.push( curve );
  19353. this.currentPoint.set( aX, aY );
  19354. return this;
  19355. }
  19356. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  19357. const curve = new CubicBezierCurve(
  19358. this.currentPoint.clone(),
  19359. new Vector2( aCP1x, aCP1y ),
  19360. new Vector2( aCP2x, aCP2y ),
  19361. new Vector2( aX, aY )
  19362. );
  19363. this.curves.push( curve );
  19364. this.currentPoint.set( aX, aY );
  19365. return this;
  19366. }
  19367. splineThru( pts /*Array of Vector*/ ) {
  19368. const npts = [ this.currentPoint.clone() ].concat( pts );
  19369. const curve = new SplineCurve( npts );
  19370. this.curves.push( curve );
  19371. this.currentPoint.copy( pts[ pts.length - 1 ] );
  19372. return this;
  19373. }
  19374. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19375. const x0 = this.currentPoint.x;
  19376. const y0 = this.currentPoint.y;
  19377. this.absarc( aX + x0, aY + y0, aRadius,
  19378. aStartAngle, aEndAngle, aClockwise );
  19379. return this;
  19380. }
  19381. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  19382. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  19383. return this;
  19384. }
  19385. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19386. const x0 = this.currentPoint.x;
  19387. const y0 = this.currentPoint.y;
  19388. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19389. return this;
  19390. }
  19391. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  19392. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  19393. if ( this.curves.length > 0 ) {
  19394. // if a previous curve is present, attempt to join
  19395. const firstPoint = curve.getPoint( 0 );
  19396. if ( ! firstPoint.equals( this.currentPoint ) ) {
  19397. this.lineTo( firstPoint.x, firstPoint.y );
  19398. }
  19399. }
  19400. this.curves.push( curve );
  19401. const lastPoint = curve.getPoint( 1 );
  19402. this.currentPoint.copy( lastPoint );
  19403. return this;
  19404. }
  19405. copy( source ) {
  19406. super.copy( source );
  19407. this.currentPoint.copy( source.currentPoint );
  19408. return this;
  19409. }
  19410. toJSON() {
  19411. const data = super.toJSON();
  19412. data.currentPoint = this.currentPoint.toArray();
  19413. return data;
  19414. }
  19415. fromJSON( json ) {
  19416. super.fromJSON( json );
  19417. this.currentPoint.fromArray( json.currentPoint );
  19418. return this;
  19419. }
  19420. }
  19421. class LatheGeometry extends BufferGeometry {
  19422. 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 ) {
  19423. super();
  19424. this.type = 'LatheGeometry';
  19425. this.parameters = {
  19426. points: points,
  19427. segments: segments,
  19428. phiStart: phiStart,
  19429. phiLength: phiLength
  19430. };
  19431. segments = Math.floor( segments );
  19432. // clamp phiLength so it's in range of [ 0, 2PI ]
  19433. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  19434. // buffers
  19435. const indices = [];
  19436. const vertices = [];
  19437. const uvs = [];
  19438. const initNormals = [];
  19439. const normals = [];
  19440. // helper variables
  19441. const inverseSegments = 1.0 / segments;
  19442. const vertex = new Vector3();
  19443. const uv = new Vector2();
  19444. const normal = new Vector3();
  19445. const curNormal = new Vector3();
  19446. const prevNormal = new Vector3();
  19447. let dx = 0;
  19448. let dy = 0;
  19449. // pre-compute normals for initial "meridian"
  19450. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  19451. switch ( j ) {
  19452. case 0: // special handling for 1st vertex on path
  19453. dx = points[ j + 1 ].x - points[ j ].x;
  19454. dy = points[ j + 1 ].y - points[ j ].y;
  19455. normal.x = dy * 1.0;
  19456. normal.y = - dx;
  19457. normal.z = dy * 0.0;
  19458. prevNormal.copy( normal );
  19459. normal.normalize();
  19460. initNormals.push( normal.x, normal.y, normal.z );
  19461. break;
  19462. case ( points.length - 1 ): // special handling for last Vertex on path
  19463. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  19464. break;
  19465. default: // default handling for all vertices in between
  19466. dx = points[ j + 1 ].x - points[ j ].x;
  19467. dy = points[ j + 1 ].y - points[ j ].y;
  19468. normal.x = dy * 1.0;
  19469. normal.y = - dx;
  19470. normal.z = dy * 0.0;
  19471. curNormal.copy( normal );
  19472. normal.x += prevNormal.x;
  19473. normal.y += prevNormal.y;
  19474. normal.z += prevNormal.z;
  19475. normal.normalize();
  19476. initNormals.push( normal.x, normal.y, normal.z );
  19477. prevNormal.copy( curNormal );
  19478. }
  19479. }
  19480. // generate vertices, uvs and normals
  19481. for ( let i = 0; i <= segments; i ++ ) {
  19482. const phi = phiStart + i * inverseSegments * phiLength;
  19483. const sin = Math.sin( phi );
  19484. const cos = Math.cos( phi );
  19485. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  19486. // vertex
  19487. vertex.x = points[ j ].x * sin;
  19488. vertex.y = points[ j ].y;
  19489. vertex.z = points[ j ].x * cos;
  19490. vertices.push( vertex.x, vertex.y, vertex.z );
  19491. // uv
  19492. uv.x = i / segments;
  19493. uv.y = j / ( points.length - 1 );
  19494. uvs.push( uv.x, uv.y );
  19495. // normal
  19496. const x = initNormals[ 3 * j + 0 ] * sin;
  19497. const y = initNormals[ 3 * j + 1 ];
  19498. const z = initNormals[ 3 * j + 0 ] * cos;
  19499. normals.push( x, y, z );
  19500. }
  19501. }
  19502. // indices
  19503. for ( let i = 0; i < segments; i ++ ) {
  19504. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  19505. const base = j + i * points.length;
  19506. const a = base;
  19507. const b = base + points.length;
  19508. const c = base + points.length + 1;
  19509. const d = base + 1;
  19510. // faces
  19511. indices.push( a, b, d );
  19512. indices.push( c, d, b );
  19513. }
  19514. }
  19515. // build geometry
  19516. this.setIndex( indices );
  19517. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19518. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19519. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19520. }
  19521. static fromJSON( data ) {
  19522. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  19523. }
  19524. }
  19525. class CapsuleGeometry extends LatheGeometry {
  19526. constructor( radius = 1, length = 1, capSegments = 4, radialSegments = 8 ) {
  19527. const path = new Path();
  19528. path.absarc( 0, - length / 2, radius, Math.PI * 1.5, 0 );
  19529. path.absarc( 0, length / 2, radius, 0, Math.PI * 0.5 );
  19530. super( path.getPoints( capSegments ), radialSegments );
  19531. this.type = 'CapsuleGeometry';
  19532. this.parameters = {
  19533. radius: radius,
  19534. height: length,
  19535. capSegments: capSegments,
  19536. radialSegments: radialSegments,
  19537. };
  19538. }
  19539. static fromJSON( data ) {
  19540. return new CapsuleGeometry( data.radius, data.length, data.capSegments, data.radialSegments );
  19541. }
  19542. }
  19543. class CircleGeometry extends BufferGeometry {
  19544. constructor( radius = 1, segments = 8, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19545. super();
  19546. this.type = 'CircleGeometry';
  19547. this.parameters = {
  19548. radius: radius,
  19549. segments: segments,
  19550. thetaStart: thetaStart,
  19551. thetaLength: thetaLength
  19552. };
  19553. segments = Math.max( 3, segments );
  19554. // buffers
  19555. const indices = [];
  19556. const vertices = [];
  19557. const normals = [];
  19558. const uvs = [];
  19559. // helper variables
  19560. const vertex = new Vector3();
  19561. const uv = new Vector2();
  19562. // center point
  19563. vertices.push( 0, 0, 0 );
  19564. normals.push( 0, 0, 1 );
  19565. uvs.push( 0.5, 0.5 );
  19566. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  19567. const segment = thetaStart + s / segments * thetaLength;
  19568. // vertex
  19569. vertex.x = radius * Math.cos( segment );
  19570. vertex.y = radius * Math.sin( segment );
  19571. vertices.push( vertex.x, vertex.y, vertex.z );
  19572. // normal
  19573. normals.push( 0, 0, 1 );
  19574. // uvs
  19575. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  19576. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  19577. uvs.push( uv.x, uv.y );
  19578. }
  19579. // indices
  19580. for ( let i = 1; i <= segments; i ++ ) {
  19581. indices.push( i, i + 1, 0 );
  19582. }
  19583. // build geometry
  19584. this.setIndex( indices );
  19585. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19586. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19587. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19588. }
  19589. static fromJSON( data ) {
  19590. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  19591. }
  19592. }
  19593. class CylinderGeometry extends BufferGeometry {
  19594. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19595. super();
  19596. this.type = 'CylinderGeometry';
  19597. this.parameters = {
  19598. radiusTop: radiusTop,
  19599. radiusBottom: radiusBottom,
  19600. height: height,
  19601. radialSegments: radialSegments,
  19602. heightSegments: heightSegments,
  19603. openEnded: openEnded,
  19604. thetaStart: thetaStart,
  19605. thetaLength: thetaLength
  19606. };
  19607. const scope = this;
  19608. radialSegments = Math.floor( radialSegments );
  19609. heightSegments = Math.floor( heightSegments );
  19610. // buffers
  19611. const indices = [];
  19612. const vertices = [];
  19613. const normals = [];
  19614. const uvs = [];
  19615. // helper variables
  19616. let index = 0;
  19617. const indexArray = [];
  19618. const halfHeight = height / 2;
  19619. let groupStart = 0;
  19620. // generate geometry
  19621. generateTorso();
  19622. if ( openEnded === false ) {
  19623. if ( radiusTop > 0 ) generateCap( true );
  19624. if ( radiusBottom > 0 ) generateCap( false );
  19625. }
  19626. // build geometry
  19627. this.setIndex( indices );
  19628. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19629. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19630. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19631. function generateTorso() {
  19632. const normal = new Vector3();
  19633. const vertex = new Vector3();
  19634. let groupCount = 0;
  19635. // this will be used to calculate the normal
  19636. const slope = ( radiusBottom - radiusTop ) / height;
  19637. // generate vertices, normals and uvs
  19638. for ( let y = 0; y <= heightSegments; y ++ ) {
  19639. const indexRow = [];
  19640. const v = y / heightSegments;
  19641. // calculate the radius of the current row
  19642. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  19643. for ( let x = 0; x <= radialSegments; x ++ ) {
  19644. const u = x / radialSegments;
  19645. const theta = u * thetaLength + thetaStart;
  19646. const sinTheta = Math.sin( theta );
  19647. const cosTheta = Math.cos( theta );
  19648. // vertex
  19649. vertex.x = radius * sinTheta;
  19650. vertex.y = - v * height + halfHeight;
  19651. vertex.z = radius * cosTheta;
  19652. vertices.push( vertex.x, vertex.y, vertex.z );
  19653. // normal
  19654. normal.set( sinTheta, slope, cosTheta ).normalize();
  19655. normals.push( normal.x, normal.y, normal.z );
  19656. // uv
  19657. uvs.push( u, 1 - v );
  19658. // save index of vertex in respective row
  19659. indexRow.push( index ++ );
  19660. }
  19661. // now save vertices of the row in our index array
  19662. indexArray.push( indexRow );
  19663. }
  19664. // generate indices
  19665. for ( let x = 0; x < radialSegments; x ++ ) {
  19666. for ( let y = 0; y < heightSegments; y ++ ) {
  19667. // we use the index array to access the correct indices
  19668. const a = indexArray[ y ][ x ];
  19669. const b = indexArray[ y + 1 ][ x ];
  19670. const c = indexArray[ y + 1 ][ x + 1 ];
  19671. const d = indexArray[ y ][ x + 1 ];
  19672. // faces
  19673. indices.push( a, b, d );
  19674. indices.push( b, c, d );
  19675. // update group counter
  19676. groupCount += 6;
  19677. }
  19678. }
  19679. // add a group to the geometry. this will ensure multi material support
  19680. scope.addGroup( groupStart, groupCount, 0 );
  19681. // calculate new start value for groups
  19682. groupStart += groupCount;
  19683. }
  19684. function generateCap( top ) {
  19685. // save the index of the first center vertex
  19686. const centerIndexStart = index;
  19687. const uv = new Vector2();
  19688. const vertex = new Vector3();
  19689. let groupCount = 0;
  19690. const radius = ( top === true ) ? radiusTop : radiusBottom;
  19691. const sign = ( top === true ) ? 1 : - 1;
  19692. // first we generate the center vertex data of the cap.
  19693. // because the geometry needs one set of uvs per face,
  19694. // we must generate a center vertex per face/segment
  19695. for ( let x = 1; x <= radialSegments; x ++ ) {
  19696. // vertex
  19697. vertices.push( 0, halfHeight * sign, 0 );
  19698. // normal
  19699. normals.push( 0, sign, 0 );
  19700. // uv
  19701. uvs.push( 0.5, 0.5 );
  19702. // increase index
  19703. index ++;
  19704. }
  19705. // save the index of the last center vertex
  19706. const centerIndexEnd = index;
  19707. // now we generate the surrounding vertices, normals and uvs
  19708. for ( let x = 0; x <= radialSegments; x ++ ) {
  19709. const u = x / radialSegments;
  19710. const theta = u * thetaLength + thetaStart;
  19711. const cosTheta = Math.cos( theta );
  19712. const sinTheta = Math.sin( theta );
  19713. // vertex
  19714. vertex.x = radius * sinTheta;
  19715. vertex.y = halfHeight * sign;
  19716. vertex.z = radius * cosTheta;
  19717. vertices.push( vertex.x, vertex.y, vertex.z );
  19718. // normal
  19719. normals.push( 0, sign, 0 );
  19720. // uv
  19721. uv.x = ( cosTheta * 0.5 ) + 0.5;
  19722. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  19723. uvs.push( uv.x, uv.y );
  19724. // increase index
  19725. index ++;
  19726. }
  19727. // generate indices
  19728. for ( let x = 0; x < radialSegments; x ++ ) {
  19729. const c = centerIndexStart + x;
  19730. const i = centerIndexEnd + x;
  19731. if ( top === true ) {
  19732. // face top
  19733. indices.push( i, i + 1, c );
  19734. } else {
  19735. // face bottom
  19736. indices.push( i + 1, i, c );
  19737. }
  19738. groupCount += 3;
  19739. }
  19740. // add a group to the geometry. this will ensure multi material support
  19741. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  19742. // calculate new start value for groups
  19743. groupStart += groupCount;
  19744. }
  19745. }
  19746. static fromJSON( data ) {
  19747. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  19748. }
  19749. }
  19750. class ConeGeometry extends CylinderGeometry {
  19751. constructor( radius = 1, height = 1, radialSegments = 8, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  19752. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  19753. this.type = 'ConeGeometry';
  19754. this.parameters = {
  19755. radius: radius,
  19756. height: height,
  19757. radialSegments: radialSegments,
  19758. heightSegments: heightSegments,
  19759. openEnded: openEnded,
  19760. thetaStart: thetaStart,
  19761. thetaLength: thetaLength
  19762. };
  19763. }
  19764. static fromJSON( data ) {
  19765. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  19766. }
  19767. }
  19768. class PolyhedronGeometry extends BufferGeometry {
  19769. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  19770. super();
  19771. this.type = 'PolyhedronGeometry';
  19772. this.parameters = {
  19773. vertices: vertices,
  19774. indices: indices,
  19775. radius: radius,
  19776. detail: detail
  19777. };
  19778. // default buffer data
  19779. const vertexBuffer = [];
  19780. const uvBuffer = [];
  19781. // the subdivision creates the vertex buffer data
  19782. subdivide( detail );
  19783. // all vertices should lie on a conceptual sphere with a given radius
  19784. applyRadius( radius );
  19785. // finally, create the uv data
  19786. generateUVs();
  19787. // build non-indexed geometry
  19788. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  19789. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  19790. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  19791. if ( detail === 0 ) {
  19792. this.computeVertexNormals(); // flat normals
  19793. } else {
  19794. this.normalizeNormals(); // smooth normals
  19795. }
  19796. // helper functions
  19797. function subdivide( detail ) {
  19798. const a = new Vector3();
  19799. const b = new Vector3();
  19800. const c = new Vector3();
  19801. // iterate over all faces and apply a subdivison with the given detail value
  19802. for ( let i = 0; i < indices.length; i += 3 ) {
  19803. // get the vertices of the face
  19804. getVertexByIndex( indices[ i + 0 ], a );
  19805. getVertexByIndex( indices[ i + 1 ], b );
  19806. getVertexByIndex( indices[ i + 2 ], c );
  19807. // perform subdivision
  19808. subdivideFace( a, b, c, detail );
  19809. }
  19810. }
  19811. function subdivideFace( a, b, c, detail ) {
  19812. const cols = detail + 1;
  19813. // we use this multidimensional array as a data structure for creating the subdivision
  19814. const v = [];
  19815. // construct all of the vertices for this subdivision
  19816. for ( let i = 0; i <= cols; i ++ ) {
  19817. v[ i ] = [];
  19818. const aj = a.clone().lerp( c, i / cols );
  19819. const bj = b.clone().lerp( c, i / cols );
  19820. const rows = cols - i;
  19821. for ( let j = 0; j <= rows; j ++ ) {
  19822. if ( j === 0 && i === cols ) {
  19823. v[ i ][ j ] = aj;
  19824. } else {
  19825. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  19826. }
  19827. }
  19828. }
  19829. // construct all of the faces
  19830. for ( let i = 0; i < cols; i ++ ) {
  19831. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  19832. const k = Math.floor( j / 2 );
  19833. if ( j % 2 === 0 ) {
  19834. pushVertex( v[ i ][ k + 1 ] );
  19835. pushVertex( v[ i + 1 ][ k ] );
  19836. pushVertex( v[ i ][ k ] );
  19837. } else {
  19838. pushVertex( v[ i ][ k + 1 ] );
  19839. pushVertex( v[ i + 1 ][ k + 1 ] );
  19840. pushVertex( v[ i + 1 ][ k ] );
  19841. }
  19842. }
  19843. }
  19844. }
  19845. function applyRadius( radius ) {
  19846. const vertex = new Vector3();
  19847. // iterate over the entire buffer and apply the radius to each vertex
  19848. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  19849. vertex.x = vertexBuffer[ i + 0 ];
  19850. vertex.y = vertexBuffer[ i + 1 ];
  19851. vertex.z = vertexBuffer[ i + 2 ];
  19852. vertex.normalize().multiplyScalar( radius );
  19853. vertexBuffer[ i + 0 ] = vertex.x;
  19854. vertexBuffer[ i + 1 ] = vertex.y;
  19855. vertexBuffer[ i + 2 ] = vertex.z;
  19856. }
  19857. }
  19858. function generateUVs() {
  19859. const vertex = new Vector3();
  19860. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  19861. vertex.x = vertexBuffer[ i + 0 ];
  19862. vertex.y = vertexBuffer[ i + 1 ];
  19863. vertex.z = vertexBuffer[ i + 2 ];
  19864. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  19865. const v = inclination( vertex ) / Math.PI + 0.5;
  19866. uvBuffer.push( u, 1 - v );
  19867. }
  19868. correctUVs();
  19869. correctSeam();
  19870. }
  19871. function correctSeam() {
  19872. // handle case when face straddles the seam, see #3269
  19873. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  19874. // uv data of a single face
  19875. const x0 = uvBuffer[ i + 0 ];
  19876. const x1 = uvBuffer[ i + 2 ];
  19877. const x2 = uvBuffer[ i + 4 ];
  19878. const max = Math.max( x0, x1, x2 );
  19879. const min = Math.min( x0, x1, x2 );
  19880. // 0.9 is somewhat arbitrary
  19881. if ( max > 0.9 && min < 0.1 ) {
  19882. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  19883. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  19884. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  19885. }
  19886. }
  19887. }
  19888. function pushVertex( vertex ) {
  19889. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  19890. }
  19891. function getVertexByIndex( index, vertex ) {
  19892. const stride = index * 3;
  19893. vertex.x = vertices[ stride + 0 ];
  19894. vertex.y = vertices[ stride + 1 ];
  19895. vertex.z = vertices[ stride + 2 ];
  19896. }
  19897. function correctUVs() {
  19898. const a = new Vector3();
  19899. const b = new Vector3();
  19900. const c = new Vector3();
  19901. const centroid = new Vector3();
  19902. const uvA = new Vector2();
  19903. const uvB = new Vector2();
  19904. const uvC = new Vector2();
  19905. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  19906. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  19907. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  19908. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  19909. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  19910. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  19911. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  19912. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  19913. const azi = azimuth( centroid );
  19914. correctUV( uvA, j + 0, a, azi );
  19915. correctUV( uvB, j + 2, b, azi );
  19916. correctUV( uvC, j + 4, c, azi );
  19917. }
  19918. }
  19919. function correctUV( uv, stride, vector, azimuth ) {
  19920. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  19921. uvBuffer[ stride ] = uv.x - 1;
  19922. }
  19923. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  19924. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  19925. }
  19926. }
  19927. // Angle around the Y axis, counter-clockwise when looking from above.
  19928. function azimuth( vector ) {
  19929. return Math.atan2( vector.z, - vector.x );
  19930. }
  19931. // Angle above the XZ plane.
  19932. function inclination( vector ) {
  19933. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19934. }
  19935. }
  19936. static fromJSON( data ) {
  19937. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  19938. }
  19939. }
  19940. class DodecahedronGeometry extends PolyhedronGeometry {
  19941. constructor( radius = 1, detail = 0 ) {
  19942. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19943. const r = 1 / t;
  19944. const vertices = [
  19945. // (±1, ±1, ±1)
  19946. - 1, - 1, - 1, - 1, - 1, 1,
  19947. - 1, 1, - 1, - 1, 1, 1,
  19948. 1, - 1, - 1, 1, - 1, 1,
  19949. 1, 1, - 1, 1, 1, 1,
  19950. // (0, ±1/φ, ±φ)
  19951. 0, - r, - t, 0, - r, t,
  19952. 0, r, - t, 0, r, t,
  19953. // (±1/φ, ±φ, 0)
  19954. - r, - t, 0, - r, t, 0,
  19955. r, - t, 0, r, t, 0,
  19956. // (±φ, 0, ±1/φ)
  19957. - t, 0, - r, t, 0, - r,
  19958. - t, 0, r, t, 0, r
  19959. ];
  19960. const indices = [
  19961. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  19962. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  19963. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  19964. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  19965. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  19966. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  19967. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  19968. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  19969. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  19970. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  19971. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  19972. 1, 12, 14, 1, 14, 5, 1, 5, 9
  19973. ];
  19974. super( vertices, indices, radius, detail );
  19975. this.type = 'DodecahedronGeometry';
  19976. this.parameters = {
  19977. radius: radius,
  19978. detail: detail
  19979. };
  19980. }
  19981. static fromJSON( data ) {
  19982. return new DodecahedronGeometry( data.radius, data.detail );
  19983. }
  19984. }
  19985. const _v0 = /*@__PURE__*/ new Vector3();
  19986. const _v1$1 = /*@__PURE__*/ new Vector3();
  19987. const _normal = /*@__PURE__*/ new Vector3();
  19988. const _triangle = /*@__PURE__*/ new Triangle();
  19989. class EdgesGeometry extends BufferGeometry {
  19990. constructor( geometry = null, thresholdAngle = 1 ) {
  19991. super();
  19992. this.type = 'EdgesGeometry';
  19993. this.parameters = {
  19994. geometry: geometry,
  19995. thresholdAngle: thresholdAngle
  19996. };
  19997. if ( geometry !== null ) {
  19998. const precisionPoints = 4;
  19999. const precision = Math.pow( 10, precisionPoints );
  20000. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  20001. const indexAttr = geometry.getIndex();
  20002. const positionAttr = geometry.getAttribute( 'position' );
  20003. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  20004. const indexArr = [ 0, 0, 0 ];
  20005. const vertKeys = [ 'a', 'b', 'c' ];
  20006. const hashes = new Array( 3 );
  20007. const edgeData = {};
  20008. const vertices = [];
  20009. for ( let i = 0; i < indexCount; i += 3 ) {
  20010. if ( indexAttr ) {
  20011. indexArr[ 0 ] = indexAttr.getX( i );
  20012. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  20013. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  20014. } else {
  20015. indexArr[ 0 ] = i;
  20016. indexArr[ 1 ] = i + 1;
  20017. indexArr[ 2 ] = i + 2;
  20018. }
  20019. const { a, b, c } = _triangle;
  20020. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  20021. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  20022. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  20023. _triangle.getNormal( _normal );
  20024. // create hashes for the edge from the vertices
  20025. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  20026. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  20027. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  20028. // skip degenerate triangles
  20029. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  20030. continue;
  20031. }
  20032. // iterate over every edge
  20033. for ( let j = 0; j < 3; j ++ ) {
  20034. // get the first and next vertex making up the edge
  20035. const jNext = ( j + 1 ) % 3;
  20036. const vecHash0 = hashes[ j ];
  20037. const vecHash1 = hashes[ jNext ];
  20038. const v0 = _triangle[ vertKeys[ j ] ];
  20039. const v1 = _triangle[ vertKeys[ jNext ] ];
  20040. const hash = `${ vecHash0 }_${ vecHash1 }`;
  20041. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  20042. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  20043. // if we found a sibling edge add it into the vertex array if
  20044. // it meets the angle threshold and delete the edge from the map.
  20045. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  20046. vertices.push( v0.x, v0.y, v0.z );
  20047. vertices.push( v1.x, v1.y, v1.z );
  20048. }
  20049. edgeData[ reverseHash ] = null;
  20050. } else if ( ! ( hash in edgeData ) ) {
  20051. // if we've already got an edge here then skip adding a new one
  20052. edgeData[ hash ] = {
  20053. index0: indexArr[ j ],
  20054. index1: indexArr[ jNext ],
  20055. normal: _normal.clone(),
  20056. };
  20057. }
  20058. }
  20059. }
  20060. // iterate over all remaining, unmatched edges and add them to the vertex array
  20061. for ( const key in edgeData ) {
  20062. if ( edgeData[ key ] ) {
  20063. const { index0, index1 } = edgeData[ key ];
  20064. _v0.fromBufferAttribute( positionAttr, index0 );
  20065. _v1$1.fromBufferAttribute( positionAttr, index1 );
  20066. vertices.push( _v0.x, _v0.y, _v0.z );
  20067. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  20068. }
  20069. }
  20070. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20071. }
  20072. }
  20073. }
  20074. class Shape extends Path {
  20075. constructor( points ) {
  20076. super( points );
  20077. this.uuid = generateUUID();
  20078. this.type = 'Shape';
  20079. this.holes = [];
  20080. }
  20081. getPointsHoles( divisions ) {
  20082. const holesPts = [];
  20083. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20084. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  20085. }
  20086. return holesPts;
  20087. }
  20088. // get points of shape and holes (keypoints based on segments parameter)
  20089. extractPoints( divisions ) {
  20090. return {
  20091. shape: this.getPoints( divisions ),
  20092. holes: this.getPointsHoles( divisions )
  20093. };
  20094. }
  20095. copy( source ) {
  20096. super.copy( source );
  20097. this.holes = [];
  20098. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  20099. const hole = source.holes[ i ];
  20100. this.holes.push( hole.clone() );
  20101. }
  20102. return this;
  20103. }
  20104. toJSON() {
  20105. const data = super.toJSON();
  20106. data.uuid = this.uuid;
  20107. data.holes = [];
  20108. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  20109. const hole = this.holes[ i ];
  20110. data.holes.push( hole.toJSON() );
  20111. }
  20112. return data;
  20113. }
  20114. fromJSON( json ) {
  20115. super.fromJSON( json );
  20116. this.uuid = json.uuid;
  20117. this.holes = [];
  20118. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  20119. const hole = json.holes[ i ];
  20120. this.holes.push( new Path().fromJSON( hole ) );
  20121. }
  20122. return this;
  20123. }
  20124. }
  20125. /**
  20126. * Port from https://github.com/mapbox/earcut (v2.2.2)
  20127. */
  20128. const Earcut = {
  20129. triangulate: function ( data, holeIndices, dim = 2 ) {
  20130. const hasHoles = holeIndices && holeIndices.length;
  20131. const outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length;
  20132. let outerNode = linkedList( data, 0, outerLen, dim, true );
  20133. const triangles = [];
  20134. if ( ! outerNode || outerNode.next === outerNode.prev ) return triangles;
  20135. let minX, minY, maxX, maxY, x, y, invSize;
  20136. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  20137. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  20138. if ( data.length > 80 * dim ) {
  20139. minX = maxX = data[ 0 ];
  20140. minY = maxY = data[ 1 ];
  20141. for ( let i = dim; i < outerLen; i += dim ) {
  20142. x = data[ i ];
  20143. y = data[ i + 1 ];
  20144. if ( x < minX ) minX = x;
  20145. if ( y < minY ) minY = y;
  20146. if ( x > maxX ) maxX = x;
  20147. if ( y > maxY ) maxY = y;
  20148. }
  20149. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  20150. invSize = Math.max( maxX - minX, maxY - minY );
  20151. invSize = invSize !== 0 ? 1 / invSize : 0;
  20152. }
  20153. earcutLinked( outerNode, triangles, dim, minX, minY, invSize );
  20154. return triangles;
  20155. }
  20156. };
  20157. // create a circular doubly linked list from polygon points in the specified winding order
  20158. function linkedList( data, start, end, dim, clockwise ) {
  20159. let i, last;
  20160. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  20161. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20162. } else {
  20163. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20164. }
  20165. if ( last && equals( last, last.next ) ) {
  20166. removeNode( last );
  20167. last = last.next;
  20168. }
  20169. return last;
  20170. }
  20171. // eliminate colinear or duplicate points
  20172. function filterPoints( start, end ) {
  20173. if ( ! start ) return start;
  20174. if ( ! end ) end = start;
  20175. let p = start,
  20176. again;
  20177. do {
  20178. again = false;
  20179. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  20180. removeNode( p );
  20181. p = end = p.prev;
  20182. if ( p === p.next ) break;
  20183. again = true;
  20184. } else {
  20185. p = p.next;
  20186. }
  20187. } while ( again || p !== end );
  20188. return end;
  20189. }
  20190. // main ear slicing loop which triangulates a polygon (given as a linked list)
  20191. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  20192. if ( ! ear ) return;
  20193. // interlink polygon nodes in z-order
  20194. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  20195. let stop = ear,
  20196. prev, next;
  20197. // iterate through ears, slicing them one by one
  20198. while ( ear.prev !== ear.next ) {
  20199. prev = ear.prev;
  20200. next = ear.next;
  20201. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  20202. // cut off the triangle
  20203. triangles.push( prev.i / dim );
  20204. triangles.push( ear.i / dim );
  20205. triangles.push( next.i / dim );
  20206. removeNode( ear );
  20207. // skipping the next vertex leads to less sliver triangles
  20208. ear = next.next;
  20209. stop = next.next;
  20210. continue;
  20211. }
  20212. ear = next;
  20213. // if we looped through the whole remaining polygon and can't find any more ears
  20214. if ( ear === stop ) {
  20215. // try filtering points and slicing again
  20216. if ( ! pass ) {
  20217. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  20218. // if this didn't work, try curing all small self-intersections locally
  20219. } else if ( pass === 1 ) {
  20220. ear = cureLocalIntersections( filterPoints( ear ), triangles, dim );
  20221. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  20222. // as a last resort, try splitting the remaining polygon into two
  20223. } else if ( pass === 2 ) {
  20224. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  20225. }
  20226. break;
  20227. }
  20228. }
  20229. }
  20230. // check whether a polygon node forms a valid ear with adjacent nodes
  20231. function isEar( ear ) {
  20232. const a = ear.prev,
  20233. b = ear,
  20234. c = ear.next;
  20235. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20236. // now make sure we don't have other points inside the potential ear
  20237. let p = ear.next.next;
  20238. while ( p !== ear.prev ) {
  20239. if ( pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  20240. area( p.prev, p, p.next ) >= 0 ) return false;
  20241. p = p.next;
  20242. }
  20243. return true;
  20244. }
  20245. function isEarHashed( ear, minX, minY, invSize ) {
  20246. const a = ear.prev,
  20247. b = ear,
  20248. c = ear.next;
  20249. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20250. // triangle bbox; min & max are calculated like this for speed
  20251. const minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
  20252. minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
  20253. maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
  20254. maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );
  20255. // z-order range for the current triangle bbox;
  20256. const minZ = zOrder( minTX, minTY, minX, minY, invSize ),
  20257. maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );
  20258. let p = ear.prevZ,
  20259. n = ear.nextZ;
  20260. // look for points inside the triangle in both directions
  20261. while ( p && p.z >= minZ && n && n.z <= maxZ ) {
  20262. if ( p !== ear.prev && p !== ear.next &&
  20263. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  20264. area( p.prev, p, p.next ) >= 0 ) return false;
  20265. p = p.prevZ;
  20266. if ( n !== ear.prev && n !== ear.next &&
  20267. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  20268. area( n.prev, n, n.next ) >= 0 ) return false;
  20269. n = n.nextZ;
  20270. }
  20271. // look for remaining points in decreasing z-order
  20272. while ( p && p.z >= minZ ) {
  20273. if ( p !== ear.prev && p !== ear.next &&
  20274. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  20275. area( p.prev, p, p.next ) >= 0 ) return false;
  20276. p = p.prevZ;
  20277. }
  20278. // look for remaining points in increasing z-order
  20279. while ( n && n.z <= maxZ ) {
  20280. if ( n !== ear.prev && n !== ear.next &&
  20281. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y ) &&
  20282. area( n.prev, n, n.next ) >= 0 ) return false;
  20283. n = n.nextZ;
  20284. }
  20285. return true;
  20286. }
  20287. // go through all polygon nodes and cure small local self-intersections
  20288. function cureLocalIntersections( start, triangles, dim ) {
  20289. let p = start;
  20290. do {
  20291. const a = p.prev,
  20292. b = p.next.next;
  20293. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  20294. triangles.push( a.i / dim );
  20295. triangles.push( p.i / dim );
  20296. triangles.push( b.i / dim );
  20297. // remove two nodes involved
  20298. removeNode( p );
  20299. removeNode( p.next );
  20300. p = start = b;
  20301. }
  20302. p = p.next;
  20303. } while ( p !== start );
  20304. return filterPoints( p );
  20305. }
  20306. // try splitting polygon into two and triangulate them independently
  20307. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  20308. // look for a valid diagonal that divides the polygon into two
  20309. let a = start;
  20310. do {
  20311. let b = a.next.next;
  20312. while ( b !== a.prev ) {
  20313. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  20314. // split the polygon in two by the diagonal
  20315. let c = splitPolygon( a, b );
  20316. // filter colinear points around the cuts
  20317. a = filterPoints( a, a.next );
  20318. c = filterPoints( c, c.next );
  20319. // run earcut on each half
  20320. earcutLinked( a, triangles, dim, minX, minY, invSize );
  20321. earcutLinked( c, triangles, dim, minX, minY, invSize );
  20322. return;
  20323. }
  20324. b = b.next;
  20325. }
  20326. a = a.next;
  20327. } while ( a !== start );
  20328. }
  20329. // link every hole into the outer loop, producing a single-ring polygon without holes
  20330. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  20331. const queue = [];
  20332. let i, len, start, end, list;
  20333. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  20334. start = holeIndices[ i ] * dim;
  20335. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  20336. list = linkedList( data, start, end, dim, false );
  20337. if ( list === list.next ) list.steiner = true;
  20338. queue.push( getLeftmost( list ) );
  20339. }
  20340. queue.sort( compareX );
  20341. // process holes from left to right
  20342. for ( i = 0; i < queue.length; i ++ ) {
  20343. eliminateHole( queue[ i ], outerNode );
  20344. outerNode = filterPoints( outerNode, outerNode.next );
  20345. }
  20346. return outerNode;
  20347. }
  20348. function compareX( a, b ) {
  20349. return a.x - b.x;
  20350. }
  20351. // find a bridge between vertices that connects hole with an outer ring and link it
  20352. function eliminateHole( hole, outerNode ) {
  20353. outerNode = findHoleBridge( hole, outerNode );
  20354. if ( outerNode ) {
  20355. const b = splitPolygon( outerNode, hole );
  20356. // filter collinear points around the cuts
  20357. filterPoints( outerNode, outerNode.next );
  20358. filterPoints( b, b.next );
  20359. }
  20360. }
  20361. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  20362. function findHoleBridge( hole, outerNode ) {
  20363. let p = outerNode;
  20364. const hx = hole.x;
  20365. const hy = hole.y;
  20366. let qx = - Infinity, m;
  20367. // find a segment intersected by a ray from the hole's leftmost point to the left;
  20368. // segment's endpoint with lesser x will be potential connection point
  20369. do {
  20370. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  20371. const x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  20372. if ( x <= hx && x > qx ) {
  20373. qx = x;
  20374. if ( x === hx ) {
  20375. if ( hy === p.y ) return p;
  20376. if ( hy === p.next.y ) return p.next;
  20377. }
  20378. m = p.x < p.next.x ? p : p.next;
  20379. }
  20380. }
  20381. p = p.next;
  20382. } while ( p !== outerNode );
  20383. if ( ! m ) return null;
  20384. if ( hx === qx ) return m; // hole touches outer segment; pick leftmost endpoint
  20385. // look for points inside the triangle of hole point, segment intersection and endpoint;
  20386. // if there are no points found, we have a valid connection;
  20387. // otherwise choose the point of the minimum angle with the ray as connection point
  20388. const stop = m,
  20389. mx = m.x,
  20390. my = m.y;
  20391. let tanMin = Infinity, tan;
  20392. p = m;
  20393. do {
  20394. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  20395. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  20396. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  20397. if ( locallyInside( p, hole ) && ( tan < tanMin || ( tan === tanMin && ( p.x > m.x || ( p.x === m.x && sectorContainsSector( m, p ) ) ) ) ) ) {
  20398. m = p;
  20399. tanMin = tan;
  20400. }
  20401. }
  20402. p = p.next;
  20403. } while ( p !== stop );
  20404. return m;
  20405. }
  20406. // whether sector in vertex m contains sector in vertex p in the same coordinates
  20407. function sectorContainsSector( m, p ) {
  20408. return area( m.prev, m, p.prev ) < 0 && area( p.next, m, m.next ) < 0;
  20409. }
  20410. // interlink polygon nodes in z-order
  20411. function indexCurve( start, minX, minY, invSize ) {
  20412. let p = start;
  20413. do {
  20414. if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  20415. p.prevZ = p.prev;
  20416. p.nextZ = p.next;
  20417. p = p.next;
  20418. } while ( p !== start );
  20419. p.prevZ.nextZ = null;
  20420. p.prevZ = null;
  20421. sortLinked( p );
  20422. }
  20423. // Simon Tatham's linked list merge sort algorithm
  20424. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  20425. function sortLinked( list ) {
  20426. let i, p, q, e, tail, numMerges, pSize, qSize,
  20427. inSize = 1;
  20428. do {
  20429. p = list;
  20430. list = null;
  20431. tail = null;
  20432. numMerges = 0;
  20433. while ( p ) {
  20434. numMerges ++;
  20435. q = p;
  20436. pSize = 0;
  20437. for ( i = 0; i < inSize; i ++ ) {
  20438. pSize ++;
  20439. q = q.nextZ;
  20440. if ( ! q ) break;
  20441. }
  20442. qSize = inSize;
  20443. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  20444. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  20445. e = p;
  20446. p = p.nextZ;
  20447. pSize --;
  20448. } else {
  20449. e = q;
  20450. q = q.nextZ;
  20451. qSize --;
  20452. }
  20453. if ( tail ) tail.nextZ = e;
  20454. else list = e;
  20455. e.prevZ = tail;
  20456. tail = e;
  20457. }
  20458. p = q;
  20459. }
  20460. tail.nextZ = null;
  20461. inSize *= 2;
  20462. } while ( numMerges > 1 );
  20463. return list;
  20464. }
  20465. // z-order of a point given coords and inverse of the longer side of data bbox
  20466. function zOrder( x, y, minX, minY, invSize ) {
  20467. // coords are transformed into non-negative 15-bit integer range
  20468. x = 32767 * ( x - minX ) * invSize;
  20469. y = 32767 * ( y - minY ) * invSize;
  20470. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  20471. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  20472. x = ( x | ( x << 2 ) ) & 0x33333333;
  20473. x = ( x | ( x << 1 ) ) & 0x55555555;
  20474. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  20475. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  20476. y = ( y | ( y << 2 ) ) & 0x33333333;
  20477. y = ( y | ( y << 1 ) ) & 0x55555555;
  20478. return x | ( y << 1 );
  20479. }
  20480. // find the leftmost node of a polygon ring
  20481. function getLeftmost( start ) {
  20482. let p = start,
  20483. leftmost = start;
  20484. do {
  20485. if ( p.x < leftmost.x || ( p.x === leftmost.x && p.y < leftmost.y ) ) leftmost = p;
  20486. p = p.next;
  20487. } while ( p !== start );
  20488. return leftmost;
  20489. }
  20490. // check if a point lies within a convex triangle
  20491. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  20492. return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
  20493. ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
  20494. ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;
  20495. }
  20496. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  20497. function isValidDiagonal( a, b ) {
  20498. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) && // doesn't intersect other edges
  20499. ( locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b ) && // locally visible
  20500. ( area( a.prev, a, b.prev ) || area( a, b.prev, b ) ) || // does not create opposite-facing sectors
  20501. equals( a, b ) && area( a.prev, a, a.next ) > 0 && area( b.prev, b, b.next ) > 0 ); // special zero-length case
  20502. }
  20503. // signed area of a triangle
  20504. function area( p, q, r ) {
  20505. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  20506. }
  20507. // check if two points are equal
  20508. function equals( p1, p2 ) {
  20509. return p1.x === p2.x && p1.y === p2.y;
  20510. }
  20511. // check if two segments intersect
  20512. function intersects( p1, q1, p2, q2 ) {
  20513. const o1 = sign( area( p1, q1, p2 ) );
  20514. const o2 = sign( area( p1, q1, q2 ) );
  20515. const o3 = sign( area( p2, q2, p1 ) );
  20516. const o4 = sign( area( p2, q2, q1 ) );
  20517. if ( o1 !== o2 && o3 !== o4 ) return true; // general case
  20518. if ( o1 === 0 && onSegment( p1, p2, q1 ) ) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  20519. if ( o2 === 0 && onSegment( p1, q2, q1 ) ) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  20520. if ( o3 === 0 && onSegment( p2, p1, q2 ) ) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  20521. if ( o4 === 0 && onSegment( p2, q1, q2 ) ) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  20522. return false;
  20523. }
  20524. // for collinear points p, q, r, check if point q lies on segment pr
  20525. function onSegment( p, q, r ) {
  20526. 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 );
  20527. }
  20528. function sign( num ) {
  20529. return num > 0 ? 1 : num < 0 ? - 1 : 0;
  20530. }
  20531. // check if a polygon diagonal intersects any polygon segments
  20532. function intersectsPolygon( a, b ) {
  20533. let p = a;
  20534. do {
  20535. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  20536. intersects( p, p.next, a, b ) ) return true;
  20537. p = p.next;
  20538. } while ( p !== a );
  20539. return false;
  20540. }
  20541. // check if a polygon diagonal is locally inside the polygon
  20542. function locallyInside( a, b ) {
  20543. return area( a.prev, a, a.next ) < 0 ?
  20544. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  20545. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  20546. }
  20547. // check if the middle point of a polygon diagonal is inside the polygon
  20548. function middleInside( a, b ) {
  20549. let p = a,
  20550. inside = false;
  20551. const px = ( a.x + b.x ) / 2,
  20552. py = ( a.y + b.y ) / 2;
  20553. do {
  20554. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  20555. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) )
  20556. inside = ! inside;
  20557. p = p.next;
  20558. } while ( p !== a );
  20559. return inside;
  20560. }
  20561. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  20562. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  20563. function splitPolygon( a, b ) {
  20564. const a2 = new Node( a.i, a.x, a.y ),
  20565. b2 = new Node( b.i, b.x, b.y ),
  20566. an = a.next,
  20567. bp = b.prev;
  20568. a.next = b;
  20569. b.prev = a;
  20570. a2.next = an;
  20571. an.prev = a2;
  20572. b2.next = a2;
  20573. a2.prev = b2;
  20574. bp.next = b2;
  20575. b2.prev = bp;
  20576. return b2;
  20577. }
  20578. // create a node and optionally link it with previous one (in a circular doubly linked list)
  20579. function insertNode( i, x, y, last ) {
  20580. const p = new Node( i, x, y );
  20581. if ( ! last ) {
  20582. p.prev = p;
  20583. p.next = p;
  20584. } else {
  20585. p.next = last.next;
  20586. p.prev = last;
  20587. last.next.prev = p;
  20588. last.next = p;
  20589. }
  20590. return p;
  20591. }
  20592. function removeNode( p ) {
  20593. p.next.prev = p.prev;
  20594. p.prev.next = p.next;
  20595. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  20596. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  20597. }
  20598. function Node( i, x, y ) {
  20599. // vertex index in coordinates array
  20600. this.i = i;
  20601. // vertex coordinates
  20602. this.x = x;
  20603. this.y = y;
  20604. // previous and next vertex nodes in a polygon ring
  20605. this.prev = null;
  20606. this.next = null;
  20607. // z-order curve value
  20608. this.z = null;
  20609. // previous and next nodes in z-order
  20610. this.prevZ = null;
  20611. this.nextZ = null;
  20612. // indicates whether this is a steiner point
  20613. this.steiner = false;
  20614. }
  20615. function signedArea( data, start, end, dim ) {
  20616. let sum = 0;
  20617. for ( let i = start, j = end - dim; i < end; i += dim ) {
  20618. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  20619. j = i;
  20620. }
  20621. return sum;
  20622. }
  20623. class ShapeUtils {
  20624. // calculate area of the contour polygon
  20625. static area( contour ) {
  20626. const n = contour.length;
  20627. let a = 0.0;
  20628. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  20629. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  20630. }
  20631. return a * 0.5;
  20632. }
  20633. static isClockWise( pts ) {
  20634. return ShapeUtils.area( pts ) < 0;
  20635. }
  20636. static triangulateShape( contour, holes ) {
  20637. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  20638. const holeIndices = []; // array of hole indices
  20639. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  20640. removeDupEndPts( contour );
  20641. addContour( vertices, contour );
  20642. //
  20643. let holeIndex = contour.length;
  20644. holes.forEach( removeDupEndPts );
  20645. for ( let i = 0; i < holes.length; i ++ ) {
  20646. holeIndices.push( holeIndex );
  20647. holeIndex += holes[ i ].length;
  20648. addContour( vertices, holes[ i ] );
  20649. }
  20650. //
  20651. const triangles = Earcut.triangulate( vertices, holeIndices );
  20652. //
  20653. for ( let i = 0; i < triangles.length; i += 3 ) {
  20654. faces.push( triangles.slice( i, i + 3 ) );
  20655. }
  20656. return faces;
  20657. }
  20658. }
  20659. function removeDupEndPts( points ) {
  20660. const l = points.length;
  20661. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  20662. points.pop();
  20663. }
  20664. }
  20665. function addContour( vertices, contour ) {
  20666. for ( let i = 0; i < contour.length; i ++ ) {
  20667. vertices.push( contour[ i ].x );
  20668. vertices.push( contour[ i ].y );
  20669. }
  20670. }
  20671. /**
  20672. * Creates extruded geometry from a path shape.
  20673. *
  20674. * parameters = {
  20675. *
  20676. * curveSegments: <int>, // number of points on the curves
  20677. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  20678. * depth: <float>, // Depth to extrude the shape
  20679. *
  20680. * bevelEnabled: <bool>, // turn on bevel
  20681. * bevelThickness: <float>, // how deep into the original shape bevel goes
  20682. * bevelSize: <float>, // how far from shape outline (including bevelOffset) is bevel
  20683. * bevelOffset: <float>, // how far from shape outline does bevel start
  20684. * bevelSegments: <int>, // number of bevel layers
  20685. *
  20686. * extrudePath: <THREE.Curve> // curve to extrude shape along
  20687. *
  20688. * UVGenerator: <Object> // object that provides UV generator functions
  20689. *
  20690. * }
  20691. */
  20692. class ExtrudeGeometry extends BufferGeometry {
  20693. 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 = {} ) {
  20694. super();
  20695. this.type = 'ExtrudeGeometry';
  20696. this.parameters = {
  20697. shapes: shapes,
  20698. options: options
  20699. };
  20700. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  20701. const scope = this;
  20702. const verticesArray = [];
  20703. const uvArray = [];
  20704. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  20705. const shape = shapes[ i ];
  20706. addShape( shape );
  20707. }
  20708. // build geometry
  20709. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  20710. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  20711. this.computeVertexNormals();
  20712. // functions
  20713. function addShape( shape ) {
  20714. const placeholder = [];
  20715. // options
  20716. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  20717. const steps = options.steps !== undefined ? options.steps : 1;
  20718. const depth = options.depth !== undefined ? options.depth : 1;
  20719. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  20720. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  20721. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  20722. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  20723. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  20724. const extrudePath = options.extrudePath;
  20725. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  20726. //
  20727. let extrudePts, extrudeByPath = false;
  20728. let splineTube, binormal, normal, position2;
  20729. if ( extrudePath ) {
  20730. extrudePts = extrudePath.getSpacedPoints( steps );
  20731. extrudeByPath = true;
  20732. bevelEnabled = false; // bevels not supported for path extrusion
  20733. // SETUP TNB variables
  20734. // TODO1 - have a .isClosed in spline?
  20735. splineTube = extrudePath.computeFrenetFrames( steps, false );
  20736. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  20737. binormal = new Vector3();
  20738. normal = new Vector3();
  20739. position2 = new Vector3();
  20740. }
  20741. // Safeguards if bevels are not enabled
  20742. if ( ! bevelEnabled ) {
  20743. bevelSegments = 0;
  20744. bevelThickness = 0;
  20745. bevelSize = 0;
  20746. bevelOffset = 0;
  20747. }
  20748. // Variables initialization
  20749. const shapePoints = shape.extractPoints( curveSegments );
  20750. let vertices = shapePoints.shape;
  20751. const holes = shapePoints.holes;
  20752. const reverse = ! ShapeUtils.isClockWise( vertices );
  20753. if ( reverse ) {
  20754. vertices = vertices.reverse();
  20755. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  20756. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20757. const ahole = holes[ h ];
  20758. if ( ShapeUtils.isClockWise( ahole ) ) {
  20759. holes[ h ] = ahole.reverse();
  20760. }
  20761. }
  20762. }
  20763. const faces = ShapeUtils.triangulateShape( vertices, holes );
  20764. /* Vertices */
  20765. const contour = vertices; // vertices has all points but contour has only points of circumference
  20766. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20767. const ahole = holes[ h ];
  20768. vertices = vertices.concat( ahole );
  20769. }
  20770. function scalePt2( pt, vec, size ) {
  20771. if ( ! vec ) console.error( 'THREE.ExtrudeGeometry: vec does not exist' );
  20772. return vec.clone().multiplyScalar( size ).add( pt );
  20773. }
  20774. const vlen = vertices.length, flen = faces.length;
  20775. // Find directions for point movement
  20776. function getBevelVec( inPt, inPrev, inNext ) {
  20777. // computes for inPt the corresponding point inPt' on a new contour
  20778. // shifted by 1 unit (length of normalized vector) to the left
  20779. // if we walk along contour clockwise, this new contour is outside the old one
  20780. //
  20781. // inPt' is the intersection of the two lines parallel to the two
  20782. // adjacent edges of inPt at a distance of 1 unit on the left side.
  20783. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  20784. // good reading for geometry algorithms (here: line-line intersection)
  20785. // http://geomalgorithms.com/a05-_intersect-1.html
  20786. const v_prev_x = inPt.x - inPrev.x,
  20787. v_prev_y = inPt.y - inPrev.y;
  20788. const v_next_x = inNext.x - inPt.x,
  20789. v_next_y = inNext.y - inPt.y;
  20790. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  20791. // check for collinear edges
  20792. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  20793. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  20794. // not collinear
  20795. // length of vectors for normalizing
  20796. const v_prev_len = Math.sqrt( v_prev_lensq );
  20797. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  20798. // shift adjacent points by unit vectors to the left
  20799. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  20800. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  20801. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  20802. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  20803. // scaling factor for v_prev to intersection point
  20804. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  20805. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  20806. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  20807. // vector from inPt to intersection point
  20808. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  20809. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  20810. // Don't normalize!, otherwise sharp corners become ugly
  20811. // but prevent crazy spikes
  20812. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  20813. if ( v_trans_lensq <= 2 ) {
  20814. return new Vector2( v_trans_x, v_trans_y );
  20815. } else {
  20816. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  20817. }
  20818. } else {
  20819. // handle special case of collinear edges
  20820. let direction_eq = false; // assumes: opposite
  20821. if ( v_prev_x > Number.EPSILON ) {
  20822. if ( v_next_x > Number.EPSILON ) {
  20823. direction_eq = true;
  20824. }
  20825. } else {
  20826. if ( v_prev_x < - Number.EPSILON ) {
  20827. if ( v_next_x < - Number.EPSILON ) {
  20828. direction_eq = true;
  20829. }
  20830. } else {
  20831. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  20832. direction_eq = true;
  20833. }
  20834. }
  20835. }
  20836. if ( direction_eq ) {
  20837. // console.log("Warning: lines are a straight sequence");
  20838. v_trans_x = - v_prev_y;
  20839. v_trans_y = v_prev_x;
  20840. shrink_by = Math.sqrt( v_prev_lensq );
  20841. } else {
  20842. // console.log("Warning: lines are a straight spike");
  20843. v_trans_x = v_prev_x;
  20844. v_trans_y = v_prev_y;
  20845. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  20846. }
  20847. }
  20848. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  20849. }
  20850. const contourMovements = [];
  20851. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  20852. if ( j === il ) j = 0;
  20853. if ( k === il ) k = 0;
  20854. // (j)---(i)---(k)
  20855. // console.log('i,j,k', i, j , k)
  20856. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  20857. }
  20858. const holesMovements = [];
  20859. let oneHoleMovements, verticesMovements = contourMovements.concat();
  20860. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20861. const ahole = holes[ h ];
  20862. oneHoleMovements = [];
  20863. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  20864. if ( j === il ) j = 0;
  20865. if ( k === il ) k = 0;
  20866. // (j)---(i)---(k)
  20867. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  20868. }
  20869. holesMovements.push( oneHoleMovements );
  20870. verticesMovements = verticesMovements.concat( oneHoleMovements );
  20871. }
  20872. // Loop bevelSegments, 1 for the front, 1 for the back
  20873. for ( let b = 0; b < bevelSegments; b ++ ) {
  20874. //for ( b = bevelSegments; b > 0; b -- ) {
  20875. const t = b / bevelSegments;
  20876. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  20877. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  20878. // contract shape
  20879. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  20880. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  20881. v( vert.x, vert.y, - z );
  20882. }
  20883. // expand holes
  20884. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20885. const ahole = holes[ h ];
  20886. oneHoleMovements = holesMovements[ h ];
  20887. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  20888. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  20889. v( vert.x, vert.y, - z );
  20890. }
  20891. }
  20892. }
  20893. const bs = bevelSize + bevelOffset;
  20894. // Back facing vertices
  20895. for ( let i = 0; i < vlen; i ++ ) {
  20896. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  20897. if ( ! extrudeByPath ) {
  20898. v( vert.x, vert.y, 0 );
  20899. } else {
  20900. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  20901. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  20902. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  20903. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  20904. v( position2.x, position2.y, position2.z );
  20905. }
  20906. }
  20907. // Add stepped vertices...
  20908. // Including front facing vertices
  20909. for ( let s = 1; s <= steps; s ++ ) {
  20910. for ( let i = 0; i < vlen; i ++ ) {
  20911. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  20912. if ( ! extrudeByPath ) {
  20913. v( vert.x, vert.y, depth / steps * s );
  20914. } else {
  20915. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  20916. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  20917. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  20918. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  20919. v( position2.x, position2.y, position2.z );
  20920. }
  20921. }
  20922. }
  20923. // Add bevel segments planes
  20924. //for ( b = 1; b <= bevelSegments; b ++ ) {
  20925. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  20926. const t = b / bevelSegments;
  20927. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  20928. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  20929. // contract shape
  20930. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  20931. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  20932. v( vert.x, vert.y, depth + z );
  20933. }
  20934. // expand holes
  20935. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20936. const ahole = holes[ h ];
  20937. oneHoleMovements = holesMovements[ h ];
  20938. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  20939. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  20940. if ( ! extrudeByPath ) {
  20941. v( vert.x, vert.y, depth + z );
  20942. } else {
  20943. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  20944. }
  20945. }
  20946. }
  20947. }
  20948. /* Faces */
  20949. // Top and bottom faces
  20950. buildLidFaces();
  20951. // Sides faces
  20952. buildSideFaces();
  20953. ///// Internal functions
  20954. function buildLidFaces() {
  20955. const start = verticesArray.length / 3;
  20956. if ( bevelEnabled ) {
  20957. let layer = 0; // steps + 1
  20958. let offset = vlen * layer;
  20959. // Bottom faces
  20960. for ( let i = 0; i < flen; i ++ ) {
  20961. const face = faces[ i ];
  20962. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  20963. }
  20964. layer = steps + bevelSegments * 2;
  20965. offset = vlen * layer;
  20966. // Top faces
  20967. for ( let i = 0; i < flen; i ++ ) {
  20968. const face = faces[ i ];
  20969. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  20970. }
  20971. } else {
  20972. // Bottom faces
  20973. for ( let i = 0; i < flen; i ++ ) {
  20974. const face = faces[ i ];
  20975. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  20976. }
  20977. // Top faces
  20978. for ( let i = 0; i < flen; i ++ ) {
  20979. const face = faces[ i ];
  20980. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  20981. }
  20982. }
  20983. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  20984. }
  20985. // Create faces for the z-sides of the shape
  20986. function buildSideFaces() {
  20987. const start = verticesArray.length / 3;
  20988. let layeroffset = 0;
  20989. sidewalls( contour, layeroffset );
  20990. layeroffset += contour.length;
  20991. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  20992. const ahole = holes[ h ];
  20993. sidewalls( ahole, layeroffset );
  20994. //, true
  20995. layeroffset += ahole.length;
  20996. }
  20997. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  20998. }
  20999. function sidewalls( contour, layeroffset ) {
  21000. let i = contour.length;
  21001. while ( -- i >= 0 ) {
  21002. const j = i;
  21003. let k = i - 1;
  21004. if ( k < 0 ) k = contour.length - 1;
  21005. //console.log('b', i,j, i-1, k,vertices.length);
  21006. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  21007. const slen1 = vlen * s;
  21008. const slen2 = vlen * ( s + 1 );
  21009. const a = layeroffset + j + slen1,
  21010. b = layeroffset + k + slen1,
  21011. c = layeroffset + k + slen2,
  21012. d = layeroffset + j + slen2;
  21013. f4( a, b, c, d );
  21014. }
  21015. }
  21016. }
  21017. function v( x, y, z ) {
  21018. placeholder.push( x );
  21019. placeholder.push( y );
  21020. placeholder.push( z );
  21021. }
  21022. function f3( a, b, c ) {
  21023. addVertex( a );
  21024. addVertex( b );
  21025. addVertex( c );
  21026. const nextIndex = verticesArray.length / 3;
  21027. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21028. addUV( uvs[ 0 ] );
  21029. addUV( uvs[ 1 ] );
  21030. addUV( uvs[ 2 ] );
  21031. }
  21032. function f4( a, b, c, d ) {
  21033. addVertex( a );
  21034. addVertex( b );
  21035. addVertex( d );
  21036. addVertex( b );
  21037. addVertex( c );
  21038. addVertex( d );
  21039. const nextIndex = verticesArray.length / 3;
  21040. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21041. addUV( uvs[ 0 ] );
  21042. addUV( uvs[ 1 ] );
  21043. addUV( uvs[ 3 ] );
  21044. addUV( uvs[ 1 ] );
  21045. addUV( uvs[ 2 ] );
  21046. addUV( uvs[ 3 ] );
  21047. }
  21048. function addVertex( index ) {
  21049. verticesArray.push( placeholder[ index * 3 + 0 ] );
  21050. verticesArray.push( placeholder[ index * 3 + 1 ] );
  21051. verticesArray.push( placeholder[ index * 3 + 2 ] );
  21052. }
  21053. function addUV( vector2 ) {
  21054. uvArray.push( vector2.x );
  21055. uvArray.push( vector2.y );
  21056. }
  21057. }
  21058. }
  21059. toJSON() {
  21060. const data = super.toJSON();
  21061. const shapes = this.parameters.shapes;
  21062. const options = this.parameters.options;
  21063. return toJSON$1( shapes, options, data );
  21064. }
  21065. static fromJSON( data, shapes ) {
  21066. const geometryShapes = [];
  21067. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21068. const shape = shapes[ data.shapes[ j ] ];
  21069. geometryShapes.push( shape );
  21070. }
  21071. const extrudePath = data.options.extrudePath;
  21072. if ( extrudePath !== undefined ) {
  21073. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  21074. }
  21075. return new ExtrudeGeometry( geometryShapes, data.options );
  21076. }
  21077. }
  21078. const WorldUVGenerator = {
  21079. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  21080. const a_x = vertices[ indexA * 3 ];
  21081. const a_y = vertices[ indexA * 3 + 1 ];
  21082. const b_x = vertices[ indexB * 3 ];
  21083. const b_y = vertices[ indexB * 3 + 1 ];
  21084. const c_x = vertices[ indexC * 3 ];
  21085. const c_y = vertices[ indexC * 3 + 1 ];
  21086. return [
  21087. new Vector2( a_x, a_y ),
  21088. new Vector2( b_x, b_y ),
  21089. new Vector2( c_x, c_y )
  21090. ];
  21091. },
  21092. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  21093. const a_x = vertices[ indexA * 3 ];
  21094. const a_y = vertices[ indexA * 3 + 1 ];
  21095. const a_z = vertices[ indexA * 3 + 2 ];
  21096. const b_x = vertices[ indexB * 3 ];
  21097. const b_y = vertices[ indexB * 3 + 1 ];
  21098. const b_z = vertices[ indexB * 3 + 2 ];
  21099. const c_x = vertices[ indexC * 3 ];
  21100. const c_y = vertices[ indexC * 3 + 1 ];
  21101. const c_z = vertices[ indexC * 3 + 2 ];
  21102. const d_x = vertices[ indexD * 3 ];
  21103. const d_y = vertices[ indexD * 3 + 1 ];
  21104. const d_z = vertices[ indexD * 3 + 2 ];
  21105. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  21106. return [
  21107. new Vector2( a_x, 1 - a_z ),
  21108. new Vector2( b_x, 1 - b_z ),
  21109. new Vector2( c_x, 1 - c_z ),
  21110. new Vector2( d_x, 1 - d_z )
  21111. ];
  21112. } else {
  21113. return [
  21114. new Vector2( a_y, 1 - a_z ),
  21115. new Vector2( b_y, 1 - b_z ),
  21116. new Vector2( c_y, 1 - c_z ),
  21117. new Vector2( d_y, 1 - d_z )
  21118. ];
  21119. }
  21120. }
  21121. };
  21122. function toJSON$1( shapes, options, data ) {
  21123. data.shapes = [];
  21124. if ( Array.isArray( shapes ) ) {
  21125. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21126. const shape = shapes[ i ];
  21127. data.shapes.push( shape.uuid );
  21128. }
  21129. } else {
  21130. data.shapes.push( shapes.uuid );
  21131. }
  21132. data.options = Object.assign( {}, options );
  21133. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  21134. return data;
  21135. }
  21136. class IcosahedronGeometry extends PolyhedronGeometry {
  21137. constructor( radius = 1, detail = 0 ) {
  21138. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21139. const vertices = [
  21140. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  21141. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  21142. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  21143. ];
  21144. const indices = [
  21145. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  21146. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  21147. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  21148. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  21149. ];
  21150. super( vertices, indices, radius, detail );
  21151. this.type = 'IcosahedronGeometry';
  21152. this.parameters = {
  21153. radius: radius,
  21154. detail: detail
  21155. };
  21156. }
  21157. static fromJSON( data ) {
  21158. return new IcosahedronGeometry( data.radius, data.detail );
  21159. }
  21160. }
  21161. class OctahedronGeometry extends PolyhedronGeometry {
  21162. constructor( radius = 1, detail = 0 ) {
  21163. const vertices = [
  21164. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  21165. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  21166. ];
  21167. const indices = [
  21168. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  21169. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  21170. 1, 3, 4, 1, 4, 2
  21171. ];
  21172. super( vertices, indices, radius, detail );
  21173. this.type = 'OctahedronGeometry';
  21174. this.parameters = {
  21175. radius: radius,
  21176. detail: detail
  21177. };
  21178. }
  21179. static fromJSON( data ) {
  21180. return new OctahedronGeometry( data.radius, data.detail );
  21181. }
  21182. }
  21183. class RingGeometry extends BufferGeometry {
  21184. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 8, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  21185. super();
  21186. this.type = 'RingGeometry';
  21187. this.parameters = {
  21188. innerRadius: innerRadius,
  21189. outerRadius: outerRadius,
  21190. thetaSegments: thetaSegments,
  21191. phiSegments: phiSegments,
  21192. thetaStart: thetaStart,
  21193. thetaLength: thetaLength
  21194. };
  21195. thetaSegments = Math.max( 3, thetaSegments );
  21196. phiSegments = Math.max( 1, phiSegments );
  21197. // buffers
  21198. const indices = [];
  21199. const vertices = [];
  21200. const normals = [];
  21201. const uvs = [];
  21202. // some helper variables
  21203. let radius = innerRadius;
  21204. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  21205. const vertex = new Vector3();
  21206. const uv = new Vector2();
  21207. // generate vertices, normals and uvs
  21208. for ( let j = 0; j <= phiSegments; j ++ ) {
  21209. for ( let i = 0; i <= thetaSegments; i ++ ) {
  21210. // values are generate from the inside of the ring to the outside
  21211. const segment = thetaStart + i / thetaSegments * thetaLength;
  21212. // vertex
  21213. vertex.x = radius * Math.cos( segment );
  21214. vertex.y = radius * Math.sin( segment );
  21215. vertices.push( vertex.x, vertex.y, vertex.z );
  21216. // normal
  21217. normals.push( 0, 0, 1 );
  21218. // uv
  21219. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  21220. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  21221. uvs.push( uv.x, uv.y );
  21222. }
  21223. // increase the radius for next row of vertices
  21224. radius += radiusStep;
  21225. }
  21226. // indices
  21227. for ( let j = 0; j < phiSegments; j ++ ) {
  21228. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  21229. for ( let i = 0; i < thetaSegments; i ++ ) {
  21230. const segment = i + thetaSegmentLevel;
  21231. const a = segment;
  21232. const b = segment + thetaSegments + 1;
  21233. const c = segment + thetaSegments + 2;
  21234. const d = segment + 1;
  21235. // faces
  21236. indices.push( a, b, d );
  21237. indices.push( b, c, d );
  21238. }
  21239. }
  21240. // build geometry
  21241. this.setIndex( indices );
  21242. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21243. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21244. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21245. }
  21246. static fromJSON( data ) {
  21247. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  21248. }
  21249. }
  21250. class ShapeGeometry extends BufferGeometry {
  21251. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( - 0.5, - 0.5 ), new Vector2( 0.5, - 0.5 ) ] ), curveSegments = 12 ) {
  21252. super();
  21253. this.type = 'ShapeGeometry';
  21254. this.parameters = {
  21255. shapes: shapes,
  21256. curveSegments: curveSegments
  21257. };
  21258. // buffers
  21259. const indices = [];
  21260. const vertices = [];
  21261. const normals = [];
  21262. const uvs = [];
  21263. // helper variables
  21264. let groupStart = 0;
  21265. let groupCount = 0;
  21266. // allow single and array values for "shapes" parameter
  21267. if ( Array.isArray( shapes ) === false ) {
  21268. addShape( shapes );
  21269. } else {
  21270. for ( let i = 0; i < shapes.length; i ++ ) {
  21271. addShape( shapes[ i ] );
  21272. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  21273. groupStart += groupCount;
  21274. groupCount = 0;
  21275. }
  21276. }
  21277. // build geometry
  21278. this.setIndex( indices );
  21279. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21280. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21281. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21282. // helper functions
  21283. function addShape( shape ) {
  21284. const indexOffset = vertices.length / 3;
  21285. const points = shape.extractPoints( curveSegments );
  21286. let shapeVertices = points.shape;
  21287. const shapeHoles = points.holes;
  21288. // check direction of vertices
  21289. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  21290. shapeVertices = shapeVertices.reverse();
  21291. }
  21292. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21293. const shapeHole = shapeHoles[ i ];
  21294. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  21295. shapeHoles[ i ] = shapeHole.reverse();
  21296. }
  21297. }
  21298. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  21299. // join vertices of inner and outer paths to a single array
  21300. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21301. const shapeHole = shapeHoles[ i ];
  21302. shapeVertices = shapeVertices.concat( shapeHole );
  21303. }
  21304. // vertices, normals, uvs
  21305. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  21306. const vertex = shapeVertices[ i ];
  21307. vertices.push( vertex.x, vertex.y, 0 );
  21308. normals.push( 0, 0, 1 );
  21309. uvs.push( vertex.x, vertex.y ); // world uvs
  21310. }
  21311. // incides
  21312. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  21313. const face = faces[ i ];
  21314. const a = face[ 0 ] + indexOffset;
  21315. const b = face[ 1 ] + indexOffset;
  21316. const c = face[ 2 ] + indexOffset;
  21317. indices.push( a, b, c );
  21318. groupCount += 3;
  21319. }
  21320. }
  21321. }
  21322. toJSON() {
  21323. const data = super.toJSON();
  21324. const shapes = this.parameters.shapes;
  21325. return toJSON( shapes, data );
  21326. }
  21327. static fromJSON( data, shapes ) {
  21328. const geometryShapes = [];
  21329. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  21330. const shape = shapes[ data.shapes[ j ] ];
  21331. geometryShapes.push( shape );
  21332. }
  21333. return new ShapeGeometry( geometryShapes, data.curveSegments );
  21334. }
  21335. }
  21336. function toJSON( shapes, data ) {
  21337. data.shapes = [];
  21338. if ( Array.isArray( shapes ) ) {
  21339. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  21340. const shape = shapes[ i ];
  21341. data.shapes.push( shape.uuid );
  21342. }
  21343. } else {
  21344. data.shapes.push( shapes.uuid );
  21345. }
  21346. return data;
  21347. }
  21348. class SphereGeometry extends BufferGeometry {
  21349. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  21350. super();
  21351. this.type = 'SphereGeometry';
  21352. this.parameters = {
  21353. radius: radius,
  21354. widthSegments: widthSegments,
  21355. heightSegments: heightSegments,
  21356. phiStart: phiStart,
  21357. phiLength: phiLength,
  21358. thetaStart: thetaStart,
  21359. thetaLength: thetaLength
  21360. };
  21361. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  21362. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  21363. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  21364. let index = 0;
  21365. const grid = [];
  21366. const vertex = new Vector3();
  21367. const normal = new Vector3();
  21368. // buffers
  21369. const indices = [];
  21370. const vertices = [];
  21371. const normals = [];
  21372. const uvs = [];
  21373. // generate vertices, normals and uvs
  21374. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  21375. const verticesRow = [];
  21376. const v = iy / heightSegments;
  21377. // special case for the poles
  21378. let uOffset = 0;
  21379. if ( iy == 0 && thetaStart == 0 ) {
  21380. uOffset = 0.5 / widthSegments;
  21381. } else if ( iy == heightSegments && thetaEnd == Math.PI ) {
  21382. uOffset = - 0.5 / widthSegments;
  21383. }
  21384. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  21385. const u = ix / widthSegments;
  21386. // vertex
  21387. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21388. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  21389. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21390. vertices.push( vertex.x, vertex.y, vertex.z );
  21391. // normal
  21392. normal.copy( vertex ).normalize();
  21393. normals.push( normal.x, normal.y, normal.z );
  21394. // uv
  21395. uvs.push( u + uOffset, 1 - v );
  21396. verticesRow.push( index ++ );
  21397. }
  21398. grid.push( verticesRow );
  21399. }
  21400. // indices
  21401. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  21402. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  21403. const a = grid[ iy ][ ix + 1 ];
  21404. const b = grid[ iy ][ ix ];
  21405. const c = grid[ iy + 1 ][ ix ];
  21406. const d = grid[ iy + 1 ][ ix + 1 ];
  21407. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  21408. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  21409. }
  21410. }
  21411. // build geometry
  21412. this.setIndex( indices );
  21413. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21414. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21415. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21416. }
  21417. static fromJSON( data ) {
  21418. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  21419. }
  21420. }
  21421. class TetrahedronGeometry extends PolyhedronGeometry {
  21422. constructor( radius = 1, detail = 0 ) {
  21423. const vertices = [
  21424. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  21425. ];
  21426. const indices = [
  21427. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  21428. ];
  21429. super( vertices, indices, radius, detail );
  21430. this.type = 'TetrahedronGeometry';
  21431. this.parameters = {
  21432. radius: radius,
  21433. detail: detail
  21434. };
  21435. }
  21436. static fromJSON( data ) {
  21437. return new TetrahedronGeometry( data.radius, data.detail );
  21438. }
  21439. }
  21440. class TorusGeometry extends BufferGeometry {
  21441. constructor( radius = 1, tube = 0.4, radialSegments = 8, tubularSegments = 6, arc = Math.PI * 2 ) {
  21442. super();
  21443. this.type = 'TorusGeometry';
  21444. this.parameters = {
  21445. radius: radius,
  21446. tube: tube,
  21447. radialSegments: radialSegments,
  21448. tubularSegments: tubularSegments,
  21449. arc: arc
  21450. };
  21451. radialSegments = Math.floor( radialSegments );
  21452. tubularSegments = Math.floor( tubularSegments );
  21453. // buffers
  21454. const indices = [];
  21455. const vertices = [];
  21456. const normals = [];
  21457. const uvs = [];
  21458. // helper variables
  21459. const center = new Vector3();
  21460. const vertex = new Vector3();
  21461. const normal = new Vector3();
  21462. // generate vertices, normals and uvs
  21463. for ( let j = 0; j <= radialSegments; j ++ ) {
  21464. for ( let i = 0; i <= tubularSegments; i ++ ) {
  21465. const u = i / tubularSegments * arc;
  21466. const v = j / radialSegments * Math.PI * 2;
  21467. // vertex
  21468. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  21469. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  21470. vertex.z = tube * Math.sin( v );
  21471. vertices.push( vertex.x, vertex.y, vertex.z );
  21472. // normal
  21473. center.x = radius * Math.cos( u );
  21474. center.y = radius * Math.sin( u );
  21475. normal.subVectors( vertex, center ).normalize();
  21476. normals.push( normal.x, normal.y, normal.z );
  21477. // uv
  21478. uvs.push( i / tubularSegments );
  21479. uvs.push( j / radialSegments );
  21480. }
  21481. }
  21482. // generate indices
  21483. for ( let j = 1; j <= radialSegments; j ++ ) {
  21484. for ( let i = 1; i <= tubularSegments; i ++ ) {
  21485. // indices
  21486. const a = ( tubularSegments + 1 ) * j + i - 1;
  21487. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  21488. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  21489. const d = ( tubularSegments + 1 ) * j + i;
  21490. // faces
  21491. indices.push( a, b, d );
  21492. indices.push( b, c, d );
  21493. }
  21494. }
  21495. // build geometry
  21496. this.setIndex( indices );
  21497. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21498. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21499. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21500. }
  21501. static fromJSON( data ) {
  21502. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  21503. }
  21504. }
  21505. class TorusKnotGeometry extends BufferGeometry {
  21506. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  21507. super();
  21508. this.type = 'TorusKnotGeometry';
  21509. this.parameters = {
  21510. radius: radius,
  21511. tube: tube,
  21512. tubularSegments: tubularSegments,
  21513. radialSegments: radialSegments,
  21514. p: p,
  21515. q: q
  21516. };
  21517. tubularSegments = Math.floor( tubularSegments );
  21518. radialSegments = Math.floor( radialSegments );
  21519. // buffers
  21520. const indices = [];
  21521. const vertices = [];
  21522. const normals = [];
  21523. const uvs = [];
  21524. // helper variables
  21525. const vertex = new Vector3();
  21526. const normal = new Vector3();
  21527. const P1 = new Vector3();
  21528. const P2 = new Vector3();
  21529. const B = new Vector3();
  21530. const T = new Vector3();
  21531. const N = new Vector3();
  21532. // generate vertices, normals and uvs
  21533. for ( let i = 0; i <= tubularSegments; ++ i ) {
  21534. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  21535. const u = i / tubularSegments * p * Math.PI * 2;
  21536. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  21537. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  21538. calculatePositionOnCurve( u, p, q, radius, P1 );
  21539. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  21540. // calculate orthonormal basis
  21541. T.subVectors( P2, P1 );
  21542. N.addVectors( P2, P1 );
  21543. B.crossVectors( T, N );
  21544. N.crossVectors( B, T );
  21545. // normalize B, N. T can be ignored, we don't use it
  21546. B.normalize();
  21547. N.normalize();
  21548. for ( let j = 0; j <= radialSegments; ++ j ) {
  21549. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  21550. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  21551. const v = j / radialSegments * Math.PI * 2;
  21552. const cx = - tube * Math.cos( v );
  21553. const cy = tube * Math.sin( v );
  21554. // now calculate the final vertex position.
  21555. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  21556. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  21557. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  21558. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  21559. vertices.push( vertex.x, vertex.y, vertex.z );
  21560. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  21561. normal.subVectors( vertex, P1 ).normalize();
  21562. normals.push( normal.x, normal.y, normal.z );
  21563. // uv
  21564. uvs.push( i / tubularSegments );
  21565. uvs.push( j / radialSegments );
  21566. }
  21567. }
  21568. // generate indices
  21569. for ( let j = 1; j <= tubularSegments; j ++ ) {
  21570. for ( let i = 1; i <= radialSegments; i ++ ) {
  21571. // indices
  21572. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  21573. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  21574. const c = ( radialSegments + 1 ) * j + i;
  21575. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  21576. // faces
  21577. indices.push( a, b, d );
  21578. indices.push( b, c, d );
  21579. }
  21580. }
  21581. // build geometry
  21582. this.setIndex( indices );
  21583. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21584. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21585. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21586. // this function calculates the current position on the torus curve
  21587. function calculatePositionOnCurve( u, p, q, radius, position ) {
  21588. const cu = Math.cos( u );
  21589. const su = Math.sin( u );
  21590. const quOverP = q / p * u;
  21591. const cs = Math.cos( quOverP );
  21592. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  21593. position.y = radius * ( 2 + cs ) * su * 0.5;
  21594. position.z = radius * Math.sin( quOverP ) * 0.5;
  21595. }
  21596. }
  21597. static fromJSON( data ) {
  21598. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  21599. }
  21600. }
  21601. class TubeGeometry extends BufferGeometry {
  21602. 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 ) {
  21603. super();
  21604. this.type = 'TubeGeometry';
  21605. this.parameters = {
  21606. path: path,
  21607. tubularSegments: tubularSegments,
  21608. radius: radius,
  21609. radialSegments: radialSegments,
  21610. closed: closed
  21611. };
  21612. const frames = path.computeFrenetFrames( tubularSegments, closed );
  21613. // expose internals
  21614. this.tangents = frames.tangents;
  21615. this.normals = frames.normals;
  21616. this.binormals = frames.binormals;
  21617. // helper variables
  21618. const vertex = new Vector3();
  21619. const normal = new Vector3();
  21620. const uv = new Vector2();
  21621. let P = new Vector3();
  21622. // buffer
  21623. const vertices = [];
  21624. const normals = [];
  21625. const uvs = [];
  21626. const indices = [];
  21627. // create buffer data
  21628. generateBufferData();
  21629. // build geometry
  21630. this.setIndex( indices );
  21631. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21632. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21633. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21634. // functions
  21635. function generateBufferData() {
  21636. for ( let i = 0; i < tubularSegments; i ++ ) {
  21637. generateSegment( i );
  21638. }
  21639. // if the geometry is not closed, generate the last row of vertices and normals
  21640. // at the regular position on the given path
  21641. //
  21642. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  21643. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  21644. // uvs are generated in a separate function.
  21645. // this makes it easy compute correct values for closed geometries
  21646. generateUVs();
  21647. // finally create faces
  21648. generateIndices();
  21649. }
  21650. function generateSegment( i ) {
  21651. // we use getPointAt to sample evenly distributed points from the given path
  21652. P = path.getPointAt( i / tubularSegments, P );
  21653. // retrieve corresponding normal and binormal
  21654. const N = frames.normals[ i ];
  21655. const B = frames.binormals[ i ];
  21656. // generate normals and vertices for the current segment
  21657. for ( let j = 0; j <= radialSegments; j ++ ) {
  21658. const v = j / radialSegments * Math.PI * 2;
  21659. const sin = Math.sin( v );
  21660. const cos = - Math.cos( v );
  21661. // normal
  21662. normal.x = ( cos * N.x + sin * B.x );
  21663. normal.y = ( cos * N.y + sin * B.y );
  21664. normal.z = ( cos * N.z + sin * B.z );
  21665. normal.normalize();
  21666. normals.push( normal.x, normal.y, normal.z );
  21667. // vertex
  21668. vertex.x = P.x + radius * normal.x;
  21669. vertex.y = P.y + radius * normal.y;
  21670. vertex.z = P.z + radius * normal.z;
  21671. vertices.push( vertex.x, vertex.y, vertex.z );
  21672. }
  21673. }
  21674. function generateIndices() {
  21675. for ( let j = 1; j <= tubularSegments; j ++ ) {
  21676. for ( let i = 1; i <= radialSegments; i ++ ) {
  21677. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  21678. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  21679. const c = ( radialSegments + 1 ) * j + i;
  21680. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  21681. // faces
  21682. indices.push( a, b, d );
  21683. indices.push( b, c, d );
  21684. }
  21685. }
  21686. }
  21687. function generateUVs() {
  21688. for ( let i = 0; i <= tubularSegments; i ++ ) {
  21689. for ( let j = 0; j <= radialSegments; j ++ ) {
  21690. uv.x = i / tubularSegments;
  21691. uv.y = j / radialSegments;
  21692. uvs.push( uv.x, uv.y );
  21693. }
  21694. }
  21695. }
  21696. }
  21697. toJSON() {
  21698. const data = super.toJSON();
  21699. data.path = this.parameters.path.toJSON();
  21700. return data;
  21701. }
  21702. static fromJSON( data ) {
  21703. // This only works for built-in curves (e.g. CatmullRomCurve3).
  21704. // User defined curves or instances of CurvePath will not be deserialized.
  21705. return new TubeGeometry(
  21706. new Curves[ data.path.type ]().fromJSON( data.path ),
  21707. data.tubularSegments,
  21708. data.radius,
  21709. data.radialSegments,
  21710. data.closed
  21711. );
  21712. }
  21713. }
  21714. class WireframeGeometry extends BufferGeometry {
  21715. constructor( geometry = null ) {
  21716. super();
  21717. this.type = 'WireframeGeometry';
  21718. this.parameters = {
  21719. geometry: geometry
  21720. };
  21721. if ( geometry !== null ) {
  21722. // buffer
  21723. const vertices = [];
  21724. const edges = new Set();
  21725. // helper variables
  21726. const start = new Vector3();
  21727. const end = new Vector3();
  21728. if ( geometry.index !== null ) {
  21729. // indexed BufferGeometry
  21730. const position = geometry.attributes.position;
  21731. const indices = geometry.index;
  21732. let groups = geometry.groups;
  21733. if ( groups.length === 0 ) {
  21734. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  21735. }
  21736. // create a data structure that contains all edges without duplicates
  21737. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  21738. const group = groups[ o ];
  21739. const groupStart = group.start;
  21740. const groupCount = group.count;
  21741. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  21742. for ( let j = 0; j < 3; j ++ ) {
  21743. const index1 = indices.getX( i + j );
  21744. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  21745. start.fromBufferAttribute( position, index1 );
  21746. end.fromBufferAttribute( position, index2 );
  21747. if ( isUniqueEdge( start, end, edges ) === true ) {
  21748. vertices.push( start.x, start.y, start.z );
  21749. vertices.push( end.x, end.y, end.z );
  21750. }
  21751. }
  21752. }
  21753. }
  21754. } else {
  21755. // non-indexed BufferGeometry
  21756. const position = geometry.attributes.position;
  21757. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  21758. for ( let j = 0; j < 3; j ++ ) {
  21759. // three edges per triangle, an edge is represented as (index1, index2)
  21760. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  21761. const index1 = 3 * i + j;
  21762. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  21763. start.fromBufferAttribute( position, index1 );
  21764. end.fromBufferAttribute( position, index2 );
  21765. if ( isUniqueEdge( start, end, edges ) === true ) {
  21766. vertices.push( start.x, start.y, start.z );
  21767. vertices.push( end.x, end.y, end.z );
  21768. }
  21769. }
  21770. }
  21771. }
  21772. // build geometry
  21773. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21774. }
  21775. }
  21776. }
  21777. function isUniqueEdge( start, end, edges ) {
  21778. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  21779. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  21780. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  21781. return false;
  21782. } else {
  21783. edges.add( hash1 );
  21784. edges.add( hash2 );
  21785. return true;
  21786. }
  21787. }
  21788. var Geometries = /*#__PURE__*/Object.freeze({
  21789. __proto__: null,
  21790. BoxGeometry: BoxGeometry,
  21791. CapsuleGeometry: CapsuleGeometry,
  21792. CircleGeometry: CircleGeometry,
  21793. ConeGeometry: ConeGeometry,
  21794. CylinderGeometry: CylinderGeometry,
  21795. DodecahedronGeometry: DodecahedronGeometry,
  21796. EdgesGeometry: EdgesGeometry,
  21797. ExtrudeGeometry: ExtrudeGeometry,
  21798. IcosahedronGeometry: IcosahedronGeometry,
  21799. LatheGeometry: LatheGeometry,
  21800. OctahedronGeometry: OctahedronGeometry,
  21801. PlaneGeometry: PlaneGeometry,
  21802. PolyhedronGeometry: PolyhedronGeometry,
  21803. RingGeometry: RingGeometry,
  21804. ShapeGeometry: ShapeGeometry,
  21805. SphereGeometry: SphereGeometry,
  21806. TetrahedronGeometry: TetrahedronGeometry,
  21807. TorusGeometry: TorusGeometry,
  21808. TorusKnotGeometry: TorusKnotGeometry,
  21809. TubeGeometry: TubeGeometry,
  21810. WireframeGeometry: WireframeGeometry
  21811. });
  21812. class ShadowMaterial extends Material {
  21813. constructor( parameters ) {
  21814. super();
  21815. this.isShadowMaterial = true;
  21816. this.type = 'ShadowMaterial';
  21817. this.color = new Color( 0x000000 );
  21818. this.transparent = true;
  21819. this.fog = true;
  21820. this.setValues( parameters );
  21821. }
  21822. copy( source ) {
  21823. super.copy( source );
  21824. this.color.copy( source.color );
  21825. this.fog = source.fog;
  21826. return this;
  21827. }
  21828. }
  21829. class RawShaderMaterial extends ShaderMaterial {
  21830. constructor( parameters ) {
  21831. super( parameters );
  21832. this.isRawShaderMaterial = true;
  21833. this.type = 'RawShaderMaterial';
  21834. }
  21835. }
  21836. class MeshStandardMaterial extends Material {
  21837. constructor( parameters ) {
  21838. super();
  21839. this.isMeshStandardMaterial = true;
  21840. this.defines = { 'STANDARD': '' };
  21841. this.type = 'MeshStandardMaterial';
  21842. this.color = new Color( 0xffffff ); // diffuse
  21843. this.roughness = 1.0;
  21844. this.metalness = 0.0;
  21845. this.map = null;
  21846. this.lightMap = null;
  21847. this.lightMapIntensity = 1.0;
  21848. this.aoMap = null;
  21849. this.aoMapIntensity = 1.0;
  21850. this.emissive = new Color( 0x000000 );
  21851. this.emissiveIntensity = 1.0;
  21852. this.emissiveMap = null;
  21853. this.bumpMap = null;
  21854. this.bumpScale = 1;
  21855. this.normalMap = null;
  21856. this.normalMapType = TangentSpaceNormalMap;
  21857. this.normalScale = new Vector2( 1, 1 );
  21858. this.displacementMap = null;
  21859. this.displacementScale = 1;
  21860. this.displacementBias = 0;
  21861. this.roughnessMap = null;
  21862. this.metalnessMap = null;
  21863. this.alphaMap = null;
  21864. this.envMap = null;
  21865. this.envMapIntensity = 1.0;
  21866. this.wireframe = false;
  21867. this.wireframeLinewidth = 1;
  21868. this.wireframeLinecap = 'round';
  21869. this.wireframeLinejoin = 'round';
  21870. this.flatShading = false;
  21871. this.fog = true;
  21872. this.setValues( parameters );
  21873. }
  21874. copy( source ) {
  21875. super.copy( source );
  21876. this.defines = { 'STANDARD': '' };
  21877. this.color.copy( source.color );
  21878. this.roughness = source.roughness;
  21879. this.metalness = source.metalness;
  21880. this.map = source.map;
  21881. this.lightMap = source.lightMap;
  21882. this.lightMapIntensity = source.lightMapIntensity;
  21883. this.aoMap = source.aoMap;
  21884. this.aoMapIntensity = source.aoMapIntensity;
  21885. this.emissive.copy( source.emissive );
  21886. this.emissiveMap = source.emissiveMap;
  21887. this.emissiveIntensity = source.emissiveIntensity;
  21888. this.bumpMap = source.bumpMap;
  21889. this.bumpScale = source.bumpScale;
  21890. this.normalMap = source.normalMap;
  21891. this.normalMapType = source.normalMapType;
  21892. this.normalScale.copy( source.normalScale );
  21893. this.displacementMap = source.displacementMap;
  21894. this.displacementScale = source.displacementScale;
  21895. this.displacementBias = source.displacementBias;
  21896. this.roughnessMap = source.roughnessMap;
  21897. this.metalnessMap = source.metalnessMap;
  21898. this.alphaMap = source.alphaMap;
  21899. this.envMap = source.envMap;
  21900. this.envMapIntensity = source.envMapIntensity;
  21901. this.wireframe = source.wireframe;
  21902. this.wireframeLinewidth = source.wireframeLinewidth;
  21903. this.wireframeLinecap = source.wireframeLinecap;
  21904. this.wireframeLinejoin = source.wireframeLinejoin;
  21905. this.flatShading = source.flatShading;
  21906. this.fog = source.fog;
  21907. return this;
  21908. }
  21909. }
  21910. class MeshPhysicalMaterial extends MeshStandardMaterial {
  21911. constructor( parameters ) {
  21912. super();
  21913. this.isMeshPhysicalMaterial = true;
  21914. this.defines = {
  21915. 'STANDARD': '',
  21916. 'PHYSICAL': ''
  21917. };
  21918. this.type = 'MeshPhysicalMaterial';
  21919. this.clearcoatMap = null;
  21920. this.clearcoatRoughness = 0.0;
  21921. this.clearcoatRoughnessMap = null;
  21922. this.clearcoatNormalScale = new Vector2( 1, 1 );
  21923. this.clearcoatNormalMap = null;
  21924. this.ior = 1.5;
  21925. Object.defineProperty( this, 'reflectivity', {
  21926. get: function () {
  21927. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  21928. },
  21929. set: function ( reflectivity ) {
  21930. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  21931. }
  21932. } );
  21933. this.iridescenceMap = null;
  21934. this.iridescenceIOR = 1.3;
  21935. this.iridescenceThicknessRange = [ 100, 400 ];
  21936. this.iridescenceThicknessMap = null;
  21937. this.sheenColor = new Color( 0x000000 );
  21938. this.sheenColorMap = null;
  21939. this.sheenRoughness = 1.0;
  21940. this.sheenRoughnessMap = null;
  21941. this.transmissionMap = null;
  21942. this.thickness = 0;
  21943. this.thicknessMap = null;
  21944. this.attenuationDistance = 0.0;
  21945. this.attenuationColor = new Color( 1, 1, 1 );
  21946. this.specularIntensity = 1.0;
  21947. this.specularIntensityMap = null;
  21948. this.specularColor = new Color( 1, 1, 1 );
  21949. this.specularColorMap = null;
  21950. this._sheen = 0.0;
  21951. this._clearcoat = 0;
  21952. this._iridescence = 0;
  21953. this._transmission = 0;
  21954. this.setValues( parameters );
  21955. }
  21956. get sheen() {
  21957. return this._sheen;
  21958. }
  21959. set sheen( value ) {
  21960. if ( this._sheen > 0 !== value > 0 ) {
  21961. this.version ++;
  21962. }
  21963. this._sheen = value;
  21964. }
  21965. get clearcoat() {
  21966. return this._clearcoat;
  21967. }
  21968. set clearcoat( value ) {
  21969. if ( this._clearcoat > 0 !== value > 0 ) {
  21970. this.version ++;
  21971. }
  21972. this._clearcoat = value;
  21973. }
  21974. get iridescence() {
  21975. return this._iridescence;
  21976. }
  21977. set iridescence( value ) {
  21978. if ( this._iridescence > 0 !== value > 0 ) {
  21979. this.version ++;
  21980. }
  21981. this._iridescence = value;
  21982. }
  21983. get transmission() {
  21984. return this._transmission;
  21985. }
  21986. set transmission( value ) {
  21987. if ( this._transmission > 0 !== value > 0 ) {
  21988. this.version ++;
  21989. }
  21990. this._transmission = value;
  21991. }
  21992. copy( source ) {
  21993. super.copy( source );
  21994. this.defines = {
  21995. 'STANDARD': '',
  21996. 'PHYSICAL': ''
  21997. };
  21998. this.clearcoat = source.clearcoat;
  21999. this.clearcoatMap = source.clearcoatMap;
  22000. this.clearcoatRoughness = source.clearcoatRoughness;
  22001. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  22002. this.clearcoatNormalMap = source.clearcoatNormalMap;
  22003. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  22004. this.ior = source.ior;
  22005. this.iridescence = source.iridescence;
  22006. this.iridescenceMap = source.iridescenceMap;
  22007. this.iridescenceIOR = source.iridescenceIOR;
  22008. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  22009. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  22010. this.sheen = source.sheen;
  22011. this.sheenColor.copy( source.sheenColor );
  22012. this.sheenColorMap = source.sheenColorMap;
  22013. this.sheenRoughness = source.sheenRoughness;
  22014. this.sheenRoughnessMap = source.sheenRoughnessMap;
  22015. this.transmission = source.transmission;
  22016. this.transmissionMap = source.transmissionMap;
  22017. this.thickness = source.thickness;
  22018. this.thicknessMap = source.thicknessMap;
  22019. this.attenuationDistance = source.attenuationDistance;
  22020. this.attenuationColor.copy( source.attenuationColor );
  22021. this.specularIntensity = source.specularIntensity;
  22022. this.specularIntensityMap = source.specularIntensityMap;
  22023. this.specularColor.copy( source.specularColor );
  22024. this.specularColorMap = source.specularColorMap;
  22025. return this;
  22026. }
  22027. }
  22028. class MeshPhongMaterial extends Material {
  22029. constructor( parameters ) {
  22030. super();
  22031. this.isMeshPhongMaterial = true;
  22032. this.type = 'MeshPhongMaterial';
  22033. this.color = new Color( 0xffffff ); // diffuse
  22034. this.specular = new Color( 0x111111 );
  22035. this.shininess = 30;
  22036. this.map = null;
  22037. this.lightMap = null;
  22038. this.lightMapIntensity = 1.0;
  22039. this.aoMap = null;
  22040. this.aoMapIntensity = 1.0;
  22041. this.emissive = new Color( 0x000000 );
  22042. this.emissiveIntensity = 1.0;
  22043. this.emissiveMap = null;
  22044. this.bumpMap = null;
  22045. this.bumpScale = 1;
  22046. this.normalMap = null;
  22047. this.normalMapType = TangentSpaceNormalMap;
  22048. this.normalScale = new Vector2( 1, 1 );
  22049. this.displacementMap = null;
  22050. this.displacementScale = 1;
  22051. this.displacementBias = 0;
  22052. this.specularMap = null;
  22053. this.alphaMap = null;
  22054. this.envMap = null;
  22055. this.combine = MultiplyOperation;
  22056. this.reflectivity = 1;
  22057. this.refractionRatio = 0.98;
  22058. this.wireframe = false;
  22059. this.wireframeLinewidth = 1;
  22060. this.wireframeLinecap = 'round';
  22061. this.wireframeLinejoin = 'round';
  22062. this.flatShading = false;
  22063. this.fog = true;
  22064. this.setValues( parameters );
  22065. }
  22066. copy( source ) {
  22067. super.copy( source );
  22068. this.color.copy( source.color );
  22069. this.specular.copy( source.specular );
  22070. this.shininess = source.shininess;
  22071. this.map = source.map;
  22072. this.lightMap = source.lightMap;
  22073. this.lightMapIntensity = source.lightMapIntensity;
  22074. this.aoMap = source.aoMap;
  22075. this.aoMapIntensity = source.aoMapIntensity;
  22076. this.emissive.copy( source.emissive );
  22077. this.emissiveMap = source.emissiveMap;
  22078. this.emissiveIntensity = source.emissiveIntensity;
  22079. this.bumpMap = source.bumpMap;
  22080. this.bumpScale = source.bumpScale;
  22081. this.normalMap = source.normalMap;
  22082. this.normalMapType = source.normalMapType;
  22083. this.normalScale.copy( source.normalScale );
  22084. this.displacementMap = source.displacementMap;
  22085. this.displacementScale = source.displacementScale;
  22086. this.displacementBias = source.displacementBias;
  22087. this.specularMap = source.specularMap;
  22088. this.alphaMap = source.alphaMap;
  22089. this.envMap = source.envMap;
  22090. this.combine = source.combine;
  22091. this.reflectivity = source.reflectivity;
  22092. this.refractionRatio = source.refractionRatio;
  22093. this.wireframe = source.wireframe;
  22094. this.wireframeLinewidth = source.wireframeLinewidth;
  22095. this.wireframeLinecap = source.wireframeLinecap;
  22096. this.wireframeLinejoin = source.wireframeLinejoin;
  22097. this.flatShading = source.flatShading;
  22098. this.fog = source.fog;
  22099. return this;
  22100. }
  22101. }
  22102. class MeshToonMaterial extends Material {
  22103. constructor( parameters ) {
  22104. super();
  22105. this.isMeshToonMaterial = true;
  22106. this.defines = { 'TOON': '' };
  22107. this.type = 'MeshToonMaterial';
  22108. this.color = new Color( 0xffffff );
  22109. this.map = null;
  22110. this.gradientMap = null;
  22111. this.lightMap = null;
  22112. this.lightMapIntensity = 1.0;
  22113. this.aoMap = null;
  22114. this.aoMapIntensity = 1.0;
  22115. this.emissive = new Color( 0x000000 );
  22116. this.emissiveIntensity = 1.0;
  22117. this.emissiveMap = null;
  22118. this.bumpMap = null;
  22119. this.bumpScale = 1;
  22120. this.normalMap = null;
  22121. this.normalMapType = TangentSpaceNormalMap;
  22122. this.normalScale = new Vector2( 1, 1 );
  22123. this.displacementMap = null;
  22124. this.displacementScale = 1;
  22125. this.displacementBias = 0;
  22126. this.alphaMap = null;
  22127. this.wireframe = false;
  22128. this.wireframeLinewidth = 1;
  22129. this.wireframeLinecap = 'round';
  22130. this.wireframeLinejoin = 'round';
  22131. this.fog = true;
  22132. this.setValues( parameters );
  22133. }
  22134. copy( source ) {
  22135. super.copy( source );
  22136. this.color.copy( source.color );
  22137. this.map = source.map;
  22138. this.gradientMap = source.gradientMap;
  22139. this.lightMap = source.lightMap;
  22140. this.lightMapIntensity = source.lightMapIntensity;
  22141. this.aoMap = source.aoMap;
  22142. this.aoMapIntensity = source.aoMapIntensity;
  22143. this.emissive.copy( source.emissive );
  22144. this.emissiveMap = source.emissiveMap;
  22145. this.emissiveIntensity = source.emissiveIntensity;
  22146. this.bumpMap = source.bumpMap;
  22147. this.bumpScale = source.bumpScale;
  22148. this.normalMap = source.normalMap;
  22149. this.normalMapType = source.normalMapType;
  22150. this.normalScale.copy( source.normalScale );
  22151. this.displacementMap = source.displacementMap;
  22152. this.displacementScale = source.displacementScale;
  22153. this.displacementBias = source.displacementBias;
  22154. this.alphaMap = source.alphaMap;
  22155. this.wireframe = source.wireframe;
  22156. this.wireframeLinewidth = source.wireframeLinewidth;
  22157. this.wireframeLinecap = source.wireframeLinecap;
  22158. this.wireframeLinejoin = source.wireframeLinejoin;
  22159. this.fog = source.fog;
  22160. return this;
  22161. }
  22162. }
  22163. class MeshNormalMaterial extends Material {
  22164. constructor( parameters ) {
  22165. super();
  22166. this.isMeshNormalMaterial = true;
  22167. this.type = 'MeshNormalMaterial';
  22168. this.bumpMap = null;
  22169. this.bumpScale = 1;
  22170. this.normalMap = null;
  22171. this.normalMapType = TangentSpaceNormalMap;
  22172. this.normalScale = new Vector2( 1, 1 );
  22173. this.displacementMap = null;
  22174. this.displacementScale = 1;
  22175. this.displacementBias = 0;
  22176. this.wireframe = false;
  22177. this.wireframeLinewidth = 1;
  22178. this.flatShading = false;
  22179. this.setValues( parameters );
  22180. }
  22181. copy( source ) {
  22182. super.copy( source );
  22183. this.bumpMap = source.bumpMap;
  22184. this.bumpScale = source.bumpScale;
  22185. this.normalMap = source.normalMap;
  22186. this.normalMapType = source.normalMapType;
  22187. this.normalScale.copy( source.normalScale );
  22188. this.displacementMap = source.displacementMap;
  22189. this.displacementScale = source.displacementScale;
  22190. this.displacementBias = source.displacementBias;
  22191. this.wireframe = source.wireframe;
  22192. this.wireframeLinewidth = source.wireframeLinewidth;
  22193. this.flatShading = source.flatShading;
  22194. return this;
  22195. }
  22196. }
  22197. class MeshLambertMaterial extends Material {
  22198. constructor( parameters ) {
  22199. super();
  22200. this.isMeshLambertMaterial = true;
  22201. this.type = 'MeshLambertMaterial';
  22202. this.color = new Color( 0xffffff ); // diffuse
  22203. this.map = null;
  22204. this.lightMap = null;
  22205. this.lightMapIntensity = 1.0;
  22206. this.aoMap = null;
  22207. this.aoMapIntensity = 1.0;
  22208. this.emissive = new Color( 0x000000 );
  22209. this.emissiveIntensity = 1.0;
  22210. this.emissiveMap = null;
  22211. this.bumpMap = null;
  22212. this.bumpScale = 1;
  22213. this.normalMap = null;
  22214. this.normalMapType = TangentSpaceNormalMap;
  22215. this.normalScale = new Vector2( 1, 1 );
  22216. this.displacementMap = null;
  22217. this.displacementScale = 1;
  22218. this.displacementBias = 0;
  22219. this.specularMap = null;
  22220. this.alphaMap = null;
  22221. this.envMap = null;
  22222. this.combine = MultiplyOperation;
  22223. this.reflectivity = 1;
  22224. this.refractionRatio = 0.98;
  22225. this.wireframe = false;
  22226. this.wireframeLinewidth = 1;
  22227. this.wireframeLinecap = 'round';
  22228. this.wireframeLinejoin = 'round';
  22229. this.flatShading = false;
  22230. this.fog = true;
  22231. this.setValues( parameters );
  22232. }
  22233. copy( source ) {
  22234. super.copy( source );
  22235. this.color.copy( source.color );
  22236. this.map = source.map;
  22237. this.lightMap = source.lightMap;
  22238. this.lightMapIntensity = source.lightMapIntensity;
  22239. this.aoMap = source.aoMap;
  22240. this.aoMapIntensity = source.aoMapIntensity;
  22241. this.emissive.copy( source.emissive );
  22242. this.emissiveMap = source.emissiveMap;
  22243. this.emissiveIntensity = source.emissiveIntensity;
  22244. this.bumpMap = source.bumpMap;
  22245. this.bumpScale = source.bumpScale;
  22246. this.normalMap = source.normalMap;
  22247. this.normalMapType = source.normalMapType;
  22248. this.normalScale.copy( source.normalScale );
  22249. this.displacementMap = source.displacementMap;
  22250. this.displacementScale = source.displacementScale;
  22251. this.displacementBias = source.displacementBias;
  22252. this.specularMap = source.specularMap;
  22253. this.alphaMap = source.alphaMap;
  22254. this.envMap = source.envMap;
  22255. this.combine = source.combine;
  22256. this.reflectivity = source.reflectivity;
  22257. this.refractionRatio = source.refractionRatio;
  22258. this.wireframe = source.wireframe;
  22259. this.wireframeLinewidth = source.wireframeLinewidth;
  22260. this.wireframeLinecap = source.wireframeLinecap;
  22261. this.wireframeLinejoin = source.wireframeLinejoin;
  22262. this.flatShading = source.flatShading;
  22263. this.fog = source.fog;
  22264. return this;
  22265. }
  22266. }
  22267. class MeshMatcapMaterial extends Material {
  22268. constructor( parameters ) {
  22269. super();
  22270. this.isMeshMatcapMaterial = true;
  22271. this.defines = { 'MATCAP': '' };
  22272. this.type = 'MeshMatcapMaterial';
  22273. this.color = new Color( 0xffffff ); // diffuse
  22274. this.matcap = null;
  22275. this.map = null;
  22276. this.bumpMap = null;
  22277. this.bumpScale = 1;
  22278. this.normalMap = null;
  22279. this.normalMapType = TangentSpaceNormalMap;
  22280. this.normalScale = new Vector2( 1, 1 );
  22281. this.displacementMap = null;
  22282. this.displacementScale = 1;
  22283. this.displacementBias = 0;
  22284. this.alphaMap = null;
  22285. this.flatShading = false;
  22286. this.fog = true;
  22287. this.setValues( parameters );
  22288. }
  22289. copy( source ) {
  22290. super.copy( source );
  22291. this.defines = { 'MATCAP': '' };
  22292. this.color.copy( source.color );
  22293. this.matcap = source.matcap;
  22294. this.map = source.map;
  22295. this.bumpMap = source.bumpMap;
  22296. this.bumpScale = source.bumpScale;
  22297. this.normalMap = source.normalMap;
  22298. this.normalMapType = source.normalMapType;
  22299. this.normalScale.copy( source.normalScale );
  22300. this.displacementMap = source.displacementMap;
  22301. this.displacementScale = source.displacementScale;
  22302. this.displacementBias = source.displacementBias;
  22303. this.alphaMap = source.alphaMap;
  22304. this.flatShading = source.flatShading;
  22305. this.fog = source.fog;
  22306. return this;
  22307. }
  22308. }
  22309. class LineDashedMaterial extends LineBasicMaterial {
  22310. constructor( parameters ) {
  22311. super();
  22312. this.isLineDashedMaterial = true;
  22313. this.type = 'LineDashedMaterial';
  22314. this.scale = 1;
  22315. this.dashSize = 3;
  22316. this.gapSize = 1;
  22317. this.setValues( parameters );
  22318. }
  22319. copy( source ) {
  22320. super.copy( source );
  22321. this.scale = source.scale;
  22322. this.dashSize = source.dashSize;
  22323. this.gapSize = source.gapSize;
  22324. return this;
  22325. }
  22326. }
  22327. // same as Array.prototype.slice, but also works on typed arrays
  22328. function arraySlice( array, from, to ) {
  22329. if ( isTypedArray( array ) ) {
  22330. // in ios9 array.subarray(from, undefined) will return empty array
  22331. // but array.subarray(from) or array.subarray(from, len) is correct
  22332. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  22333. }
  22334. return array.slice( from, to );
  22335. }
  22336. // converts an array to a specific type
  22337. function convertArray( array, type, forceClone ) {
  22338. if ( ! array || // let 'undefined' and 'null' pass
  22339. ! forceClone && array.constructor === type ) return array;
  22340. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  22341. return new type( array ); // create typed array
  22342. }
  22343. return Array.prototype.slice.call( array ); // create Array
  22344. }
  22345. function isTypedArray( object ) {
  22346. return ArrayBuffer.isView( object ) &&
  22347. ! ( object instanceof DataView );
  22348. }
  22349. // returns an array by which times and values can be sorted
  22350. function getKeyframeOrder( times ) {
  22351. function compareTime( i, j ) {
  22352. return times[ i ] - times[ j ];
  22353. }
  22354. const n = times.length;
  22355. const result = new Array( n );
  22356. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  22357. result.sort( compareTime );
  22358. return result;
  22359. }
  22360. // uses the array previously returned by 'getKeyframeOrder' to sort data
  22361. function sortedArray( values, stride, order ) {
  22362. const nValues = values.length;
  22363. const result = new values.constructor( nValues );
  22364. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  22365. const srcOffset = order[ i ] * stride;
  22366. for ( let j = 0; j !== stride; ++ j ) {
  22367. result[ dstOffset ++ ] = values[ srcOffset + j ];
  22368. }
  22369. }
  22370. return result;
  22371. }
  22372. // function for parsing AOS keyframe formats
  22373. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  22374. let i = 1, key = jsonKeys[ 0 ];
  22375. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  22376. key = jsonKeys[ i ++ ];
  22377. }
  22378. if ( key === undefined ) return; // no data
  22379. let value = key[ valuePropertyName ];
  22380. if ( value === undefined ) return; // no data
  22381. if ( Array.isArray( value ) ) {
  22382. do {
  22383. value = key[ valuePropertyName ];
  22384. if ( value !== undefined ) {
  22385. times.push( key.time );
  22386. values.push.apply( values, value ); // push all elements
  22387. }
  22388. key = jsonKeys[ i ++ ];
  22389. } while ( key !== undefined );
  22390. } else if ( value.toArray !== undefined ) {
  22391. // ...assume THREE.Math-ish
  22392. do {
  22393. value = key[ valuePropertyName ];
  22394. if ( value !== undefined ) {
  22395. times.push( key.time );
  22396. value.toArray( values, values.length );
  22397. }
  22398. key = jsonKeys[ i ++ ];
  22399. } while ( key !== undefined );
  22400. } else {
  22401. // otherwise push as-is
  22402. do {
  22403. value = key[ valuePropertyName ];
  22404. if ( value !== undefined ) {
  22405. times.push( key.time );
  22406. values.push( value );
  22407. }
  22408. key = jsonKeys[ i ++ ];
  22409. } while ( key !== undefined );
  22410. }
  22411. }
  22412. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  22413. const clip = sourceClip.clone();
  22414. clip.name = name;
  22415. const tracks = [];
  22416. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22417. const track = clip.tracks[ i ];
  22418. const valueSize = track.getValueSize();
  22419. const times = [];
  22420. const values = [];
  22421. for ( let j = 0; j < track.times.length; ++ j ) {
  22422. const frame = track.times[ j ] * fps;
  22423. if ( frame < startFrame || frame >= endFrame ) continue;
  22424. times.push( track.times[ j ] );
  22425. for ( let k = 0; k < valueSize; ++ k ) {
  22426. values.push( track.values[ j * valueSize + k ] );
  22427. }
  22428. }
  22429. if ( times.length === 0 ) continue;
  22430. track.times = convertArray( times, track.times.constructor );
  22431. track.values = convertArray( values, track.values.constructor );
  22432. tracks.push( track );
  22433. }
  22434. clip.tracks = tracks;
  22435. // find minimum .times value across all tracks in the trimmed clip
  22436. let minStartTime = Infinity;
  22437. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22438. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  22439. minStartTime = clip.tracks[ i ].times[ 0 ];
  22440. }
  22441. }
  22442. // shift all tracks such that clip begins at t=0
  22443. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  22444. clip.tracks[ i ].shift( - 1 * minStartTime );
  22445. }
  22446. clip.resetDuration();
  22447. return clip;
  22448. }
  22449. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  22450. if ( fps <= 0 ) fps = 30;
  22451. const numTracks = referenceClip.tracks.length;
  22452. const referenceTime = referenceFrame / fps;
  22453. // Make each track's values relative to the values at the reference frame
  22454. for ( let i = 0; i < numTracks; ++ i ) {
  22455. const referenceTrack = referenceClip.tracks[ i ];
  22456. const referenceTrackType = referenceTrack.ValueTypeName;
  22457. // Skip this track if it's non-numeric
  22458. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  22459. // Find the track in the target clip whose name and type matches the reference track
  22460. const targetTrack = targetClip.tracks.find( function ( track ) {
  22461. return track.name === referenceTrack.name
  22462. && track.ValueTypeName === referenceTrackType;
  22463. } );
  22464. if ( targetTrack === undefined ) continue;
  22465. let referenceOffset = 0;
  22466. const referenceValueSize = referenceTrack.getValueSize();
  22467. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  22468. referenceOffset = referenceValueSize / 3;
  22469. }
  22470. let targetOffset = 0;
  22471. const targetValueSize = targetTrack.getValueSize();
  22472. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  22473. targetOffset = targetValueSize / 3;
  22474. }
  22475. const lastIndex = referenceTrack.times.length - 1;
  22476. let referenceValue;
  22477. // Find the value to subtract out of the track
  22478. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  22479. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  22480. const startIndex = referenceOffset;
  22481. const endIndex = referenceValueSize - referenceOffset;
  22482. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  22483. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  22484. // Reference frame is after the last keyframe, so just use the last keyframe
  22485. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  22486. const endIndex = startIndex + referenceValueSize - referenceOffset;
  22487. referenceValue = arraySlice( referenceTrack.values, startIndex, endIndex );
  22488. } else {
  22489. // Interpolate to the reference value
  22490. const interpolant = referenceTrack.createInterpolant();
  22491. const startIndex = referenceOffset;
  22492. const endIndex = referenceValueSize - referenceOffset;
  22493. interpolant.evaluate( referenceTime );
  22494. referenceValue = arraySlice( interpolant.resultBuffer, startIndex, endIndex );
  22495. }
  22496. // Conjugate the quaternion
  22497. if ( referenceTrackType === 'quaternion' ) {
  22498. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  22499. referenceQuat.toArray( referenceValue );
  22500. }
  22501. // Subtract the reference value from all of the track values
  22502. const numTimes = targetTrack.times.length;
  22503. for ( let j = 0; j < numTimes; ++ j ) {
  22504. const valueStart = j * targetValueSize + targetOffset;
  22505. if ( referenceTrackType === 'quaternion' ) {
  22506. // Multiply the conjugate for quaternion track types
  22507. Quaternion.multiplyQuaternionsFlat(
  22508. targetTrack.values,
  22509. valueStart,
  22510. referenceValue,
  22511. 0,
  22512. targetTrack.values,
  22513. valueStart
  22514. );
  22515. } else {
  22516. const valueEnd = targetValueSize - targetOffset * 2;
  22517. // Subtract each value for all other numeric track types
  22518. for ( let k = 0; k < valueEnd; ++ k ) {
  22519. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  22520. }
  22521. }
  22522. }
  22523. }
  22524. targetClip.blendMode = AdditiveAnimationBlendMode;
  22525. return targetClip;
  22526. }
  22527. var AnimationUtils = /*#__PURE__*/Object.freeze({
  22528. __proto__: null,
  22529. arraySlice: arraySlice,
  22530. convertArray: convertArray,
  22531. isTypedArray: isTypedArray,
  22532. getKeyframeOrder: getKeyframeOrder,
  22533. sortedArray: sortedArray,
  22534. flattenJSON: flattenJSON,
  22535. subclip: subclip,
  22536. makeClipAdditive: makeClipAdditive
  22537. });
  22538. /**
  22539. * Abstract base class of interpolants over parametric samples.
  22540. *
  22541. * The parameter domain is one dimensional, typically the time or a path
  22542. * along a curve defined by the data.
  22543. *
  22544. * The sample values can have any dimensionality and derived classes may
  22545. * apply special interpretations to the data.
  22546. *
  22547. * This class provides the interval seek in a Template Method, deferring
  22548. * the actual interpolation to derived classes.
  22549. *
  22550. * Time complexity is O(1) for linear access crossing at most two points
  22551. * and O(log N) for random access, where N is the number of positions.
  22552. *
  22553. * References:
  22554. *
  22555. * http://www.oodesign.com/template-method-pattern.html
  22556. *
  22557. */
  22558. class Interpolant {
  22559. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22560. this.parameterPositions = parameterPositions;
  22561. this._cachedIndex = 0;
  22562. this.resultBuffer = resultBuffer !== undefined ?
  22563. resultBuffer : new sampleValues.constructor( sampleSize );
  22564. this.sampleValues = sampleValues;
  22565. this.valueSize = sampleSize;
  22566. this.settings = null;
  22567. this.DefaultSettings_ = {};
  22568. }
  22569. evaluate( t ) {
  22570. const pp = this.parameterPositions;
  22571. let i1 = this._cachedIndex,
  22572. t1 = pp[ i1 ],
  22573. t0 = pp[ i1 - 1 ];
  22574. validate_interval: {
  22575. seek: {
  22576. let right;
  22577. linear_scan: {
  22578. //- See http://jsperf.com/comparison-to-undefined/3
  22579. //- slower code:
  22580. //-
  22581. //- if ( t >= t1 || t1 === undefined ) {
  22582. forward_scan: if ( ! ( t < t1 ) ) {
  22583. for ( let giveUpAt = i1 + 2; ; ) {
  22584. if ( t1 === undefined ) {
  22585. if ( t < t0 ) break forward_scan;
  22586. // after end
  22587. i1 = pp.length;
  22588. this._cachedIndex = i1;
  22589. return this.copySampleValue_( i1 - 1 );
  22590. }
  22591. if ( i1 === giveUpAt ) break; // this loop
  22592. t0 = t1;
  22593. t1 = pp[ ++ i1 ];
  22594. if ( t < t1 ) {
  22595. // we have arrived at the sought interval
  22596. break seek;
  22597. }
  22598. }
  22599. // prepare binary search on the right side of the index
  22600. right = pp.length;
  22601. break linear_scan;
  22602. }
  22603. //- slower code:
  22604. //- if ( t < t0 || t0 === undefined ) {
  22605. if ( ! ( t >= t0 ) ) {
  22606. // looping?
  22607. const t1global = pp[ 1 ];
  22608. if ( t < t1global ) {
  22609. i1 = 2; // + 1, using the scan for the details
  22610. t0 = t1global;
  22611. }
  22612. // linear reverse scan
  22613. for ( let giveUpAt = i1 - 2; ; ) {
  22614. if ( t0 === undefined ) {
  22615. // before start
  22616. this._cachedIndex = 0;
  22617. return this.copySampleValue_( 0 );
  22618. }
  22619. if ( i1 === giveUpAt ) break; // this loop
  22620. t1 = t0;
  22621. t0 = pp[ -- i1 - 1 ];
  22622. if ( t >= t0 ) {
  22623. // we have arrived at the sought interval
  22624. break seek;
  22625. }
  22626. }
  22627. // prepare binary search on the left side of the index
  22628. right = i1;
  22629. i1 = 0;
  22630. break linear_scan;
  22631. }
  22632. // the interval is valid
  22633. break validate_interval;
  22634. } // linear scan
  22635. // binary search
  22636. while ( i1 < right ) {
  22637. const mid = ( i1 + right ) >>> 1;
  22638. if ( t < pp[ mid ] ) {
  22639. right = mid;
  22640. } else {
  22641. i1 = mid + 1;
  22642. }
  22643. }
  22644. t1 = pp[ i1 ];
  22645. t0 = pp[ i1 - 1 ];
  22646. // check boundary cases, again
  22647. if ( t0 === undefined ) {
  22648. this._cachedIndex = 0;
  22649. return this.copySampleValue_( 0 );
  22650. }
  22651. if ( t1 === undefined ) {
  22652. i1 = pp.length;
  22653. this._cachedIndex = i1;
  22654. return this.copySampleValue_( i1 - 1 );
  22655. }
  22656. } // seek
  22657. this._cachedIndex = i1;
  22658. this.intervalChanged_( i1, t0, t1 );
  22659. } // validate_interval
  22660. return this.interpolate_( i1, t0, t, t1 );
  22661. }
  22662. getSettings_() {
  22663. return this.settings || this.DefaultSettings_;
  22664. }
  22665. copySampleValue_( index ) {
  22666. // copies a sample value to the result buffer
  22667. const result = this.resultBuffer,
  22668. values = this.sampleValues,
  22669. stride = this.valueSize,
  22670. offset = index * stride;
  22671. for ( let i = 0; i !== stride; ++ i ) {
  22672. result[ i ] = values[ offset + i ];
  22673. }
  22674. return result;
  22675. }
  22676. // Template methods for derived classes:
  22677. interpolate_( /* i1, t0, t, t1 */ ) {
  22678. throw new Error( 'call to abstract method' );
  22679. // implementations shall return this.resultBuffer
  22680. }
  22681. intervalChanged_( /* i1, t0, t1 */ ) {
  22682. // empty
  22683. }
  22684. }
  22685. /**
  22686. * Fast and simple cubic spline interpolant.
  22687. *
  22688. * It was derived from a Hermitian construction setting the first derivative
  22689. * at each sample position to the linear slope between neighboring positions
  22690. * over their parameter interval.
  22691. */
  22692. class CubicInterpolant extends Interpolant {
  22693. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22694. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  22695. this._weightPrev = - 0;
  22696. this._offsetPrev = - 0;
  22697. this._weightNext = - 0;
  22698. this._offsetNext = - 0;
  22699. this.DefaultSettings_ = {
  22700. endingStart: ZeroCurvatureEnding,
  22701. endingEnd: ZeroCurvatureEnding
  22702. };
  22703. }
  22704. intervalChanged_( i1, t0, t1 ) {
  22705. const pp = this.parameterPositions;
  22706. let iPrev = i1 - 2,
  22707. iNext = i1 + 1,
  22708. tPrev = pp[ iPrev ],
  22709. tNext = pp[ iNext ];
  22710. if ( tPrev === undefined ) {
  22711. switch ( this.getSettings_().endingStart ) {
  22712. case ZeroSlopeEnding:
  22713. // f'(t0) = 0
  22714. iPrev = i1;
  22715. tPrev = 2 * t0 - t1;
  22716. break;
  22717. case WrapAroundEnding:
  22718. // use the other end of the curve
  22719. iPrev = pp.length - 2;
  22720. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  22721. break;
  22722. default: // ZeroCurvatureEnding
  22723. // f''(t0) = 0 a.k.a. Natural Spline
  22724. iPrev = i1;
  22725. tPrev = t1;
  22726. }
  22727. }
  22728. if ( tNext === undefined ) {
  22729. switch ( this.getSettings_().endingEnd ) {
  22730. case ZeroSlopeEnding:
  22731. // f'(tN) = 0
  22732. iNext = i1;
  22733. tNext = 2 * t1 - t0;
  22734. break;
  22735. case WrapAroundEnding:
  22736. // use the other end of the curve
  22737. iNext = 1;
  22738. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  22739. break;
  22740. default: // ZeroCurvatureEnding
  22741. // f''(tN) = 0, a.k.a. Natural Spline
  22742. iNext = i1 - 1;
  22743. tNext = t0;
  22744. }
  22745. }
  22746. const halfDt = ( t1 - t0 ) * 0.5,
  22747. stride = this.valueSize;
  22748. this._weightPrev = halfDt / ( t0 - tPrev );
  22749. this._weightNext = halfDt / ( tNext - t1 );
  22750. this._offsetPrev = iPrev * stride;
  22751. this._offsetNext = iNext * stride;
  22752. }
  22753. interpolate_( i1, t0, t, t1 ) {
  22754. const result = this.resultBuffer,
  22755. values = this.sampleValues,
  22756. stride = this.valueSize,
  22757. o1 = i1 * stride, o0 = o1 - stride,
  22758. oP = this._offsetPrev, oN = this._offsetNext,
  22759. wP = this._weightPrev, wN = this._weightNext,
  22760. p = ( t - t0 ) / ( t1 - t0 ),
  22761. pp = p * p,
  22762. ppp = pp * p;
  22763. // evaluate polynomials
  22764. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  22765. const s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  22766. const s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  22767. const sN = wN * ppp - wN * pp;
  22768. // combine data linearly
  22769. for ( let i = 0; i !== stride; ++ i ) {
  22770. result[ i ] =
  22771. sP * values[ oP + i ] +
  22772. s0 * values[ o0 + i ] +
  22773. s1 * values[ o1 + i ] +
  22774. sN * values[ oN + i ];
  22775. }
  22776. return result;
  22777. }
  22778. }
  22779. class LinearInterpolant extends Interpolant {
  22780. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22781. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  22782. }
  22783. interpolate_( i1, t0, t, t1 ) {
  22784. const result = this.resultBuffer,
  22785. values = this.sampleValues,
  22786. stride = this.valueSize,
  22787. offset1 = i1 * stride,
  22788. offset0 = offset1 - stride,
  22789. weight1 = ( t - t0 ) / ( t1 - t0 ),
  22790. weight0 = 1 - weight1;
  22791. for ( let i = 0; i !== stride; ++ i ) {
  22792. result[ i ] =
  22793. values[ offset0 + i ] * weight0 +
  22794. values[ offset1 + i ] * weight1;
  22795. }
  22796. return result;
  22797. }
  22798. }
  22799. /**
  22800. *
  22801. * Interpolant that evaluates to the sample value at the position preceding
  22802. * the parameter.
  22803. */
  22804. class DiscreteInterpolant extends Interpolant {
  22805. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22806. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  22807. }
  22808. interpolate_( i1 /*, t0, t, t1 */ ) {
  22809. return this.copySampleValue_( i1 - 1 );
  22810. }
  22811. }
  22812. class KeyframeTrack {
  22813. constructor( name, times, values, interpolation ) {
  22814. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  22815. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  22816. this.name = name;
  22817. this.times = convertArray( times, this.TimeBufferType );
  22818. this.values = convertArray( values, this.ValueBufferType );
  22819. this.setInterpolation( interpolation || this.DefaultInterpolation );
  22820. }
  22821. // Serialization (in static context, because of constructor invocation
  22822. // and automatic invocation of .toJSON):
  22823. static toJSON( track ) {
  22824. const trackType = track.constructor;
  22825. let json;
  22826. // derived classes can define a static toJSON method
  22827. if ( trackType.toJSON !== this.toJSON ) {
  22828. json = trackType.toJSON( track );
  22829. } else {
  22830. // by default, we assume the data can be serialized as-is
  22831. json = {
  22832. 'name': track.name,
  22833. 'times': convertArray( track.times, Array ),
  22834. 'values': convertArray( track.values, Array )
  22835. };
  22836. const interpolation = track.getInterpolation();
  22837. if ( interpolation !== track.DefaultInterpolation ) {
  22838. json.interpolation = interpolation;
  22839. }
  22840. }
  22841. json.type = track.ValueTypeName; // mandatory
  22842. return json;
  22843. }
  22844. InterpolantFactoryMethodDiscrete( result ) {
  22845. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  22846. }
  22847. InterpolantFactoryMethodLinear( result ) {
  22848. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  22849. }
  22850. InterpolantFactoryMethodSmooth( result ) {
  22851. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  22852. }
  22853. setInterpolation( interpolation ) {
  22854. let factoryMethod;
  22855. switch ( interpolation ) {
  22856. case InterpolateDiscrete:
  22857. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  22858. break;
  22859. case InterpolateLinear:
  22860. factoryMethod = this.InterpolantFactoryMethodLinear;
  22861. break;
  22862. case InterpolateSmooth:
  22863. factoryMethod = this.InterpolantFactoryMethodSmooth;
  22864. break;
  22865. }
  22866. if ( factoryMethod === undefined ) {
  22867. const message = 'unsupported interpolation for ' +
  22868. this.ValueTypeName + ' keyframe track named ' + this.name;
  22869. if ( this.createInterpolant === undefined ) {
  22870. // fall back to default, unless the default itself is messed up
  22871. if ( interpolation !== this.DefaultInterpolation ) {
  22872. this.setInterpolation( this.DefaultInterpolation );
  22873. } else {
  22874. throw new Error( message ); // fatal, in this case
  22875. }
  22876. }
  22877. console.warn( 'THREE.KeyframeTrack:', message );
  22878. return this;
  22879. }
  22880. this.createInterpolant = factoryMethod;
  22881. return this;
  22882. }
  22883. getInterpolation() {
  22884. switch ( this.createInterpolant ) {
  22885. case this.InterpolantFactoryMethodDiscrete:
  22886. return InterpolateDiscrete;
  22887. case this.InterpolantFactoryMethodLinear:
  22888. return InterpolateLinear;
  22889. case this.InterpolantFactoryMethodSmooth:
  22890. return InterpolateSmooth;
  22891. }
  22892. }
  22893. getValueSize() {
  22894. return this.values.length / this.times.length;
  22895. }
  22896. // move all keyframes either forwards or backwards in time
  22897. shift( timeOffset ) {
  22898. if ( timeOffset !== 0.0 ) {
  22899. const times = this.times;
  22900. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  22901. times[ i ] += timeOffset;
  22902. }
  22903. }
  22904. return this;
  22905. }
  22906. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  22907. scale( timeScale ) {
  22908. if ( timeScale !== 1.0 ) {
  22909. const times = this.times;
  22910. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  22911. times[ i ] *= timeScale;
  22912. }
  22913. }
  22914. return this;
  22915. }
  22916. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  22917. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  22918. trim( startTime, endTime ) {
  22919. const times = this.times,
  22920. nKeys = times.length;
  22921. let from = 0,
  22922. to = nKeys - 1;
  22923. while ( from !== nKeys && times[ from ] < startTime ) {
  22924. ++ from;
  22925. }
  22926. while ( to !== - 1 && times[ to ] > endTime ) {
  22927. -- to;
  22928. }
  22929. ++ to; // inclusive -> exclusive bound
  22930. if ( from !== 0 || to !== nKeys ) {
  22931. // empty tracks are forbidden, so keep at least one keyframe
  22932. if ( from >= to ) {
  22933. to = Math.max( to, 1 );
  22934. from = to - 1;
  22935. }
  22936. const stride = this.getValueSize();
  22937. this.times = arraySlice( times, from, to );
  22938. this.values = arraySlice( this.values, from * stride, to * stride );
  22939. }
  22940. return this;
  22941. }
  22942. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  22943. validate() {
  22944. let valid = true;
  22945. const valueSize = this.getValueSize();
  22946. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  22947. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  22948. valid = false;
  22949. }
  22950. const times = this.times,
  22951. values = this.values,
  22952. nKeys = times.length;
  22953. if ( nKeys === 0 ) {
  22954. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  22955. valid = false;
  22956. }
  22957. let prevTime = null;
  22958. for ( let i = 0; i !== nKeys; i ++ ) {
  22959. const currTime = times[ i ];
  22960. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  22961. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  22962. valid = false;
  22963. break;
  22964. }
  22965. if ( prevTime !== null && prevTime > currTime ) {
  22966. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  22967. valid = false;
  22968. break;
  22969. }
  22970. prevTime = currTime;
  22971. }
  22972. if ( values !== undefined ) {
  22973. if ( isTypedArray( values ) ) {
  22974. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  22975. const value = values[ i ];
  22976. if ( isNaN( value ) ) {
  22977. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  22978. valid = false;
  22979. break;
  22980. }
  22981. }
  22982. }
  22983. }
  22984. return valid;
  22985. }
  22986. // removes equivalent sequential keys as common in morph target sequences
  22987. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  22988. optimize() {
  22989. // times or values may be shared with other tracks, so overwriting is unsafe
  22990. const times = arraySlice( this.times ),
  22991. values = arraySlice( this.values ),
  22992. stride = this.getValueSize(),
  22993. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  22994. lastIndex = times.length - 1;
  22995. let writeIndex = 1;
  22996. for ( let i = 1; i < lastIndex; ++ i ) {
  22997. let keep = false;
  22998. const time = times[ i ];
  22999. const timeNext = times[ i + 1 ];
  23000. // remove adjacent keyframes scheduled at the same time
  23001. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  23002. if ( ! smoothInterpolation ) {
  23003. // remove unnecessary keyframes same as their neighbors
  23004. const offset = i * stride,
  23005. offsetP = offset - stride,
  23006. offsetN = offset + stride;
  23007. for ( let j = 0; j !== stride; ++ j ) {
  23008. const value = values[ offset + j ];
  23009. if ( value !== values[ offsetP + j ] ||
  23010. value !== values[ offsetN + j ] ) {
  23011. keep = true;
  23012. break;
  23013. }
  23014. }
  23015. } else {
  23016. keep = true;
  23017. }
  23018. }
  23019. // in-place compaction
  23020. if ( keep ) {
  23021. if ( i !== writeIndex ) {
  23022. times[ writeIndex ] = times[ i ];
  23023. const readOffset = i * stride,
  23024. writeOffset = writeIndex * stride;
  23025. for ( let j = 0; j !== stride; ++ j ) {
  23026. values[ writeOffset + j ] = values[ readOffset + j ];
  23027. }
  23028. }
  23029. ++ writeIndex;
  23030. }
  23031. }
  23032. // flush last keyframe (compaction looks ahead)
  23033. if ( lastIndex > 0 ) {
  23034. times[ writeIndex ] = times[ lastIndex ];
  23035. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  23036. values[ writeOffset + j ] = values[ readOffset + j ];
  23037. }
  23038. ++ writeIndex;
  23039. }
  23040. if ( writeIndex !== times.length ) {
  23041. this.times = arraySlice( times, 0, writeIndex );
  23042. this.values = arraySlice( values, 0, writeIndex * stride );
  23043. } else {
  23044. this.times = times;
  23045. this.values = values;
  23046. }
  23047. return this;
  23048. }
  23049. clone() {
  23050. const times = arraySlice( this.times, 0 );
  23051. const values = arraySlice( this.values, 0 );
  23052. const TypedKeyframeTrack = this.constructor;
  23053. const track = new TypedKeyframeTrack( this.name, times, values );
  23054. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  23055. track.createInterpolant = this.createInterpolant;
  23056. return track;
  23057. }
  23058. }
  23059. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  23060. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  23061. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23062. /**
  23063. * A Track of Boolean keyframe values.
  23064. */
  23065. class BooleanKeyframeTrack extends KeyframeTrack {}
  23066. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  23067. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  23068. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23069. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23070. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23071. /**
  23072. * A Track of keyframe values that represent color.
  23073. */
  23074. class ColorKeyframeTrack extends KeyframeTrack {}
  23075. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  23076. /**
  23077. * A Track of numeric keyframe values.
  23078. */
  23079. class NumberKeyframeTrack extends KeyframeTrack {}
  23080. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  23081. /**
  23082. * Spherical linear unit quaternion interpolant.
  23083. */
  23084. class QuaternionLinearInterpolant extends Interpolant {
  23085. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  23086. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  23087. }
  23088. interpolate_( i1, t0, t, t1 ) {
  23089. const result = this.resultBuffer,
  23090. values = this.sampleValues,
  23091. stride = this.valueSize,
  23092. alpha = ( t - t0 ) / ( t1 - t0 );
  23093. let offset = i1 * stride;
  23094. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  23095. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  23096. }
  23097. return result;
  23098. }
  23099. }
  23100. /**
  23101. * A Track of quaternion keyframe values.
  23102. */
  23103. class QuaternionKeyframeTrack extends KeyframeTrack {
  23104. InterpolantFactoryMethodLinear( result ) {
  23105. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  23106. }
  23107. }
  23108. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  23109. // ValueBufferType is inherited
  23110. QuaternionKeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  23111. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23112. /**
  23113. * A Track that interpolates Strings
  23114. */
  23115. class StringKeyframeTrack extends KeyframeTrack {}
  23116. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  23117. StringKeyframeTrack.prototype.ValueBufferType = Array;
  23118. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  23119. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  23120. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  23121. /**
  23122. * A Track of vectored keyframe values.
  23123. */
  23124. class VectorKeyframeTrack extends KeyframeTrack {}
  23125. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  23126. class AnimationClip {
  23127. constructor( name, duration = - 1, tracks, blendMode = NormalAnimationBlendMode ) {
  23128. this.name = name;
  23129. this.tracks = tracks;
  23130. this.duration = duration;
  23131. this.blendMode = blendMode;
  23132. this.uuid = generateUUID();
  23133. // this means it should figure out its duration by scanning the tracks
  23134. if ( this.duration < 0 ) {
  23135. this.resetDuration();
  23136. }
  23137. }
  23138. static parse( json ) {
  23139. const tracks = [],
  23140. jsonTracks = json.tracks,
  23141. frameTime = 1.0 / ( json.fps || 1.0 );
  23142. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  23143. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  23144. }
  23145. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  23146. clip.uuid = json.uuid;
  23147. return clip;
  23148. }
  23149. static toJSON( clip ) {
  23150. const tracks = [],
  23151. clipTracks = clip.tracks;
  23152. const json = {
  23153. 'name': clip.name,
  23154. 'duration': clip.duration,
  23155. 'tracks': tracks,
  23156. 'uuid': clip.uuid,
  23157. 'blendMode': clip.blendMode
  23158. };
  23159. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  23160. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  23161. }
  23162. return json;
  23163. }
  23164. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  23165. const numMorphTargets = morphTargetSequence.length;
  23166. const tracks = [];
  23167. for ( let i = 0; i < numMorphTargets; i ++ ) {
  23168. let times = [];
  23169. let values = [];
  23170. times.push(
  23171. ( i + numMorphTargets - 1 ) % numMorphTargets,
  23172. i,
  23173. ( i + 1 ) % numMorphTargets );
  23174. values.push( 0, 1, 0 );
  23175. const order = getKeyframeOrder( times );
  23176. times = sortedArray( times, 1, order );
  23177. values = sortedArray( values, 1, order );
  23178. // if there is a key at the first frame, duplicate it as the
  23179. // last frame as well for perfect loop.
  23180. if ( ! noLoop && times[ 0 ] === 0 ) {
  23181. times.push( numMorphTargets );
  23182. values.push( values[ 0 ] );
  23183. }
  23184. tracks.push(
  23185. new NumberKeyframeTrack(
  23186. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  23187. times, values
  23188. ).scale( 1.0 / fps ) );
  23189. }
  23190. return new this( name, - 1, tracks );
  23191. }
  23192. static findByName( objectOrClipArray, name ) {
  23193. let clipArray = objectOrClipArray;
  23194. if ( ! Array.isArray( objectOrClipArray ) ) {
  23195. const o = objectOrClipArray;
  23196. clipArray = o.geometry && o.geometry.animations || o.animations;
  23197. }
  23198. for ( let i = 0; i < clipArray.length; i ++ ) {
  23199. if ( clipArray[ i ].name === name ) {
  23200. return clipArray[ i ];
  23201. }
  23202. }
  23203. return null;
  23204. }
  23205. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  23206. const animationToMorphTargets = {};
  23207. // tested with https://regex101.com/ on trick sequences
  23208. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  23209. const pattern = /^([\w-]*?)([\d]+)$/;
  23210. // sort morph target names into animation groups based
  23211. // patterns like Walk_001, Walk_002, Run_001, Run_002
  23212. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  23213. const morphTarget = morphTargets[ i ];
  23214. const parts = morphTarget.name.match( pattern );
  23215. if ( parts && parts.length > 1 ) {
  23216. const name = parts[ 1 ];
  23217. let animationMorphTargets = animationToMorphTargets[ name ];
  23218. if ( ! animationMorphTargets ) {
  23219. animationToMorphTargets[ name ] = animationMorphTargets = [];
  23220. }
  23221. animationMorphTargets.push( morphTarget );
  23222. }
  23223. }
  23224. const clips = [];
  23225. for ( const name in animationToMorphTargets ) {
  23226. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  23227. }
  23228. return clips;
  23229. }
  23230. // parse the animation.hierarchy format
  23231. static parseAnimation( animation, bones ) {
  23232. if ( ! animation ) {
  23233. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  23234. return null;
  23235. }
  23236. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  23237. // only return track if there are actually keys.
  23238. if ( animationKeys.length !== 0 ) {
  23239. const times = [];
  23240. const values = [];
  23241. flattenJSON( animationKeys, times, values, propertyName );
  23242. // empty keys are filtered out, so check again
  23243. if ( times.length !== 0 ) {
  23244. destTracks.push( new trackType( trackName, times, values ) );
  23245. }
  23246. }
  23247. };
  23248. const tracks = [];
  23249. const clipName = animation.name || 'default';
  23250. const fps = animation.fps || 30;
  23251. const blendMode = animation.blendMode;
  23252. // automatic length determination in AnimationClip.
  23253. let duration = animation.length || - 1;
  23254. const hierarchyTracks = animation.hierarchy || [];
  23255. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  23256. const animationKeys = hierarchyTracks[ h ].keys;
  23257. // skip empty tracks
  23258. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  23259. // process morph targets
  23260. if ( animationKeys[ 0 ].morphTargets ) {
  23261. // figure out all morph targets used in this track
  23262. const morphTargetNames = {};
  23263. let k;
  23264. for ( k = 0; k < animationKeys.length; k ++ ) {
  23265. if ( animationKeys[ k ].morphTargets ) {
  23266. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  23267. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  23268. }
  23269. }
  23270. }
  23271. // create a track for each morph target with all zero
  23272. // morphTargetInfluences except for the keys in which
  23273. // the morphTarget is named.
  23274. for ( const morphTargetName in morphTargetNames ) {
  23275. const times = [];
  23276. const values = [];
  23277. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  23278. const animationKey = animationKeys[ k ];
  23279. times.push( animationKey.time );
  23280. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  23281. }
  23282. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  23283. }
  23284. duration = morphTargetNames.length * fps;
  23285. } else {
  23286. // ...assume skeletal animation
  23287. const boneName = '.bones[' + bones[ h ].name + ']';
  23288. addNonemptyTrack(
  23289. VectorKeyframeTrack, boneName + '.position',
  23290. animationKeys, 'pos', tracks );
  23291. addNonemptyTrack(
  23292. QuaternionKeyframeTrack, boneName + '.quaternion',
  23293. animationKeys, 'rot', tracks );
  23294. addNonemptyTrack(
  23295. VectorKeyframeTrack, boneName + '.scale',
  23296. animationKeys, 'scl', tracks );
  23297. }
  23298. }
  23299. if ( tracks.length === 0 ) {
  23300. return null;
  23301. }
  23302. const clip = new this( clipName, duration, tracks, blendMode );
  23303. return clip;
  23304. }
  23305. resetDuration() {
  23306. const tracks = this.tracks;
  23307. let duration = 0;
  23308. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  23309. const track = this.tracks[ i ];
  23310. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  23311. }
  23312. this.duration = duration;
  23313. return this;
  23314. }
  23315. trim() {
  23316. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23317. this.tracks[ i ].trim( 0, this.duration );
  23318. }
  23319. return this;
  23320. }
  23321. validate() {
  23322. let valid = true;
  23323. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23324. valid = valid && this.tracks[ i ].validate();
  23325. }
  23326. return valid;
  23327. }
  23328. optimize() {
  23329. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23330. this.tracks[ i ].optimize();
  23331. }
  23332. return this;
  23333. }
  23334. clone() {
  23335. const tracks = [];
  23336. for ( let i = 0; i < this.tracks.length; i ++ ) {
  23337. tracks.push( this.tracks[ i ].clone() );
  23338. }
  23339. return new this.constructor( this.name, this.duration, tracks, this.blendMode );
  23340. }
  23341. toJSON() {
  23342. return this.constructor.toJSON( this );
  23343. }
  23344. }
  23345. function getTrackTypeForValueTypeName( typeName ) {
  23346. switch ( typeName.toLowerCase() ) {
  23347. case 'scalar':
  23348. case 'double':
  23349. case 'float':
  23350. case 'number':
  23351. case 'integer':
  23352. return NumberKeyframeTrack;
  23353. case 'vector':
  23354. case 'vector2':
  23355. case 'vector3':
  23356. case 'vector4':
  23357. return VectorKeyframeTrack;
  23358. case 'color':
  23359. return ColorKeyframeTrack;
  23360. case 'quaternion':
  23361. return QuaternionKeyframeTrack;
  23362. case 'bool':
  23363. case 'boolean':
  23364. return BooleanKeyframeTrack;
  23365. case 'string':
  23366. return StringKeyframeTrack;
  23367. }
  23368. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  23369. }
  23370. function parseKeyframeTrack( json ) {
  23371. if ( json.type === undefined ) {
  23372. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  23373. }
  23374. const trackType = getTrackTypeForValueTypeName( json.type );
  23375. if ( json.times === undefined ) {
  23376. const times = [], values = [];
  23377. flattenJSON( json.keys, times, values, 'value' );
  23378. json.times = times;
  23379. json.values = values;
  23380. }
  23381. // derived classes can define a static parse method
  23382. if ( trackType.parse !== undefined ) {
  23383. return trackType.parse( json );
  23384. } else {
  23385. // by default, we assume a constructor compatible with the base
  23386. return new trackType( json.name, json.times, json.values, json.interpolation );
  23387. }
  23388. }
  23389. const Cache = {
  23390. enabled: false,
  23391. files: {},
  23392. add: function ( key, file ) {
  23393. if ( this.enabled === false ) return;
  23394. // console.log( 'THREE.Cache', 'Adding key:', key );
  23395. this.files[ key ] = file;
  23396. },
  23397. get: function ( key ) {
  23398. if ( this.enabled === false ) return;
  23399. // console.log( 'THREE.Cache', 'Checking key:', key );
  23400. return this.files[ key ];
  23401. },
  23402. remove: function ( key ) {
  23403. delete this.files[ key ];
  23404. },
  23405. clear: function () {
  23406. this.files = {};
  23407. }
  23408. };
  23409. class LoadingManager {
  23410. constructor( onLoad, onProgress, onError ) {
  23411. const scope = this;
  23412. let isLoading = false;
  23413. let itemsLoaded = 0;
  23414. let itemsTotal = 0;
  23415. let urlModifier = undefined;
  23416. const handlers = [];
  23417. // Refer to #5689 for the reason why we don't set .onStart
  23418. // in the constructor
  23419. this.onStart = undefined;
  23420. this.onLoad = onLoad;
  23421. this.onProgress = onProgress;
  23422. this.onError = onError;
  23423. this.itemStart = function ( url ) {
  23424. itemsTotal ++;
  23425. if ( isLoading === false ) {
  23426. if ( scope.onStart !== undefined ) {
  23427. scope.onStart( url, itemsLoaded, itemsTotal );
  23428. }
  23429. }
  23430. isLoading = true;
  23431. };
  23432. this.itemEnd = function ( url ) {
  23433. itemsLoaded ++;
  23434. if ( scope.onProgress !== undefined ) {
  23435. scope.onProgress( url, itemsLoaded, itemsTotal );
  23436. }
  23437. if ( itemsLoaded === itemsTotal ) {
  23438. isLoading = false;
  23439. if ( scope.onLoad !== undefined ) {
  23440. scope.onLoad();
  23441. }
  23442. }
  23443. };
  23444. this.itemError = function ( url ) {
  23445. if ( scope.onError !== undefined ) {
  23446. scope.onError( url );
  23447. }
  23448. };
  23449. this.resolveURL = function ( url ) {
  23450. if ( urlModifier ) {
  23451. return urlModifier( url );
  23452. }
  23453. return url;
  23454. };
  23455. this.setURLModifier = function ( transform ) {
  23456. urlModifier = transform;
  23457. return this;
  23458. };
  23459. this.addHandler = function ( regex, loader ) {
  23460. handlers.push( regex, loader );
  23461. return this;
  23462. };
  23463. this.removeHandler = function ( regex ) {
  23464. const index = handlers.indexOf( regex );
  23465. if ( index !== - 1 ) {
  23466. handlers.splice( index, 2 );
  23467. }
  23468. return this;
  23469. };
  23470. this.getHandler = function ( file ) {
  23471. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  23472. const regex = handlers[ i ];
  23473. const loader = handlers[ i + 1 ];
  23474. if ( regex.global ) regex.lastIndex = 0; // see #17920
  23475. if ( regex.test( file ) ) {
  23476. return loader;
  23477. }
  23478. }
  23479. return null;
  23480. };
  23481. }
  23482. }
  23483. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  23484. class Loader {
  23485. constructor( manager ) {
  23486. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23487. this.crossOrigin = 'anonymous';
  23488. this.withCredentials = false;
  23489. this.path = '';
  23490. this.resourcePath = '';
  23491. this.requestHeader = {};
  23492. }
  23493. load( /* url, onLoad, onProgress, onError */ ) {}
  23494. loadAsync( url, onProgress ) {
  23495. const scope = this;
  23496. return new Promise( function ( resolve, reject ) {
  23497. scope.load( url, resolve, onProgress, reject );
  23498. } );
  23499. }
  23500. parse( /* data */ ) {}
  23501. setCrossOrigin( crossOrigin ) {
  23502. this.crossOrigin = crossOrigin;
  23503. return this;
  23504. }
  23505. setWithCredentials( value ) {
  23506. this.withCredentials = value;
  23507. return this;
  23508. }
  23509. setPath( path ) {
  23510. this.path = path;
  23511. return this;
  23512. }
  23513. setResourcePath( resourcePath ) {
  23514. this.resourcePath = resourcePath;
  23515. return this;
  23516. }
  23517. setRequestHeader( requestHeader ) {
  23518. this.requestHeader = requestHeader;
  23519. return this;
  23520. }
  23521. }
  23522. const loading = {};
  23523. class HttpError extends Error {
  23524. constructor( message, response ) {
  23525. super( message );
  23526. this.response = response;
  23527. }
  23528. }
  23529. class FileLoader extends Loader {
  23530. constructor( manager ) {
  23531. super( manager );
  23532. }
  23533. load( url, onLoad, onProgress, onError ) {
  23534. if ( url === undefined ) url = '';
  23535. if ( this.path !== undefined ) url = this.path + url;
  23536. url = this.manager.resolveURL( url );
  23537. const cached = Cache.get( url );
  23538. if ( cached !== undefined ) {
  23539. this.manager.itemStart( url );
  23540. setTimeout( () => {
  23541. if ( onLoad ) onLoad( cached );
  23542. this.manager.itemEnd( url );
  23543. }, 0 );
  23544. return cached;
  23545. }
  23546. // Check if request is duplicate
  23547. if ( loading[ url ] !== undefined ) {
  23548. loading[ url ].push( {
  23549. onLoad: onLoad,
  23550. onProgress: onProgress,
  23551. onError: onError
  23552. } );
  23553. return;
  23554. }
  23555. // Initialise array for duplicate requests
  23556. loading[ url ] = [];
  23557. loading[ url ].push( {
  23558. onLoad: onLoad,
  23559. onProgress: onProgress,
  23560. onError: onError,
  23561. } );
  23562. // create request
  23563. const req = new Request( url, {
  23564. headers: new Headers( this.requestHeader ),
  23565. credentials: this.withCredentials ? 'include' : 'same-origin',
  23566. // An abort controller could be added within a future PR
  23567. } );
  23568. // record states ( avoid data race )
  23569. const mimeType = this.mimeType;
  23570. const responseType = this.responseType;
  23571. // start the fetch
  23572. fetch( req )
  23573. .then( response => {
  23574. if ( response.status === 200 || response.status === 0 ) {
  23575. // Some browsers return HTTP Status 0 when using non-http protocol
  23576. // e.g. 'file://' or 'data://'. Handle as success.
  23577. if ( response.status === 0 ) {
  23578. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  23579. }
  23580. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  23581. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  23582. return response;
  23583. }
  23584. const callbacks = loading[ url ];
  23585. const reader = response.body.getReader();
  23586. const contentLength = response.headers.get( 'Content-Length' );
  23587. const total = contentLength ? parseInt( contentLength ) : 0;
  23588. const lengthComputable = total !== 0;
  23589. let loaded = 0;
  23590. // periodically read data into the new stream tracking while download progress
  23591. const stream = new ReadableStream( {
  23592. start( controller ) {
  23593. readData();
  23594. function readData() {
  23595. reader.read().then( ( { done, value } ) => {
  23596. if ( done ) {
  23597. controller.close();
  23598. } else {
  23599. loaded += value.byteLength;
  23600. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  23601. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23602. const callback = callbacks[ i ];
  23603. if ( callback.onProgress ) callback.onProgress( event );
  23604. }
  23605. controller.enqueue( value );
  23606. readData();
  23607. }
  23608. } );
  23609. }
  23610. }
  23611. } );
  23612. return new Response( stream );
  23613. } else {
  23614. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  23615. }
  23616. } )
  23617. .then( response => {
  23618. switch ( responseType ) {
  23619. case 'arraybuffer':
  23620. return response.arrayBuffer();
  23621. case 'blob':
  23622. return response.blob();
  23623. case 'document':
  23624. return response.text()
  23625. .then( text => {
  23626. const parser = new DOMParser();
  23627. return parser.parseFromString( text, mimeType );
  23628. } );
  23629. case 'json':
  23630. return response.json();
  23631. default:
  23632. if ( mimeType === undefined ) {
  23633. return response.text();
  23634. } else {
  23635. // sniff encoding
  23636. const re = /charset="?([^;"\s]*)"?/i;
  23637. const exec = re.exec( mimeType );
  23638. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  23639. const decoder = new TextDecoder( label );
  23640. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  23641. }
  23642. }
  23643. } )
  23644. .then( data => {
  23645. // Add to cache only on HTTP success, so that we do not cache
  23646. // error response bodies as proper responses to requests.
  23647. Cache.add( url, data );
  23648. const callbacks = loading[ url ];
  23649. delete loading[ url ];
  23650. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23651. const callback = callbacks[ i ];
  23652. if ( callback.onLoad ) callback.onLoad( data );
  23653. }
  23654. } )
  23655. .catch( err => {
  23656. // Abort errors and other errors are handled the same
  23657. const callbacks = loading[ url ];
  23658. if ( callbacks === undefined ) {
  23659. // When onLoad was called and url was deleted in `loading`
  23660. this.manager.itemError( url );
  23661. throw err;
  23662. }
  23663. delete loading[ url ];
  23664. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  23665. const callback = callbacks[ i ];
  23666. if ( callback.onError ) callback.onError( err );
  23667. }
  23668. this.manager.itemError( url );
  23669. } )
  23670. .finally( () => {
  23671. this.manager.itemEnd( url );
  23672. } );
  23673. this.manager.itemStart( url );
  23674. }
  23675. setResponseType( value ) {
  23676. this.responseType = value;
  23677. return this;
  23678. }
  23679. setMimeType( value ) {
  23680. this.mimeType = value;
  23681. return this;
  23682. }
  23683. }
  23684. class AnimationLoader extends Loader {
  23685. constructor( manager ) {
  23686. super( manager );
  23687. }
  23688. load( url, onLoad, onProgress, onError ) {
  23689. const scope = this;
  23690. const loader = new FileLoader( this.manager );
  23691. loader.setPath( this.path );
  23692. loader.setRequestHeader( this.requestHeader );
  23693. loader.setWithCredentials( this.withCredentials );
  23694. loader.load( url, function ( text ) {
  23695. try {
  23696. onLoad( scope.parse( JSON.parse( text ) ) );
  23697. } catch ( e ) {
  23698. if ( onError ) {
  23699. onError( e );
  23700. } else {
  23701. console.error( e );
  23702. }
  23703. scope.manager.itemError( url );
  23704. }
  23705. }, onProgress, onError );
  23706. }
  23707. parse( json ) {
  23708. const animations = [];
  23709. for ( let i = 0; i < json.length; i ++ ) {
  23710. const clip = AnimationClip.parse( json[ i ] );
  23711. animations.push( clip );
  23712. }
  23713. return animations;
  23714. }
  23715. }
  23716. /**
  23717. * Abstract Base class to block based textures loader (dds, pvr, ...)
  23718. *
  23719. * Sub classes have to implement the parse() method which will be used in load().
  23720. */
  23721. class CompressedTextureLoader extends Loader {
  23722. constructor( manager ) {
  23723. super( manager );
  23724. }
  23725. load( url, onLoad, onProgress, onError ) {
  23726. const scope = this;
  23727. const images = [];
  23728. const texture = new CompressedTexture();
  23729. const loader = new FileLoader( this.manager );
  23730. loader.setPath( this.path );
  23731. loader.setResponseType( 'arraybuffer' );
  23732. loader.setRequestHeader( this.requestHeader );
  23733. loader.setWithCredentials( scope.withCredentials );
  23734. let loaded = 0;
  23735. function loadTexture( i ) {
  23736. loader.load( url[ i ], function ( buffer ) {
  23737. const texDatas = scope.parse( buffer, true );
  23738. images[ i ] = {
  23739. width: texDatas.width,
  23740. height: texDatas.height,
  23741. format: texDatas.format,
  23742. mipmaps: texDatas.mipmaps
  23743. };
  23744. loaded += 1;
  23745. if ( loaded === 6 ) {
  23746. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  23747. texture.image = images;
  23748. texture.format = texDatas.format;
  23749. texture.needsUpdate = true;
  23750. if ( onLoad ) onLoad( texture );
  23751. }
  23752. }, onProgress, onError );
  23753. }
  23754. if ( Array.isArray( url ) ) {
  23755. for ( let i = 0, il = url.length; i < il; ++ i ) {
  23756. loadTexture( i );
  23757. }
  23758. } else {
  23759. // compressed cubemap texture stored in a single DDS file
  23760. loader.load( url, function ( buffer ) {
  23761. const texDatas = scope.parse( buffer, true );
  23762. if ( texDatas.isCubemap ) {
  23763. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  23764. for ( let f = 0; f < faces; f ++ ) {
  23765. images[ f ] = { mipmaps: [] };
  23766. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  23767. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  23768. images[ f ].format = texDatas.format;
  23769. images[ f ].width = texDatas.width;
  23770. images[ f ].height = texDatas.height;
  23771. }
  23772. }
  23773. texture.image = images;
  23774. } else {
  23775. texture.image.width = texDatas.width;
  23776. texture.image.height = texDatas.height;
  23777. texture.mipmaps = texDatas.mipmaps;
  23778. }
  23779. if ( texDatas.mipmapCount === 1 ) {
  23780. texture.minFilter = LinearFilter;
  23781. }
  23782. texture.format = texDatas.format;
  23783. texture.needsUpdate = true;
  23784. if ( onLoad ) onLoad( texture );
  23785. }, onProgress, onError );
  23786. }
  23787. return texture;
  23788. }
  23789. }
  23790. class ImageLoader extends Loader {
  23791. constructor( manager ) {
  23792. super( manager );
  23793. }
  23794. load( url, onLoad, onProgress, onError ) {
  23795. if ( this.path !== undefined ) url = this.path + url;
  23796. url = this.manager.resolveURL( url );
  23797. const scope = this;
  23798. const cached = Cache.get( url );
  23799. if ( cached !== undefined ) {
  23800. scope.manager.itemStart( url );
  23801. setTimeout( function () {
  23802. if ( onLoad ) onLoad( cached );
  23803. scope.manager.itemEnd( url );
  23804. }, 0 );
  23805. return cached;
  23806. }
  23807. const image = createElementNS( 'img' );
  23808. function onImageLoad() {
  23809. removeEventListeners();
  23810. Cache.add( url, this );
  23811. if ( onLoad ) onLoad( this );
  23812. scope.manager.itemEnd( url );
  23813. }
  23814. function onImageError( event ) {
  23815. removeEventListeners();
  23816. if ( onError ) onError( event );
  23817. scope.manager.itemError( url );
  23818. scope.manager.itemEnd( url );
  23819. }
  23820. function removeEventListeners() {
  23821. image.removeEventListener( 'load', onImageLoad, false );
  23822. image.removeEventListener( 'error', onImageError, false );
  23823. }
  23824. image.addEventListener( 'load', onImageLoad, false );
  23825. image.addEventListener( 'error', onImageError, false );
  23826. if ( url.slice( 0, 5 ) !== 'data:' ) {
  23827. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  23828. }
  23829. scope.manager.itemStart( url );
  23830. image.src = url;
  23831. return image;
  23832. }
  23833. }
  23834. class CubeTextureLoader extends Loader {
  23835. constructor( manager ) {
  23836. super( manager );
  23837. }
  23838. load( urls, onLoad, onProgress, onError ) {
  23839. const texture = new CubeTexture();
  23840. const loader = new ImageLoader( this.manager );
  23841. loader.setCrossOrigin( this.crossOrigin );
  23842. loader.setPath( this.path );
  23843. let loaded = 0;
  23844. function loadTexture( i ) {
  23845. loader.load( urls[ i ], function ( image ) {
  23846. texture.images[ i ] = image;
  23847. loaded ++;
  23848. if ( loaded === 6 ) {
  23849. texture.needsUpdate = true;
  23850. if ( onLoad ) onLoad( texture );
  23851. }
  23852. }, undefined, onError );
  23853. }
  23854. for ( let i = 0; i < urls.length; ++ i ) {
  23855. loadTexture( i );
  23856. }
  23857. return texture;
  23858. }
  23859. }
  23860. /**
  23861. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  23862. *
  23863. * Sub classes have to implement the parse() method which will be used in load().
  23864. */
  23865. class DataTextureLoader extends Loader {
  23866. constructor( manager ) {
  23867. super( manager );
  23868. }
  23869. load( url, onLoad, onProgress, onError ) {
  23870. const scope = this;
  23871. const texture = new DataTexture();
  23872. const loader = new FileLoader( this.manager );
  23873. loader.setResponseType( 'arraybuffer' );
  23874. loader.setRequestHeader( this.requestHeader );
  23875. loader.setPath( this.path );
  23876. loader.setWithCredentials( scope.withCredentials );
  23877. loader.load( url, function ( buffer ) {
  23878. const texData = scope.parse( buffer );
  23879. if ( ! texData ) return;
  23880. if ( texData.image !== undefined ) {
  23881. texture.image = texData.image;
  23882. } else if ( texData.data !== undefined ) {
  23883. texture.image.width = texData.width;
  23884. texture.image.height = texData.height;
  23885. texture.image.data = texData.data;
  23886. }
  23887. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  23888. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  23889. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  23890. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  23891. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  23892. if ( texData.encoding !== undefined ) {
  23893. texture.encoding = texData.encoding;
  23894. }
  23895. if ( texData.flipY !== undefined ) {
  23896. texture.flipY = texData.flipY;
  23897. }
  23898. if ( texData.format !== undefined ) {
  23899. texture.format = texData.format;
  23900. }
  23901. if ( texData.type !== undefined ) {
  23902. texture.type = texData.type;
  23903. }
  23904. if ( texData.mipmaps !== undefined ) {
  23905. texture.mipmaps = texData.mipmaps;
  23906. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  23907. }
  23908. if ( texData.mipmapCount === 1 ) {
  23909. texture.minFilter = LinearFilter;
  23910. }
  23911. if ( texData.generateMipmaps !== undefined ) {
  23912. texture.generateMipmaps = texData.generateMipmaps;
  23913. }
  23914. texture.needsUpdate = true;
  23915. if ( onLoad ) onLoad( texture, texData );
  23916. }, onProgress, onError );
  23917. return texture;
  23918. }
  23919. }
  23920. class TextureLoader extends Loader {
  23921. constructor( manager ) {
  23922. super( manager );
  23923. }
  23924. load( url, onLoad, onProgress, onError ) {
  23925. const texture = new Texture();
  23926. const loader = new ImageLoader( this.manager );
  23927. loader.setCrossOrigin( this.crossOrigin );
  23928. loader.setPath( this.path );
  23929. loader.load( url, function ( image ) {
  23930. texture.image = image;
  23931. texture.needsUpdate = true;
  23932. if ( onLoad !== undefined ) {
  23933. onLoad( texture );
  23934. }
  23935. }, onProgress, onError );
  23936. return texture;
  23937. }
  23938. }
  23939. class Light extends Object3D {
  23940. constructor( color, intensity = 1 ) {
  23941. super();
  23942. this.isLight = true;
  23943. this.type = 'Light';
  23944. this.color = new Color( color );
  23945. this.intensity = intensity;
  23946. }
  23947. dispose() {
  23948. // Empty here in base class; some subclasses override.
  23949. }
  23950. copy( source, recursive ) {
  23951. super.copy( source, recursive );
  23952. this.color.copy( source.color );
  23953. this.intensity = source.intensity;
  23954. return this;
  23955. }
  23956. toJSON( meta ) {
  23957. const data = super.toJSON( meta );
  23958. data.object.color = this.color.getHex();
  23959. data.object.intensity = this.intensity;
  23960. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  23961. if ( this.distance !== undefined ) data.object.distance = this.distance;
  23962. if ( this.angle !== undefined ) data.object.angle = this.angle;
  23963. if ( this.decay !== undefined ) data.object.decay = this.decay;
  23964. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  23965. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  23966. return data;
  23967. }
  23968. }
  23969. class HemisphereLight extends Light {
  23970. constructor( skyColor, groundColor, intensity ) {
  23971. super( skyColor, intensity );
  23972. this.isHemisphereLight = true;
  23973. this.type = 'HemisphereLight';
  23974. this.position.copy( Object3D.DefaultUp );
  23975. this.updateMatrix();
  23976. this.groundColor = new Color( groundColor );
  23977. }
  23978. copy( source, recursive ) {
  23979. super.copy( source, recursive );
  23980. this.groundColor.copy( source.groundColor );
  23981. return this;
  23982. }
  23983. }
  23984. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  23985. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  23986. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  23987. class LightShadow {
  23988. constructor( camera ) {
  23989. this.camera = camera;
  23990. this.bias = 0;
  23991. this.normalBias = 0;
  23992. this.radius = 1;
  23993. this.blurSamples = 8;
  23994. this.mapSize = new Vector2( 512, 512 );
  23995. this.map = null;
  23996. this.mapPass = null;
  23997. this.matrix = new Matrix4();
  23998. this.autoUpdate = true;
  23999. this.needsUpdate = false;
  24000. this._frustum = new Frustum();
  24001. this._frameExtents = new Vector2( 1, 1 );
  24002. this._viewportCount = 1;
  24003. this._viewports = [
  24004. new Vector4( 0, 0, 1, 1 )
  24005. ];
  24006. }
  24007. getViewportCount() {
  24008. return this._viewportCount;
  24009. }
  24010. getFrustum() {
  24011. return this._frustum;
  24012. }
  24013. updateMatrices( light ) {
  24014. const shadowCamera = this.camera;
  24015. const shadowMatrix = this.matrix;
  24016. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  24017. shadowCamera.position.copy( _lightPositionWorld$1 );
  24018. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  24019. shadowCamera.lookAt( _lookTarget$1 );
  24020. shadowCamera.updateMatrixWorld();
  24021. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  24022. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1 );
  24023. shadowMatrix.set(
  24024. 0.5, 0.0, 0.0, 0.5,
  24025. 0.0, 0.5, 0.0, 0.5,
  24026. 0.0, 0.0, 0.5, 0.5,
  24027. 0.0, 0.0, 0.0, 1.0
  24028. );
  24029. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  24030. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  24031. }
  24032. getViewport( viewportIndex ) {
  24033. return this._viewports[ viewportIndex ];
  24034. }
  24035. getFrameExtents() {
  24036. return this._frameExtents;
  24037. }
  24038. dispose() {
  24039. if ( this.map ) {
  24040. this.map.dispose();
  24041. }
  24042. if ( this.mapPass ) {
  24043. this.mapPass.dispose();
  24044. }
  24045. }
  24046. copy( source ) {
  24047. this.camera = source.camera.clone();
  24048. this.bias = source.bias;
  24049. this.radius = source.radius;
  24050. this.mapSize.copy( source.mapSize );
  24051. return this;
  24052. }
  24053. clone() {
  24054. return new this.constructor().copy( this );
  24055. }
  24056. toJSON() {
  24057. const object = {};
  24058. if ( this.bias !== 0 ) object.bias = this.bias;
  24059. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  24060. if ( this.radius !== 1 ) object.radius = this.radius;
  24061. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  24062. object.camera = this.camera.toJSON( false ).object;
  24063. delete object.camera.matrix;
  24064. return object;
  24065. }
  24066. }
  24067. class SpotLightShadow extends LightShadow {
  24068. constructor() {
  24069. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  24070. this.isSpotLightShadow = true;
  24071. this.focus = 1;
  24072. }
  24073. updateMatrices( light ) {
  24074. const camera = this.camera;
  24075. const fov = RAD2DEG * 2 * light.angle * this.focus;
  24076. const aspect = this.mapSize.width / this.mapSize.height;
  24077. const far = light.distance || camera.far;
  24078. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  24079. camera.fov = fov;
  24080. camera.aspect = aspect;
  24081. camera.far = far;
  24082. camera.updateProjectionMatrix();
  24083. }
  24084. super.updateMatrices( light );
  24085. }
  24086. copy( source ) {
  24087. super.copy( source );
  24088. this.focus = source.focus;
  24089. return this;
  24090. }
  24091. }
  24092. class SpotLight extends Light {
  24093. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 1 ) {
  24094. super( color, intensity );
  24095. this.isSpotLight = true;
  24096. this.type = 'SpotLight';
  24097. this.position.copy( Object3D.DefaultUp );
  24098. this.updateMatrix();
  24099. this.target = new Object3D();
  24100. this.distance = distance;
  24101. this.angle = angle;
  24102. this.penumbra = penumbra;
  24103. this.decay = decay; // for physically correct lights, should be 2.
  24104. this.shadow = new SpotLightShadow();
  24105. }
  24106. get power() {
  24107. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24108. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  24109. return this.intensity * Math.PI;
  24110. }
  24111. set power( power ) {
  24112. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24113. this.intensity = power / Math.PI;
  24114. }
  24115. dispose() {
  24116. this.shadow.dispose();
  24117. }
  24118. copy( source, recursive ) {
  24119. super.copy( source, recursive );
  24120. this.distance = source.distance;
  24121. this.angle = source.angle;
  24122. this.penumbra = source.penumbra;
  24123. this.decay = source.decay;
  24124. this.target = source.target.clone();
  24125. this.shadow = source.shadow.clone();
  24126. return this;
  24127. }
  24128. }
  24129. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  24130. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  24131. const _lookTarget = /*@__PURE__*/ new Vector3();
  24132. class PointLightShadow extends LightShadow {
  24133. constructor() {
  24134. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  24135. this.isPointLightShadow = true;
  24136. this._frameExtents = new Vector2( 4, 2 );
  24137. this._viewportCount = 6;
  24138. this._viewports = [
  24139. // These viewports map a cube-map onto a 2D texture with the
  24140. // following orientation:
  24141. //
  24142. // xzXZ
  24143. // y Y
  24144. //
  24145. // X - Positive x direction
  24146. // x - Negative x direction
  24147. // Y - Positive y direction
  24148. // y - Negative y direction
  24149. // Z - Positive z direction
  24150. // z - Negative z direction
  24151. // positive X
  24152. new Vector4( 2, 1, 1, 1 ),
  24153. // negative X
  24154. new Vector4( 0, 1, 1, 1 ),
  24155. // positive Z
  24156. new Vector4( 3, 1, 1, 1 ),
  24157. // negative Z
  24158. new Vector4( 1, 1, 1, 1 ),
  24159. // positive Y
  24160. new Vector4( 3, 0, 1, 1 ),
  24161. // negative Y
  24162. new Vector4( 1, 0, 1, 1 )
  24163. ];
  24164. this._cubeDirections = [
  24165. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  24166. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  24167. ];
  24168. this._cubeUps = [
  24169. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  24170. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  24171. ];
  24172. }
  24173. updateMatrices( light, viewportIndex = 0 ) {
  24174. const camera = this.camera;
  24175. const shadowMatrix = this.matrix;
  24176. const far = light.distance || camera.far;
  24177. if ( far !== camera.far ) {
  24178. camera.far = far;
  24179. camera.updateProjectionMatrix();
  24180. }
  24181. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  24182. camera.position.copy( _lightPositionWorld );
  24183. _lookTarget.copy( camera.position );
  24184. _lookTarget.add( this._cubeDirections[ viewportIndex ] );
  24185. camera.up.copy( this._cubeUps[ viewportIndex ] );
  24186. camera.lookAt( _lookTarget );
  24187. camera.updateMatrixWorld();
  24188. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  24189. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  24190. this._frustum.setFromProjectionMatrix( _projScreenMatrix );
  24191. }
  24192. }
  24193. class PointLight extends Light {
  24194. constructor( color, intensity, distance = 0, decay = 1 ) {
  24195. super( color, intensity );
  24196. this.isPointLight = true;
  24197. this.type = 'PointLight';
  24198. this.distance = distance;
  24199. this.decay = decay; // for physically correct lights, should be 2.
  24200. this.shadow = new PointLightShadow();
  24201. }
  24202. get power() {
  24203. // compute the light's luminous power (in lumens) from its intensity (in candela)
  24204. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  24205. return this.intensity * 4 * Math.PI;
  24206. }
  24207. set power( power ) {
  24208. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  24209. this.intensity = power / ( 4 * Math.PI );
  24210. }
  24211. dispose() {
  24212. this.shadow.dispose();
  24213. }
  24214. copy( source, recursive ) {
  24215. super.copy( source, recursive );
  24216. this.distance = source.distance;
  24217. this.decay = source.decay;
  24218. this.shadow = source.shadow.clone();
  24219. return this;
  24220. }
  24221. }
  24222. class DirectionalLightShadow extends LightShadow {
  24223. constructor() {
  24224. super( new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  24225. this.isDirectionalLightShadow = true;
  24226. }
  24227. }
  24228. class DirectionalLight extends Light {
  24229. constructor( color, intensity ) {
  24230. super( color, intensity );
  24231. this.isDirectionalLight = true;
  24232. this.type = 'DirectionalLight';
  24233. this.position.copy( Object3D.DefaultUp );
  24234. this.updateMatrix();
  24235. this.target = new Object3D();
  24236. this.shadow = new DirectionalLightShadow();
  24237. }
  24238. dispose() {
  24239. this.shadow.dispose();
  24240. }
  24241. copy( source ) {
  24242. super.copy( source );
  24243. this.target = source.target.clone();
  24244. this.shadow = source.shadow.clone();
  24245. return this;
  24246. }
  24247. }
  24248. class AmbientLight extends Light {
  24249. constructor( color, intensity ) {
  24250. super( color, intensity );
  24251. this.isAmbientLight = true;
  24252. this.type = 'AmbientLight';
  24253. }
  24254. }
  24255. class RectAreaLight extends Light {
  24256. constructor( color, intensity, width = 10, height = 10 ) {
  24257. super( color, intensity );
  24258. this.isRectAreaLight = true;
  24259. this.type = 'RectAreaLight';
  24260. this.width = width;
  24261. this.height = height;
  24262. }
  24263. get power() {
  24264. // compute the light's luminous power (in lumens) from its intensity (in nits)
  24265. return this.intensity * this.width * this.height * Math.PI;
  24266. }
  24267. set power( power ) {
  24268. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  24269. this.intensity = power / ( this.width * this.height * Math.PI );
  24270. }
  24271. copy( source ) {
  24272. super.copy( source );
  24273. this.width = source.width;
  24274. this.height = source.height;
  24275. return this;
  24276. }
  24277. toJSON( meta ) {
  24278. const data = super.toJSON( meta );
  24279. data.object.width = this.width;
  24280. data.object.height = this.height;
  24281. return data;
  24282. }
  24283. }
  24284. /**
  24285. * Primary reference:
  24286. * https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24287. *
  24288. * Secondary reference:
  24289. * https://www.ppsloan.org/publications/StupidSH36.pdf
  24290. */
  24291. // 3-band SH defined by 9 coefficients
  24292. class SphericalHarmonics3 {
  24293. constructor() {
  24294. this.isSphericalHarmonics3 = true;
  24295. this.coefficients = [];
  24296. for ( let i = 0; i < 9; i ++ ) {
  24297. this.coefficients.push( new Vector3() );
  24298. }
  24299. }
  24300. set( coefficients ) {
  24301. for ( let i = 0; i < 9; i ++ ) {
  24302. this.coefficients[ i ].copy( coefficients[ i ] );
  24303. }
  24304. return this;
  24305. }
  24306. zero() {
  24307. for ( let i = 0; i < 9; i ++ ) {
  24308. this.coefficients[ i ].set( 0, 0, 0 );
  24309. }
  24310. return this;
  24311. }
  24312. // get the radiance in the direction of the normal
  24313. // target is a Vector3
  24314. getAt( normal, target ) {
  24315. // normal is assumed to be unit length
  24316. const x = normal.x, y = normal.y, z = normal.z;
  24317. const coeff = this.coefficients;
  24318. // band 0
  24319. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  24320. // band 1
  24321. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  24322. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  24323. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  24324. // band 2
  24325. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  24326. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  24327. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  24328. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  24329. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  24330. return target;
  24331. }
  24332. // get the irradiance (radiance convolved with cosine lobe) in the direction of the normal
  24333. // target is a Vector3
  24334. // https://graphics.stanford.edu/papers/envmap/envmap.pdf
  24335. getIrradianceAt( normal, target ) {
  24336. // normal is assumed to be unit length
  24337. const x = normal.x, y = normal.y, z = normal.z;
  24338. const coeff = this.coefficients;
  24339. // band 0
  24340. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  24341. // band 1
  24342. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  24343. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  24344. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  24345. // band 2
  24346. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  24347. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  24348. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  24349. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  24350. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  24351. return target;
  24352. }
  24353. add( sh ) {
  24354. for ( let i = 0; i < 9; i ++ ) {
  24355. this.coefficients[ i ].add( sh.coefficients[ i ] );
  24356. }
  24357. return this;
  24358. }
  24359. addScaledSH( sh, s ) {
  24360. for ( let i = 0; i < 9; i ++ ) {
  24361. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  24362. }
  24363. return this;
  24364. }
  24365. scale( s ) {
  24366. for ( let i = 0; i < 9; i ++ ) {
  24367. this.coefficients[ i ].multiplyScalar( s );
  24368. }
  24369. return this;
  24370. }
  24371. lerp( sh, alpha ) {
  24372. for ( let i = 0; i < 9; i ++ ) {
  24373. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  24374. }
  24375. return this;
  24376. }
  24377. equals( sh ) {
  24378. for ( let i = 0; i < 9; i ++ ) {
  24379. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  24380. return false;
  24381. }
  24382. }
  24383. return true;
  24384. }
  24385. copy( sh ) {
  24386. return this.set( sh.coefficients );
  24387. }
  24388. clone() {
  24389. return new this.constructor().copy( this );
  24390. }
  24391. fromArray( array, offset = 0 ) {
  24392. const coefficients = this.coefficients;
  24393. for ( let i = 0; i < 9; i ++ ) {
  24394. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  24395. }
  24396. return this;
  24397. }
  24398. toArray( array = [], offset = 0 ) {
  24399. const coefficients = this.coefficients;
  24400. for ( let i = 0; i < 9; i ++ ) {
  24401. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  24402. }
  24403. return array;
  24404. }
  24405. // evaluate the basis functions
  24406. // shBasis is an Array[ 9 ]
  24407. static getBasisAt( normal, shBasis ) {
  24408. // normal is assumed to be unit length
  24409. const x = normal.x, y = normal.y, z = normal.z;
  24410. // band 0
  24411. shBasis[ 0 ] = 0.282095;
  24412. // band 1
  24413. shBasis[ 1 ] = 0.488603 * y;
  24414. shBasis[ 2 ] = 0.488603 * z;
  24415. shBasis[ 3 ] = 0.488603 * x;
  24416. // band 2
  24417. shBasis[ 4 ] = 1.092548 * x * y;
  24418. shBasis[ 5 ] = 1.092548 * y * z;
  24419. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  24420. shBasis[ 7 ] = 1.092548 * x * z;
  24421. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  24422. }
  24423. }
  24424. class LightProbe extends Light {
  24425. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  24426. super( undefined, intensity );
  24427. this.isLightProbe = true;
  24428. this.sh = sh;
  24429. }
  24430. copy( source ) {
  24431. super.copy( source );
  24432. this.sh.copy( source.sh );
  24433. return this;
  24434. }
  24435. fromJSON( json ) {
  24436. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  24437. this.sh.fromArray( json.sh );
  24438. return this;
  24439. }
  24440. toJSON( meta ) {
  24441. const data = super.toJSON( meta );
  24442. data.object.sh = this.sh.toArray();
  24443. return data;
  24444. }
  24445. }
  24446. class MaterialLoader extends Loader {
  24447. constructor( manager ) {
  24448. super( manager );
  24449. this.textures = {};
  24450. }
  24451. load( url, onLoad, onProgress, onError ) {
  24452. const scope = this;
  24453. const loader = new FileLoader( scope.manager );
  24454. loader.setPath( scope.path );
  24455. loader.setRequestHeader( scope.requestHeader );
  24456. loader.setWithCredentials( scope.withCredentials );
  24457. loader.load( url, function ( text ) {
  24458. try {
  24459. onLoad( scope.parse( JSON.parse( text ) ) );
  24460. } catch ( e ) {
  24461. if ( onError ) {
  24462. onError( e );
  24463. } else {
  24464. console.error( e );
  24465. }
  24466. scope.manager.itemError( url );
  24467. }
  24468. }, onProgress, onError );
  24469. }
  24470. parse( json ) {
  24471. const textures = this.textures;
  24472. function getTexture( name ) {
  24473. if ( textures[ name ] === undefined ) {
  24474. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  24475. }
  24476. return textures[ name ];
  24477. }
  24478. const material = MaterialLoader.createMaterialFromType( json.type );
  24479. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  24480. if ( json.name !== undefined ) material.name = json.name;
  24481. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  24482. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  24483. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  24484. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  24485. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  24486. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  24487. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  24488. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  24489. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  24490. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  24491. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  24492. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  24493. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  24494. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  24495. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  24496. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  24497. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  24498. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  24499. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  24500. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  24501. if ( json.fog !== undefined ) material.fog = json.fog;
  24502. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  24503. if ( json.blending !== undefined ) material.blending = json.blending;
  24504. if ( json.combine !== undefined ) material.combine = json.combine;
  24505. if ( json.side !== undefined ) material.side = json.side;
  24506. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  24507. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  24508. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  24509. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  24510. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  24511. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  24512. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  24513. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  24514. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  24515. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  24516. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  24517. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  24518. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  24519. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  24520. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  24521. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  24522. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  24523. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  24524. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  24525. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  24526. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  24527. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  24528. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  24529. if ( json.scale !== undefined ) material.scale = json.scale;
  24530. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  24531. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  24532. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  24533. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  24534. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  24535. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  24536. if ( json.visible !== undefined ) material.visible = json.visible;
  24537. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  24538. if ( json.userData !== undefined ) material.userData = json.userData;
  24539. if ( json.vertexColors !== undefined ) {
  24540. if ( typeof json.vertexColors === 'number' ) {
  24541. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  24542. } else {
  24543. material.vertexColors = json.vertexColors;
  24544. }
  24545. }
  24546. // Shader Material
  24547. if ( json.uniforms !== undefined ) {
  24548. for ( const name in json.uniforms ) {
  24549. const uniform = json.uniforms[ name ];
  24550. material.uniforms[ name ] = {};
  24551. switch ( uniform.type ) {
  24552. case 't':
  24553. material.uniforms[ name ].value = getTexture( uniform.value );
  24554. break;
  24555. case 'c':
  24556. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  24557. break;
  24558. case 'v2':
  24559. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  24560. break;
  24561. case 'v3':
  24562. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  24563. break;
  24564. case 'v4':
  24565. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  24566. break;
  24567. case 'm3':
  24568. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  24569. break;
  24570. case 'm4':
  24571. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  24572. break;
  24573. default:
  24574. material.uniforms[ name ].value = uniform.value;
  24575. }
  24576. }
  24577. }
  24578. if ( json.defines !== undefined ) material.defines = json.defines;
  24579. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  24580. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  24581. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  24582. if ( json.extensions !== undefined ) {
  24583. for ( const key in json.extensions ) {
  24584. material.extensions[ key ] = json.extensions[ key ];
  24585. }
  24586. }
  24587. // for PointsMaterial
  24588. if ( json.size !== undefined ) material.size = json.size;
  24589. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  24590. // maps
  24591. if ( json.map !== undefined ) material.map = getTexture( json.map );
  24592. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  24593. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  24594. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  24595. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  24596. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  24597. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  24598. if ( json.normalScale !== undefined ) {
  24599. let normalScale = json.normalScale;
  24600. if ( Array.isArray( normalScale ) === false ) {
  24601. // Blender exporter used to export a scalar. See #7459
  24602. normalScale = [ normalScale, normalScale ];
  24603. }
  24604. material.normalScale = new Vector2().fromArray( normalScale );
  24605. }
  24606. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  24607. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  24608. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  24609. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  24610. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  24611. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  24612. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  24613. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  24614. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  24615. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  24616. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  24617. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  24618. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  24619. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  24620. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  24621. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  24622. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  24623. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  24624. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  24625. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  24626. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  24627. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  24628. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  24629. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  24630. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  24631. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  24632. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  24633. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  24634. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  24635. return material;
  24636. }
  24637. setTextures( value ) {
  24638. this.textures = value;
  24639. return this;
  24640. }
  24641. static createMaterialFromType( type ) {
  24642. const materialLib = {
  24643. ShadowMaterial,
  24644. SpriteMaterial,
  24645. RawShaderMaterial,
  24646. ShaderMaterial,
  24647. PointsMaterial,
  24648. MeshPhysicalMaterial,
  24649. MeshStandardMaterial,
  24650. MeshPhongMaterial,
  24651. MeshToonMaterial,
  24652. MeshNormalMaterial,
  24653. MeshLambertMaterial,
  24654. MeshDepthMaterial,
  24655. MeshDistanceMaterial,
  24656. MeshBasicMaterial,
  24657. MeshMatcapMaterial,
  24658. LineDashedMaterial,
  24659. LineBasicMaterial,
  24660. Material
  24661. };
  24662. return new materialLib[ type ]();
  24663. }
  24664. }
  24665. class LoaderUtils {
  24666. static decodeText( array ) {
  24667. if ( typeof TextDecoder !== 'undefined' ) {
  24668. return new TextDecoder().decode( array );
  24669. }
  24670. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  24671. // throws a "maximum call stack size exceeded" error for large arrays.
  24672. let s = '';
  24673. for ( let i = 0, il = array.length; i < il; i ++ ) {
  24674. // Implicitly assumes little-endian.
  24675. s += String.fromCharCode( array[ i ] );
  24676. }
  24677. try {
  24678. // merges multi-byte utf-8 characters.
  24679. return decodeURIComponent( escape( s ) );
  24680. } catch ( e ) { // see #16358
  24681. return s;
  24682. }
  24683. }
  24684. static extractUrlBase( url ) {
  24685. const index = url.lastIndexOf( '/' );
  24686. if ( index === - 1 ) return './';
  24687. return url.slice( 0, index + 1 );
  24688. }
  24689. static resolveURL( url, path ) {
  24690. // Invalid URL
  24691. if ( typeof url !== 'string' || url === '' ) return '';
  24692. // Host Relative URL
  24693. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  24694. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  24695. }
  24696. // Absolute URL http://,https://,//
  24697. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  24698. // Data URI
  24699. if ( /^data:.*,.*$/i.test( url ) ) return url;
  24700. // Blob URL
  24701. if ( /^blob:.*$/i.test( url ) ) return url;
  24702. // Relative URL
  24703. return path + url;
  24704. }
  24705. }
  24706. class InstancedBufferGeometry extends BufferGeometry {
  24707. constructor() {
  24708. super();
  24709. this.isInstancedBufferGeometry = true;
  24710. this.type = 'InstancedBufferGeometry';
  24711. this.instanceCount = Infinity;
  24712. }
  24713. copy( source ) {
  24714. super.copy( source );
  24715. this.instanceCount = source.instanceCount;
  24716. return this;
  24717. }
  24718. clone() {
  24719. return new this.constructor().copy( this );
  24720. }
  24721. toJSON() {
  24722. const data = super.toJSON( this );
  24723. data.instanceCount = this.instanceCount;
  24724. data.isInstancedBufferGeometry = true;
  24725. return data;
  24726. }
  24727. }
  24728. class BufferGeometryLoader extends Loader {
  24729. constructor( manager ) {
  24730. super( manager );
  24731. }
  24732. load( url, onLoad, onProgress, onError ) {
  24733. const scope = this;
  24734. const loader = new FileLoader( scope.manager );
  24735. loader.setPath( scope.path );
  24736. loader.setRequestHeader( scope.requestHeader );
  24737. loader.setWithCredentials( scope.withCredentials );
  24738. loader.load( url, function ( text ) {
  24739. try {
  24740. onLoad( scope.parse( JSON.parse( text ) ) );
  24741. } catch ( e ) {
  24742. if ( onError ) {
  24743. onError( e );
  24744. } else {
  24745. console.error( e );
  24746. }
  24747. scope.manager.itemError( url );
  24748. }
  24749. }, onProgress, onError );
  24750. }
  24751. parse( json ) {
  24752. const interleavedBufferMap = {};
  24753. const arrayBufferMap = {};
  24754. function getInterleavedBuffer( json, uuid ) {
  24755. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  24756. const interleavedBuffers = json.interleavedBuffers;
  24757. const interleavedBuffer = interleavedBuffers[ uuid ];
  24758. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  24759. const array = getTypedArray( interleavedBuffer.type, buffer );
  24760. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  24761. ib.uuid = interleavedBuffer.uuid;
  24762. interleavedBufferMap[ uuid ] = ib;
  24763. return ib;
  24764. }
  24765. function getArrayBuffer( json, uuid ) {
  24766. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  24767. const arrayBuffers = json.arrayBuffers;
  24768. const arrayBuffer = arrayBuffers[ uuid ];
  24769. const ab = new Uint32Array( arrayBuffer ).buffer;
  24770. arrayBufferMap[ uuid ] = ab;
  24771. return ab;
  24772. }
  24773. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  24774. const index = json.data.index;
  24775. if ( index !== undefined ) {
  24776. const typedArray = getTypedArray( index.type, index.array );
  24777. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  24778. }
  24779. const attributes = json.data.attributes;
  24780. for ( const key in attributes ) {
  24781. const attribute = attributes[ key ];
  24782. let bufferAttribute;
  24783. if ( attribute.isInterleavedBufferAttribute ) {
  24784. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  24785. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  24786. } else {
  24787. const typedArray = getTypedArray( attribute.type, attribute.array );
  24788. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  24789. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  24790. }
  24791. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  24792. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  24793. if ( attribute.updateRange !== undefined ) {
  24794. bufferAttribute.updateRange.offset = attribute.updateRange.offset;
  24795. bufferAttribute.updateRange.count = attribute.updateRange.count;
  24796. }
  24797. geometry.setAttribute( key, bufferAttribute );
  24798. }
  24799. const morphAttributes = json.data.morphAttributes;
  24800. if ( morphAttributes ) {
  24801. for ( const key in morphAttributes ) {
  24802. const attributeArray = morphAttributes[ key ];
  24803. const array = [];
  24804. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  24805. const attribute = attributeArray[ i ];
  24806. let bufferAttribute;
  24807. if ( attribute.isInterleavedBufferAttribute ) {
  24808. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  24809. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  24810. } else {
  24811. const typedArray = getTypedArray( attribute.type, attribute.array );
  24812. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  24813. }
  24814. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  24815. array.push( bufferAttribute );
  24816. }
  24817. geometry.morphAttributes[ key ] = array;
  24818. }
  24819. }
  24820. const morphTargetsRelative = json.data.morphTargetsRelative;
  24821. if ( morphTargetsRelative ) {
  24822. geometry.morphTargetsRelative = true;
  24823. }
  24824. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  24825. if ( groups !== undefined ) {
  24826. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  24827. const group = groups[ i ];
  24828. geometry.addGroup( group.start, group.count, group.materialIndex );
  24829. }
  24830. }
  24831. const boundingSphere = json.data.boundingSphere;
  24832. if ( boundingSphere !== undefined ) {
  24833. const center = new Vector3();
  24834. if ( boundingSphere.center !== undefined ) {
  24835. center.fromArray( boundingSphere.center );
  24836. }
  24837. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  24838. }
  24839. if ( json.name ) geometry.name = json.name;
  24840. if ( json.userData ) geometry.userData = json.userData;
  24841. return geometry;
  24842. }
  24843. }
  24844. class ObjectLoader extends Loader {
  24845. constructor( manager ) {
  24846. super( manager );
  24847. }
  24848. load( url, onLoad, onProgress, onError ) {
  24849. const scope = this;
  24850. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  24851. this.resourcePath = this.resourcePath || path;
  24852. const loader = new FileLoader( this.manager );
  24853. loader.setPath( this.path );
  24854. loader.setRequestHeader( this.requestHeader );
  24855. loader.setWithCredentials( this.withCredentials );
  24856. loader.load( url, function ( text ) {
  24857. let json = null;
  24858. try {
  24859. json = JSON.parse( text );
  24860. } catch ( error ) {
  24861. if ( onError !== undefined ) onError( error );
  24862. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  24863. return;
  24864. }
  24865. const metadata = json.metadata;
  24866. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  24867. console.error( 'THREE.ObjectLoader: Can\'t load ' + url );
  24868. return;
  24869. }
  24870. scope.parse( json, onLoad );
  24871. }, onProgress, onError );
  24872. }
  24873. async loadAsync( url, onProgress ) {
  24874. const scope = this;
  24875. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  24876. this.resourcePath = this.resourcePath || path;
  24877. const loader = new FileLoader( this.manager );
  24878. loader.setPath( this.path );
  24879. loader.setRequestHeader( this.requestHeader );
  24880. loader.setWithCredentials( this.withCredentials );
  24881. const text = await loader.loadAsync( url, onProgress );
  24882. const json = JSON.parse( text );
  24883. const metadata = json.metadata;
  24884. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  24885. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  24886. }
  24887. return await scope.parseAsync( json );
  24888. }
  24889. parse( json, onLoad ) {
  24890. const animations = this.parseAnimations( json.animations );
  24891. const shapes = this.parseShapes( json.shapes );
  24892. const geometries = this.parseGeometries( json.geometries, shapes );
  24893. const images = this.parseImages( json.images, function () {
  24894. if ( onLoad !== undefined ) onLoad( object );
  24895. } );
  24896. const textures = this.parseTextures( json.textures, images );
  24897. const materials = this.parseMaterials( json.materials, textures );
  24898. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  24899. const skeletons = this.parseSkeletons( json.skeletons, object );
  24900. this.bindSkeletons( object, skeletons );
  24901. //
  24902. if ( onLoad !== undefined ) {
  24903. let hasImages = false;
  24904. for ( const uuid in images ) {
  24905. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  24906. hasImages = true;
  24907. break;
  24908. }
  24909. }
  24910. if ( hasImages === false ) onLoad( object );
  24911. }
  24912. return object;
  24913. }
  24914. async parseAsync( json ) {
  24915. const animations = this.parseAnimations( json.animations );
  24916. const shapes = this.parseShapes( json.shapes );
  24917. const geometries = this.parseGeometries( json.geometries, shapes );
  24918. const images = await this.parseImagesAsync( json.images );
  24919. const textures = this.parseTextures( json.textures, images );
  24920. const materials = this.parseMaterials( json.materials, textures );
  24921. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  24922. const skeletons = this.parseSkeletons( json.skeletons, object );
  24923. this.bindSkeletons( object, skeletons );
  24924. return object;
  24925. }
  24926. parseShapes( json ) {
  24927. const shapes = {};
  24928. if ( json !== undefined ) {
  24929. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24930. const shape = new Shape().fromJSON( json[ i ] );
  24931. shapes[ shape.uuid ] = shape;
  24932. }
  24933. }
  24934. return shapes;
  24935. }
  24936. parseSkeletons( json, object ) {
  24937. const skeletons = {};
  24938. const bones = {};
  24939. // generate bone lookup table
  24940. object.traverse( function ( child ) {
  24941. if ( child.isBone ) bones[ child.uuid ] = child;
  24942. } );
  24943. // create skeletons
  24944. if ( json !== undefined ) {
  24945. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24946. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  24947. skeletons[ skeleton.uuid ] = skeleton;
  24948. }
  24949. }
  24950. return skeletons;
  24951. }
  24952. parseGeometries( json, shapes ) {
  24953. const geometries = {};
  24954. if ( json !== undefined ) {
  24955. const bufferGeometryLoader = new BufferGeometryLoader();
  24956. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24957. let geometry;
  24958. const data = json[ i ];
  24959. switch ( data.type ) {
  24960. case 'BufferGeometry':
  24961. case 'InstancedBufferGeometry':
  24962. geometry = bufferGeometryLoader.parse( data );
  24963. break;
  24964. default:
  24965. if ( data.type in Geometries ) {
  24966. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  24967. } else {
  24968. console.warn( `THREE.ObjectLoader: Unsupported geometry type "${ data.type }"` );
  24969. }
  24970. }
  24971. geometry.uuid = data.uuid;
  24972. if ( data.name !== undefined ) geometry.name = data.name;
  24973. if ( geometry.isBufferGeometry === true && data.userData !== undefined ) geometry.userData = data.userData;
  24974. geometries[ data.uuid ] = geometry;
  24975. }
  24976. }
  24977. return geometries;
  24978. }
  24979. parseMaterials( json, textures ) {
  24980. const cache = {}; // MultiMaterial
  24981. const materials = {};
  24982. if ( json !== undefined ) {
  24983. const loader = new MaterialLoader();
  24984. loader.setTextures( textures );
  24985. for ( let i = 0, l = json.length; i < l; i ++ ) {
  24986. const data = json[ i ];
  24987. if ( cache[ data.uuid ] === undefined ) {
  24988. cache[ data.uuid ] = loader.parse( data );
  24989. }
  24990. materials[ data.uuid ] = cache[ data.uuid ];
  24991. }
  24992. }
  24993. return materials;
  24994. }
  24995. parseAnimations( json ) {
  24996. const animations = {};
  24997. if ( json !== undefined ) {
  24998. for ( let i = 0; i < json.length; i ++ ) {
  24999. const data = json[ i ];
  25000. const clip = AnimationClip.parse( data );
  25001. animations[ clip.uuid ] = clip;
  25002. }
  25003. }
  25004. return animations;
  25005. }
  25006. parseImages( json, onLoad ) {
  25007. const scope = this;
  25008. const images = {};
  25009. let loader;
  25010. function loadImage( url ) {
  25011. scope.manager.itemStart( url );
  25012. return loader.load( url, function () {
  25013. scope.manager.itemEnd( url );
  25014. }, undefined, function () {
  25015. scope.manager.itemError( url );
  25016. scope.manager.itemEnd( url );
  25017. } );
  25018. }
  25019. function deserializeImage( image ) {
  25020. if ( typeof image === 'string' ) {
  25021. const url = image;
  25022. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25023. return loadImage( path );
  25024. } else {
  25025. if ( image.data ) {
  25026. return {
  25027. data: getTypedArray( image.type, image.data ),
  25028. width: image.width,
  25029. height: image.height
  25030. };
  25031. } else {
  25032. return null;
  25033. }
  25034. }
  25035. }
  25036. if ( json !== undefined && json.length > 0 ) {
  25037. const manager = new LoadingManager( onLoad );
  25038. loader = new ImageLoader( manager );
  25039. loader.setCrossOrigin( this.crossOrigin );
  25040. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25041. const image = json[ i ];
  25042. const url = image.url;
  25043. if ( Array.isArray( url ) ) {
  25044. // load array of images e.g CubeTexture
  25045. const imageArray = [];
  25046. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25047. const currentUrl = url[ j ];
  25048. const deserializedImage = deserializeImage( currentUrl );
  25049. if ( deserializedImage !== null ) {
  25050. if ( deserializedImage instanceof HTMLImageElement ) {
  25051. imageArray.push( deserializedImage );
  25052. } else {
  25053. // special case: handle array of data textures for cube textures
  25054. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25055. }
  25056. }
  25057. }
  25058. images[ image.uuid ] = new Source( imageArray );
  25059. } else {
  25060. // load single image
  25061. const deserializedImage = deserializeImage( image.url );
  25062. images[ image.uuid ] = new Source( deserializedImage );
  25063. }
  25064. }
  25065. }
  25066. return images;
  25067. }
  25068. async parseImagesAsync( json ) {
  25069. const scope = this;
  25070. const images = {};
  25071. let loader;
  25072. async function deserializeImage( image ) {
  25073. if ( typeof image === 'string' ) {
  25074. const url = image;
  25075. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  25076. return await loader.loadAsync( path );
  25077. } else {
  25078. if ( image.data ) {
  25079. return {
  25080. data: getTypedArray( image.type, image.data ),
  25081. width: image.width,
  25082. height: image.height
  25083. };
  25084. } else {
  25085. return null;
  25086. }
  25087. }
  25088. }
  25089. if ( json !== undefined && json.length > 0 ) {
  25090. loader = new ImageLoader( this.manager );
  25091. loader.setCrossOrigin( this.crossOrigin );
  25092. for ( let i = 0, il = json.length; i < il; i ++ ) {
  25093. const image = json[ i ];
  25094. const url = image.url;
  25095. if ( Array.isArray( url ) ) {
  25096. // load array of images e.g CubeTexture
  25097. const imageArray = [];
  25098. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  25099. const currentUrl = url[ j ];
  25100. const deserializedImage = await deserializeImage( currentUrl );
  25101. if ( deserializedImage !== null ) {
  25102. if ( deserializedImage instanceof HTMLImageElement ) {
  25103. imageArray.push( deserializedImage );
  25104. } else {
  25105. // special case: handle array of data textures for cube textures
  25106. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  25107. }
  25108. }
  25109. }
  25110. images[ image.uuid ] = new Source( imageArray );
  25111. } else {
  25112. // load single image
  25113. const deserializedImage = await deserializeImage( image.url );
  25114. images[ image.uuid ] = new Source( deserializedImage );
  25115. }
  25116. }
  25117. }
  25118. return images;
  25119. }
  25120. parseTextures( json, images ) {
  25121. function parseConstant( value, type ) {
  25122. if ( typeof value === 'number' ) return value;
  25123. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  25124. return type[ value ];
  25125. }
  25126. const textures = {};
  25127. if ( json !== undefined ) {
  25128. for ( let i = 0, l = json.length; i < l; i ++ ) {
  25129. const data = json[ i ];
  25130. if ( data.image === undefined ) {
  25131. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  25132. }
  25133. if ( images[ data.image ] === undefined ) {
  25134. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  25135. }
  25136. const source = images[ data.image ];
  25137. const image = source.data;
  25138. let texture;
  25139. if ( Array.isArray( image ) ) {
  25140. texture = new CubeTexture();
  25141. if ( image.length === 6 ) texture.needsUpdate = true;
  25142. } else {
  25143. if ( image && image.data ) {
  25144. texture = new DataTexture();
  25145. } else {
  25146. texture = new Texture();
  25147. }
  25148. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  25149. }
  25150. texture.source = source;
  25151. texture.uuid = data.uuid;
  25152. if ( data.name !== undefined ) texture.name = data.name;
  25153. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  25154. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  25155. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  25156. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  25157. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  25158. if ( data.wrap !== undefined ) {
  25159. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  25160. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  25161. }
  25162. if ( data.format !== undefined ) texture.format = data.format;
  25163. if ( data.type !== undefined ) texture.type = data.type;
  25164. if ( data.encoding !== undefined ) texture.encoding = data.encoding;
  25165. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  25166. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  25167. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  25168. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  25169. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  25170. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  25171. if ( data.userData !== undefined ) texture.userData = data.userData;
  25172. textures[ data.uuid ] = texture;
  25173. }
  25174. }
  25175. return textures;
  25176. }
  25177. parseObject( data, geometries, materials, textures, animations ) {
  25178. let object;
  25179. function getGeometry( name ) {
  25180. if ( geometries[ name ] === undefined ) {
  25181. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  25182. }
  25183. return geometries[ name ];
  25184. }
  25185. function getMaterial( name ) {
  25186. if ( name === undefined ) return undefined;
  25187. if ( Array.isArray( name ) ) {
  25188. const array = [];
  25189. for ( let i = 0, l = name.length; i < l; i ++ ) {
  25190. const uuid = name[ i ];
  25191. if ( materials[ uuid ] === undefined ) {
  25192. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  25193. }
  25194. array.push( materials[ uuid ] );
  25195. }
  25196. return array;
  25197. }
  25198. if ( materials[ name ] === undefined ) {
  25199. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  25200. }
  25201. return materials[ name ];
  25202. }
  25203. function getTexture( uuid ) {
  25204. if ( textures[ uuid ] === undefined ) {
  25205. console.warn( 'THREE.ObjectLoader: Undefined texture', uuid );
  25206. }
  25207. return textures[ uuid ];
  25208. }
  25209. let geometry, material;
  25210. switch ( data.type ) {
  25211. case 'Scene':
  25212. object = new Scene();
  25213. if ( data.background !== undefined ) {
  25214. if ( Number.isInteger( data.background ) ) {
  25215. object.background = new Color( data.background );
  25216. } else {
  25217. object.background = getTexture( data.background );
  25218. }
  25219. }
  25220. if ( data.environment !== undefined ) {
  25221. object.environment = getTexture( data.environment );
  25222. }
  25223. if ( data.fog !== undefined ) {
  25224. if ( data.fog.type === 'Fog' ) {
  25225. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  25226. } else if ( data.fog.type === 'FogExp2' ) {
  25227. object.fog = new FogExp2( data.fog.color, data.fog.density );
  25228. }
  25229. }
  25230. break;
  25231. case 'PerspectiveCamera':
  25232. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  25233. if ( data.focus !== undefined ) object.focus = data.focus;
  25234. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25235. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  25236. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  25237. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25238. break;
  25239. case 'OrthographicCamera':
  25240. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  25241. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  25242. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  25243. break;
  25244. case 'AmbientLight':
  25245. object = new AmbientLight( data.color, data.intensity );
  25246. break;
  25247. case 'DirectionalLight':
  25248. object = new DirectionalLight( data.color, data.intensity );
  25249. break;
  25250. case 'PointLight':
  25251. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  25252. break;
  25253. case 'RectAreaLight':
  25254. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  25255. break;
  25256. case 'SpotLight':
  25257. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  25258. break;
  25259. case 'HemisphereLight':
  25260. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  25261. break;
  25262. case 'LightProbe':
  25263. object = new LightProbe().fromJSON( data );
  25264. break;
  25265. case 'SkinnedMesh':
  25266. geometry = getGeometry( data.geometry );
  25267. material = getMaterial( data.material );
  25268. object = new SkinnedMesh( geometry, material );
  25269. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  25270. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  25271. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  25272. break;
  25273. case 'Mesh':
  25274. geometry = getGeometry( data.geometry );
  25275. material = getMaterial( data.material );
  25276. object = new Mesh( geometry, material );
  25277. break;
  25278. case 'InstancedMesh':
  25279. geometry = getGeometry( data.geometry );
  25280. material = getMaterial( data.material );
  25281. const count = data.count;
  25282. const instanceMatrix = data.instanceMatrix;
  25283. const instanceColor = data.instanceColor;
  25284. object = new InstancedMesh( geometry, material, count );
  25285. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  25286. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  25287. break;
  25288. case 'LOD':
  25289. object = new LOD();
  25290. break;
  25291. case 'Line':
  25292. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  25293. break;
  25294. case 'LineLoop':
  25295. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  25296. break;
  25297. case 'LineSegments':
  25298. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  25299. break;
  25300. case 'PointCloud':
  25301. case 'Points':
  25302. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  25303. break;
  25304. case 'Sprite':
  25305. object = new Sprite( getMaterial( data.material ) );
  25306. break;
  25307. case 'Group':
  25308. object = new Group();
  25309. break;
  25310. case 'Bone':
  25311. object = new Bone();
  25312. break;
  25313. default:
  25314. object = new Object3D();
  25315. }
  25316. object.uuid = data.uuid;
  25317. if ( data.name !== undefined ) object.name = data.name;
  25318. if ( data.matrix !== undefined ) {
  25319. object.matrix.fromArray( data.matrix );
  25320. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  25321. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  25322. } else {
  25323. if ( data.position !== undefined ) object.position.fromArray( data.position );
  25324. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  25325. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  25326. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  25327. }
  25328. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  25329. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  25330. if ( data.shadow ) {
  25331. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  25332. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  25333. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  25334. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  25335. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  25336. }
  25337. if ( data.visible !== undefined ) object.visible = data.visible;
  25338. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  25339. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  25340. if ( data.userData !== undefined ) object.userData = data.userData;
  25341. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  25342. if ( data.children !== undefined ) {
  25343. const children = data.children;
  25344. for ( let i = 0; i < children.length; i ++ ) {
  25345. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  25346. }
  25347. }
  25348. if ( data.animations !== undefined ) {
  25349. const objectAnimations = data.animations;
  25350. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  25351. const uuid = objectAnimations[ i ];
  25352. object.animations.push( animations[ uuid ] );
  25353. }
  25354. }
  25355. if ( data.type === 'LOD' ) {
  25356. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  25357. const levels = data.levels;
  25358. for ( let l = 0; l < levels.length; l ++ ) {
  25359. const level = levels[ l ];
  25360. const child = object.getObjectByProperty( 'uuid', level.object );
  25361. if ( child !== undefined ) {
  25362. object.addLevel( child, level.distance );
  25363. }
  25364. }
  25365. }
  25366. return object;
  25367. }
  25368. bindSkeletons( object, skeletons ) {
  25369. if ( Object.keys( skeletons ).length === 0 ) return;
  25370. object.traverse( function ( child ) {
  25371. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  25372. const skeleton = skeletons[ child.skeleton ];
  25373. if ( skeleton === undefined ) {
  25374. console.warn( 'THREE.ObjectLoader: No skeleton found with UUID:', child.skeleton );
  25375. } else {
  25376. child.bind( skeleton, child.bindMatrix );
  25377. }
  25378. }
  25379. } );
  25380. }
  25381. }
  25382. const TEXTURE_MAPPING = {
  25383. UVMapping: UVMapping,
  25384. CubeReflectionMapping: CubeReflectionMapping,
  25385. CubeRefractionMapping: CubeRefractionMapping,
  25386. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  25387. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  25388. CubeUVReflectionMapping: CubeUVReflectionMapping
  25389. };
  25390. const TEXTURE_WRAPPING = {
  25391. RepeatWrapping: RepeatWrapping,
  25392. ClampToEdgeWrapping: ClampToEdgeWrapping,
  25393. MirroredRepeatWrapping: MirroredRepeatWrapping
  25394. };
  25395. const TEXTURE_FILTER = {
  25396. NearestFilter: NearestFilter,
  25397. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  25398. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  25399. LinearFilter: LinearFilter,
  25400. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  25401. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  25402. };
  25403. class ImageBitmapLoader extends Loader {
  25404. constructor( manager ) {
  25405. super( manager );
  25406. this.isImageBitmapLoader = true;
  25407. if ( typeof createImageBitmap === 'undefined' ) {
  25408. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  25409. }
  25410. if ( typeof fetch === 'undefined' ) {
  25411. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  25412. }
  25413. this.options = { premultiplyAlpha: 'none' };
  25414. }
  25415. setOptions( options ) {
  25416. this.options = options;
  25417. return this;
  25418. }
  25419. load( url, onLoad, onProgress, onError ) {
  25420. if ( url === undefined ) url = '';
  25421. if ( this.path !== undefined ) url = this.path + url;
  25422. url = this.manager.resolveURL( url );
  25423. const scope = this;
  25424. const cached = Cache.get( url );
  25425. if ( cached !== undefined ) {
  25426. scope.manager.itemStart( url );
  25427. setTimeout( function () {
  25428. if ( onLoad ) onLoad( cached );
  25429. scope.manager.itemEnd( url );
  25430. }, 0 );
  25431. return cached;
  25432. }
  25433. const fetchOptions = {};
  25434. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  25435. fetchOptions.headers = this.requestHeader;
  25436. fetch( url, fetchOptions ).then( function ( res ) {
  25437. return res.blob();
  25438. } ).then( function ( blob ) {
  25439. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  25440. } ).then( function ( imageBitmap ) {
  25441. Cache.add( url, imageBitmap );
  25442. if ( onLoad ) onLoad( imageBitmap );
  25443. scope.manager.itemEnd( url );
  25444. } ).catch( function ( e ) {
  25445. if ( onError ) onError( e );
  25446. scope.manager.itemError( url );
  25447. scope.manager.itemEnd( url );
  25448. } );
  25449. scope.manager.itemStart( url );
  25450. }
  25451. }
  25452. let _context;
  25453. const AudioContext = {
  25454. getContext: function () {
  25455. if ( _context === undefined ) {
  25456. _context = new ( window.AudioContext || window.webkitAudioContext )();
  25457. }
  25458. return _context;
  25459. },
  25460. setContext: function ( value ) {
  25461. _context = value;
  25462. }
  25463. };
  25464. class AudioLoader extends Loader {
  25465. constructor( manager ) {
  25466. super( manager );
  25467. }
  25468. load( url, onLoad, onProgress, onError ) {
  25469. const scope = this;
  25470. const loader = new FileLoader( this.manager );
  25471. loader.setResponseType( 'arraybuffer' );
  25472. loader.setPath( this.path );
  25473. loader.setRequestHeader( this.requestHeader );
  25474. loader.setWithCredentials( this.withCredentials );
  25475. loader.load( url, function ( buffer ) {
  25476. try {
  25477. // Create a copy of the buffer. The `decodeAudioData` method
  25478. // detaches the buffer when complete, preventing reuse.
  25479. const bufferCopy = buffer.slice( 0 );
  25480. const context = AudioContext.getContext();
  25481. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  25482. onLoad( audioBuffer );
  25483. } );
  25484. } catch ( e ) {
  25485. if ( onError ) {
  25486. onError( e );
  25487. } else {
  25488. console.error( e );
  25489. }
  25490. scope.manager.itemError( url );
  25491. }
  25492. }, onProgress, onError );
  25493. }
  25494. }
  25495. class HemisphereLightProbe extends LightProbe {
  25496. constructor( skyColor, groundColor, intensity = 1 ) {
  25497. super( undefined, intensity );
  25498. this.isHemisphereLightProbe = true;
  25499. const color1 = new Color().set( skyColor );
  25500. const color2 = new Color().set( groundColor );
  25501. const sky = new Vector3( color1.r, color1.g, color1.b );
  25502. const ground = new Vector3( color2.r, color2.g, color2.b );
  25503. // without extra factor of PI in the shader, should = 1 / Math.sqrt( Math.PI );
  25504. const c0 = Math.sqrt( Math.PI );
  25505. const c1 = c0 * Math.sqrt( 0.75 );
  25506. this.sh.coefficients[ 0 ].copy( sky ).add( ground ).multiplyScalar( c0 );
  25507. this.sh.coefficients[ 1 ].copy( sky ).sub( ground ).multiplyScalar( c1 );
  25508. }
  25509. }
  25510. class AmbientLightProbe extends LightProbe {
  25511. constructor( color, intensity = 1 ) {
  25512. super( undefined, intensity );
  25513. this.isAmbientLightProbe = true;
  25514. const color1 = new Color().set( color );
  25515. // without extra factor of PI in the shader, would be 2 / Math.sqrt( Math.PI );
  25516. this.sh.coefficients[ 0 ].set( color1.r, color1.g, color1.b ).multiplyScalar( 2 * Math.sqrt( Math.PI ) );
  25517. }
  25518. }
  25519. const _eyeRight = /*@__PURE__*/ new Matrix4();
  25520. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  25521. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  25522. class StereoCamera {
  25523. constructor() {
  25524. this.type = 'StereoCamera';
  25525. this.aspect = 1;
  25526. this.eyeSep = 0.064;
  25527. this.cameraL = new PerspectiveCamera();
  25528. this.cameraL.layers.enable( 1 );
  25529. this.cameraL.matrixAutoUpdate = false;
  25530. this.cameraR = new PerspectiveCamera();
  25531. this.cameraR.layers.enable( 2 );
  25532. this.cameraR.matrixAutoUpdate = false;
  25533. this._cache = {
  25534. focus: null,
  25535. fov: null,
  25536. aspect: null,
  25537. near: null,
  25538. far: null,
  25539. zoom: null,
  25540. eyeSep: null
  25541. };
  25542. }
  25543. update( camera ) {
  25544. const cache = this._cache;
  25545. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  25546. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  25547. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  25548. if ( needsUpdate ) {
  25549. cache.focus = camera.focus;
  25550. cache.fov = camera.fov;
  25551. cache.aspect = camera.aspect * this.aspect;
  25552. cache.near = camera.near;
  25553. cache.far = camera.far;
  25554. cache.zoom = camera.zoom;
  25555. cache.eyeSep = this.eyeSep;
  25556. // Off-axis stereoscopic effect based on
  25557. // http://paulbourke.net/stereographics/stereorender/
  25558. _projectionMatrix.copy( camera.projectionMatrix );
  25559. const eyeSepHalf = cache.eyeSep / 2;
  25560. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  25561. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  25562. let xmin, xmax;
  25563. // translate xOffset
  25564. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  25565. _eyeRight.elements[ 12 ] = eyeSepHalf;
  25566. // for left eye
  25567. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  25568. xmax = ymax * cache.aspect + eyeSepOnProjection;
  25569. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25570. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25571. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  25572. // for right eye
  25573. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  25574. xmax = ymax * cache.aspect - eyeSepOnProjection;
  25575. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  25576. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25577. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  25578. }
  25579. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  25580. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  25581. }
  25582. }
  25583. class Clock {
  25584. constructor( autoStart = true ) {
  25585. this.autoStart = autoStart;
  25586. this.startTime = 0;
  25587. this.oldTime = 0;
  25588. this.elapsedTime = 0;
  25589. this.running = false;
  25590. }
  25591. start() {
  25592. this.startTime = now();
  25593. this.oldTime = this.startTime;
  25594. this.elapsedTime = 0;
  25595. this.running = true;
  25596. }
  25597. stop() {
  25598. this.getElapsedTime();
  25599. this.running = false;
  25600. this.autoStart = false;
  25601. }
  25602. getElapsedTime() {
  25603. this.getDelta();
  25604. return this.elapsedTime;
  25605. }
  25606. getDelta() {
  25607. let diff = 0;
  25608. if ( this.autoStart && ! this.running ) {
  25609. this.start();
  25610. return 0;
  25611. }
  25612. if ( this.running ) {
  25613. const newTime = now();
  25614. diff = ( newTime - this.oldTime ) / 1000;
  25615. this.oldTime = newTime;
  25616. this.elapsedTime += diff;
  25617. }
  25618. return diff;
  25619. }
  25620. }
  25621. function now() {
  25622. return ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  25623. }
  25624. const _position$1 = /*@__PURE__*/ new Vector3();
  25625. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  25626. const _scale$1 = /*@__PURE__*/ new Vector3();
  25627. const _orientation$1 = /*@__PURE__*/ new Vector3();
  25628. class AudioListener extends Object3D {
  25629. constructor() {
  25630. super();
  25631. this.type = 'AudioListener';
  25632. this.context = AudioContext.getContext();
  25633. this.gain = this.context.createGain();
  25634. this.gain.connect( this.context.destination );
  25635. this.filter = null;
  25636. this.timeDelta = 0;
  25637. // private
  25638. this._clock = new Clock();
  25639. }
  25640. getInput() {
  25641. return this.gain;
  25642. }
  25643. removeFilter() {
  25644. if ( this.filter !== null ) {
  25645. this.gain.disconnect( this.filter );
  25646. this.filter.disconnect( this.context.destination );
  25647. this.gain.connect( this.context.destination );
  25648. this.filter = null;
  25649. }
  25650. return this;
  25651. }
  25652. getFilter() {
  25653. return this.filter;
  25654. }
  25655. setFilter( value ) {
  25656. if ( this.filter !== null ) {
  25657. this.gain.disconnect( this.filter );
  25658. this.filter.disconnect( this.context.destination );
  25659. } else {
  25660. this.gain.disconnect( this.context.destination );
  25661. }
  25662. this.filter = value;
  25663. this.gain.connect( this.filter );
  25664. this.filter.connect( this.context.destination );
  25665. return this;
  25666. }
  25667. getMasterVolume() {
  25668. return this.gain.gain.value;
  25669. }
  25670. setMasterVolume( value ) {
  25671. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  25672. return this;
  25673. }
  25674. updateMatrixWorld( force ) {
  25675. super.updateMatrixWorld( force );
  25676. const listener = this.context.listener;
  25677. const up = this.up;
  25678. this.timeDelta = this._clock.getDelta();
  25679. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  25680. _orientation$1.set( 0, 0, - 1 ).applyQuaternion( _quaternion$1 );
  25681. if ( listener.positionX ) {
  25682. // code path for Chrome (see #14393)
  25683. const endTime = this.context.currentTime + this.timeDelta;
  25684. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  25685. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  25686. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  25687. listener.forwardX.linearRampToValueAtTime( _orientation$1.x, endTime );
  25688. listener.forwardY.linearRampToValueAtTime( _orientation$1.y, endTime );
  25689. listener.forwardZ.linearRampToValueAtTime( _orientation$1.z, endTime );
  25690. listener.upX.linearRampToValueAtTime( up.x, endTime );
  25691. listener.upY.linearRampToValueAtTime( up.y, endTime );
  25692. listener.upZ.linearRampToValueAtTime( up.z, endTime );
  25693. } else {
  25694. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  25695. listener.setOrientation( _orientation$1.x, _orientation$1.y, _orientation$1.z, up.x, up.y, up.z );
  25696. }
  25697. }
  25698. }
  25699. class Audio extends Object3D {
  25700. constructor( listener ) {
  25701. super();
  25702. this.type = 'Audio';
  25703. this.listener = listener;
  25704. this.context = listener.context;
  25705. this.gain = this.context.createGain();
  25706. this.gain.connect( listener.getInput() );
  25707. this.autoplay = false;
  25708. this.buffer = null;
  25709. this.detune = 0;
  25710. this.loop = false;
  25711. this.loopStart = 0;
  25712. this.loopEnd = 0;
  25713. this.offset = 0;
  25714. this.duration = undefined;
  25715. this.playbackRate = 1;
  25716. this.isPlaying = false;
  25717. this.hasPlaybackControl = true;
  25718. this.source = null;
  25719. this.sourceType = 'empty';
  25720. this._startedAt = 0;
  25721. this._progress = 0;
  25722. this._connected = false;
  25723. this.filters = [];
  25724. }
  25725. getOutput() {
  25726. return this.gain;
  25727. }
  25728. setNodeSource( audioNode ) {
  25729. this.hasPlaybackControl = false;
  25730. this.sourceType = 'audioNode';
  25731. this.source = audioNode;
  25732. this.connect();
  25733. return this;
  25734. }
  25735. setMediaElementSource( mediaElement ) {
  25736. this.hasPlaybackControl = false;
  25737. this.sourceType = 'mediaNode';
  25738. this.source = this.context.createMediaElementSource( mediaElement );
  25739. this.connect();
  25740. return this;
  25741. }
  25742. setMediaStreamSource( mediaStream ) {
  25743. this.hasPlaybackControl = false;
  25744. this.sourceType = 'mediaStreamNode';
  25745. this.source = this.context.createMediaStreamSource( mediaStream );
  25746. this.connect();
  25747. return this;
  25748. }
  25749. setBuffer( audioBuffer ) {
  25750. this.buffer = audioBuffer;
  25751. this.sourceType = 'buffer';
  25752. if ( this.autoplay ) this.play();
  25753. return this;
  25754. }
  25755. play( delay = 0 ) {
  25756. if ( this.isPlaying === true ) {
  25757. console.warn( 'THREE.Audio: Audio is already playing.' );
  25758. return;
  25759. }
  25760. if ( this.hasPlaybackControl === false ) {
  25761. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25762. return;
  25763. }
  25764. this._startedAt = this.context.currentTime + delay;
  25765. const source = this.context.createBufferSource();
  25766. source.buffer = this.buffer;
  25767. source.loop = this.loop;
  25768. source.loopStart = this.loopStart;
  25769. source.loopEnd = this.loopEnd;
  25770. source.onended = this.onEnded.bind( this );
  25771. source.start( this._startedAt, this._progress + this.offset, this.duration );
  25772. this.isPlaying = true;
  25773. this.source = source;
  25774. this.setDetune( this.detune );
  25775. this.setPlaybackRate( this.playbackRate );
  25776. return this.connect();
  25777. }
  25778. pause() {
  25779. if ( this.hasPlaybackControl === false ) {
  25780. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25781. return;
  25782. }
  25783. if ( this.isPlaying === true ) {
  25784. // update current progress
  25785. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  25786. if ( this.loop === true ) {
  25787. // ensure _progress does not exceed duration with looped audios
  25788. this._progress = this._progress % ( this.duration || this.buffer.duration );
  25789. }
  25790. this.source.stop();
  25791. this.source.onended = null;
  25792. this.isPlaying = false;
  25793. }
  25794. return this;
  25795. }
  25796. stop() {
  25797. if ( this.hasPlaybackControl === false ) {
  25798. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25799. return;
  25800. }
  25801. this._progress = 0;
  25802. this.source.stop();
  25803. this.source.onended = null;
  25804. this.isPlaying = false;
  25805. return this;
  25806. }
  25807. connect() {
  25808. if ( this.filters.length > 0 ) {
  25809. this.source.connect( this.filters[ 0 ] );
  25810. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  25811. this.filters[ i - 1 ].connect( this.filters[ i ] );
  25812. }
  25813. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  25814. } else {
  25815. this.source.connect( this.getOutput() );
  25816. }
  25817. this._connected = true;
  25818. return this;
  25819. }
  25820. disconnect() {
  25821. if ( this.filters.length > 0 ) {
  25822. this.source.disconnect( this.filters[ 0 ] );
  25823. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  25824. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  25825. }
  25826. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  25827. } else {
  25828. this.source.disconnect( this.getOutput() );
  25829. }
  25830. this._connected = false;
  25831. return this;
  25832. }
  25833. getFilters() {
  25834. return this.filters;
  25835. }
  25836. setFilters( value ) {
  25837. if ( ! value ) value = [];
  25838. if ( this._connected === true ) {
  25839. this.disconnect();
  25840. this.filters = value.slice();
  25841. this.connect();
  25842. } else {
  25843. this.filters = value.slice();
  25844. }
  25845. return this;
  25846. }
  25847. setDetune( value ) {
  25848. this.detune = value;
  25849. if ( this.source.detune === undefined ) return; // only set detune when available
  25850. if ( this.isPlaying === true ) {
  25851. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  25852. }
  25853. return this;
  25854. }
  25855. getDetune() {
  25856. return this.detune;
  25857. }
  25858. getFilter() {
  25859. return this.getFilters()[ 0 ];
  25860. }
  25861. setFilter( filter ) {
  25862. return this.setFilters( filter ? [ filter ] : [] );
  25863. }
  25864. setPlaybackRate( value ) {
  25865. if ( this.hasPlaybackControl === false ) {
  25866. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25867. return;
  25868. }
  25869. this.playbackRate = value;
  25870. if ( this.isPlaying === true ) {
  25871. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  25872. }
  25873. return this;
  25874. }
  25875. getPlaybackRate() {
  25876. return this.playbackRate;
  25877. }
  25878. onEnded() {
  25879. this.isPlaying = false;
  25880. }
  25881. getLoop() {
  25882. if ( this.hasPlaybackControl === false ) {
  25883. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25884. return false;
  25885. }
  25886. return this.loop;
  25887. }
  25888. setLoop( value ) {
  25889. if ( this.hasPlaybackControl === false ) {
  25890. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25891. return;
  25892. }
  25893. this.loop = value;
  25894. if ( this.isPlaying === true ) {
  25895. this.source.loop = this.loop;
  25896. }
  25897. return this;
  25898. }
  25899. setLoopStart( value ) {
  25900. this.loopStart = value;
  25901. return this;
  25902. }
  25903. setLoopEnd( value ) {
  25904. this.loopEnd = value;
  25905. return this;
  25906. }
  25907. getVolume() {
  25908. return this.gain.gain.value;
  25909. }
  25910. setVolume( value ) {
  25911. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  25912. return this;
  25913. }
  25914. }
  25915. const _position = /*@__PURE__*/ new Vector3();
  25916. const _quaternion = /*@__PURE__*/ new Quaternion();
  25917. const _scale = /*@__PURE__*/ new Vector3();
  25918. const _orientation = /*@__PURE__*/ new Vector3();
  25919. class PositionalAudio extends Audio {
  25920. constructor( listener ) {
  25921. super( listener );
  25922. this.panner = this.context.createPanner();
  25923. this.panner.panningModel = 'HRTF';
  25924. this.panner.connect( this.gain );
  25925. }
  25926. disconnect() {
  25927. super.disconnect();
  25928. this.panner.disconnect( this.gain );
  25929. }
  25930. getOutput() {
  25931. return this.panner;
  25932. }
  25933. getRefDistance() {
  25934. return this.panner.refDistance;
  25935. }
  25936. setRefDistance( value ) {
  25937. this.panner.refDistance = value;
  25938. return this;
  25939. }
  25940. getRolloffFactor() {
  25941. return this.panner.rolloffFactor;
  25942. }
  25943. setRolloffFactor( value ) {
  25944. this.panner.rolloffFactor = value;
  25945. return this;
  25946. }
  25947. getDistanceModel() {
  25948. return this.panner.distanceModel;
  25949. }
  25950. setDistanceModel( value ) {
  25951. this.panner.distanceModel = value;
  25952. return this;
  25953. }
  25954. getMaxDistance() {
  25955. return this.panner.maxDistance;
  25956. }
  25957. setMaxDistance( value ) {
  25958. this.panner.maxDistance = value;
  25959. return this;
  25960. }
  25961. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  25962. this.panner.coneInnerAngle = coneInnerAngle;
  25963. this.panner.coneOuterAngle = coneOuterAngle;
  25964. this.panner.coneOuterGain = coneOuterGain;
  25965. return this;
  25966. }
  25967. updateMatrixWorld( force ) {
  25968. super.updateMatrixWorld( force );
  25969. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  25970. this.matrixWorld.decompose( _position, _quaternion, _scale );
  25971. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  25972. const panner = this.panner;
  25973. if ( panner.positionX ) {
  25974. // code path for Chrome and Firefox (see #14393)
  25975. const endTime = this.context.currentTime + this.listener.timeDelta;
  25976. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  25977. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  25978. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  25979. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  25980. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  25981. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  25982. } else {
  25983. panner.setPosition( _position.x, _position.y, _position.z );
  25984. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  25985. }
  25986. }
  25987. }
  25988. class AudioAnalyser {
  25989. constructor( audio, fftSize = 2048 ) {
  25990. this.analyser = audio.context.createAnalyser();
  25991. this.analyser.fftSize = fftSize;
  25992. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  25993. audio.getOutput().connect( this.analyser );
  25994. }
  25995. getFrequencyData() {
  25996. this.analyser.getByteFrequencyData( this.data );
  25997. return this.data;
  25998. }
  25999. getAverageFrequency() {
  26000. let value = 0;
  26001. const data = this.getFrequencyData();
  26002. for ( let i = 0; i < data.length; i ++ ) {
  26003. value += data[ i ];
  26004. }
  26005. return value / data.length;
  26006. }
  26007. }
  26008. class PropertyMixer {
  26009. constructor( binding, typeName, valueSize ) {
  26010. this.binding = binding;
  26011. this.valueSize = valueSize;
  26012. let mixFunction,
  26013. mixFunctionAdditive,
  26014. setIdentity;
  26015. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  26016. //
  26017. // interpolators can use .buffer as their .result
  26018. // the data then goes to 'incoming'
  26019. //
  26020. // 'accu0' and 'accu1' are used frame-interleaved for
  26021. // the cumulative result and are compared to detect
  26022. // changes
  26023. //
  26024. // 'orig' stores the original state of the property
  26025. //
  26026. // 'add' is used for additive cumulative results
  26027. //
  26028. // 'work' is optional and is only present for quaternion types. It is used
  26029. // to store intermediate quaternion multiplication results
  26030. switch ( typeName ) {
  26031. case 'quaternion':
  26032. mixFunction = this._slerp;
  26033. mixFunctionAdditive = this._slerpAdditive;
  26034. setIdentity = this._setAdditiveIdentityQuaternion;
  26035. this.buffer = new Float64Array( valueSize * 6 );
  26036. this._workIndex = 5;
  26037. break;
  26038. case 'string':
  26039. case 'bool':
  26040. mixFunction = this._select;
  26041. // Use the regular mix function and for additive on these types,
  26042. // additive is not relevant for non-numeric types
  26043. mixFunctionAdditive = this._select;
  26044. setIdentity = this._setAdditiveIdentityOther;
  26045. this.buffer = new Array( valueSize * 5 );
  26046. break;
  26047. default:
  26048. mixFunction = this._lerp;
  26049. mixFunctionAdditive = this._lerpAdditive;
  26050. setIdentity = this._setAdditiveIdentityNumeric;
  26051. this.buffer = new Float64Array( valueSize * 5 );
  26052. }
  26053. this._mixBufferRegion = mixFunction;
  26054. this._mixBufferRegionAdditive = mixFunctionAdditive;
  26055. this._setIdentity = setIdentity;
  26056. this._origIndex = 3;
  26057. this._addIndex = 4;
  26058. this.cumulativeWeight = 0;
  26059. this.cumulativeWeightAdditive = 0;
  26060. this.useCount = 0;
  26061. this.referenceCount = 0;
  26062. }
  26063. // accumulate data in the 'incoming' region into 'accu<i>'
  26064. accumulate( accuIndex, weight ) {
  26065. // note: happily accumulating nothing when weight = 0, the caller knows
  26066. // the weight and shouldn't have made the call in the first place
  26067. const buffer = this.buffer,
  26068. stride = this.valueSize,
  26069. offset = accuIndex * stride + stride;
  26070. let currentWeight = this.cumulativeWeight;
  26071. if ( currentWeight === 0 ) {
  26072. // accuN := incoming * weight
  26073. for ( let i = 0; i !== stride; ++ i ) {
  26074. buffer[ offset + i ] = buffer[ i ];
  26075. }
  26076. currentWeight = weight;
  26077. } else {
  26078. // accuN := accuN + incoming * weight
  26079. currentWeight += weight;
  26080. const mix = weight / currentWeight;
  26081. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  26082. }
  26083. this.cumulativeWeight = currentWeight;
  26084. }
  26085. // accumulate data in the 'incoming' region into 'add'
  26086. accumulateAdditive( weight ) {
  26087. const buffer = this.buffer,
  26088. stride = this.valueSize,
  26089. offset = stride * this._addIndex;
  26090. if ( this.cumulativeWeightAdditive === 0 ) {
  26091. // add = identity
  26092. this._setIdentity();
  26093. }
  26094. // add := add + incoming * weight
  26095. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  26096. this.cumulativeWeightAdditive += weight;
  26097. }
  26098. // apply the state of 'accu<i>' to the binding when accus differ
  26099. apply( accuIndex ) {
  26100. const stride = this.valueSize,
  26101. buffer = this.buffer,
  26102. offset = accuIndex * stride + stride,
  26103. weight = this.cumulativeWeight,
  26104. weightAdditive = this.cumulativeWeightAdditive,
  26105. binding = this.binding;
  26106. this.cumulativeWeight = 0;
  26107. this.cumulativeWeightAdditive = 0;
  26108. if ( weight < 1 ) {
  26109. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26110. const originalValueOffset = stride * this._origIndex;
  26111. this._mixBufferRegion(
  26112. buffer, offset, originalValueOffset, 1 - weight, stride );
  26113. }
  26114. if ( weightAdditive > 0 ) {
  26115. // accuN := accuN + additive accuN
  26116. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  26117. }
  26118. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  26119. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  26120. // value has changed -> update scene graph
  26121. binding.setValue( buffer, offset );
  26122. break;
  26123. }
  26124. }
  26125. }
  26126. // remember the state of the bound property and copy it to both accus
  26127. saveOriginalState() {
  26128. const binding = this.binding;
  26129. const buffer = this.buffer,
  26130. stride = this.valueSize,
  26131. originalValueOffset = stride * this._origIndex;
  26132. binding.getValue( buffer, originalValueOffset );
  26133. // accu[0..1] := orig -- initially detect changes against the original
  26134. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  26135. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  26136. }
  26137. // Add to identity for additive
  26138. this._setIdentity();
  26139. this.cumulativeWeight = 0;
  26140. this.cumulativeWeightAdditive = 0;
  26141. }
  26142. // apply the state previously taken via 'saveOriginalState' to the binding
  26143. restoreOriginalState() {
  26144. const originalValueOffset = this.valueSize * 3;
  26145. this.binding.setValue( this.buffer, originalValueOffset );
  26146. }
  26147. _setAdditiveIdentityNumeric() {
  26148. const startIndex = this._addIndex * this.valueSize;
  26149. const endIndex = startIndex + this.valueSize;
  26150. for ( let i = startIndex; i < endIndex; i ++ ) {
  26151. this.buffer[ i ] = 0;
  26152. }
  26153. }
  26154. _setAdditiveIdentityQuaternion() {
  26155. this._setAdditiveIdentityNumeric();
  26156. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  26157. }
  26158. _setAdditiveIdentityOther() {
  26159. const startIndex = this._origIndex * this.valueSize;
  26160. const targetIndex = this._addIndex * this.valueSize;
  26161. for ( let i = 0; i < this.valueSize; i ++ ) {
  26162. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  26163. }
  26164. }
  26165. // mix functions
  26166. _select( buffer, dstOffset, srcOffset, t, stride ) {
  26167. if ( t >= 0.5 ) {
  26168. for ( let i = 0; i !== stride; ++ i ) {
  26169. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  26170. }
  26171. }
  26172. }
  26173. _slerp( buffer, dstOffset, srcOffset, t ) {
  26174. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  26175. }
  26176. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  26177. const workOffset = this._workIndex * stride;
  26178. // Store result in intermediate buffer offset
  26179. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  26180. // Slerp to the intermediate result
  26181. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  26182. }
  26183. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  26184. const s = 1 - t;
  26185. for ( let i = 0; i !== stride; ++ i ) {
  26186. const j = dstOffset + i;
  26187. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  26188. }
  26189. }
  26190. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  26191. for ( let i = 0; i !== stride; ++ i ) {
  26192. const j = dstOffset + i;
  26193. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  26194. }
  26195. }
  26196. }
  26197. // Characters [].:/ are reserved for track binding syntax.
  26198. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  26199. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  26200. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  26201. // only latin characters, and the unicode \p{L} is not yet supported. So
  26202. // instead, we exclude reserved characters and match everything else.
  26203. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  26204. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  26205. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  26206. // be matched to parse the rest of the track name.
  26207. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  26208. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  26209. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  26210. // Object on target node, and accessor. May not contain reserved
  26211. // characters. Accessor may contain any character except closing bracket.
  26212. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  26213. // Property and accessor. May not contain reserved characters. Accessor may
  26214. // contain any non-bracket characters.
  26215. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  26216. const _trackRe = new RegExp( ''
  26217. + '^'
  26218. + _directoryRe
  26219. + _nodeRe
  26220. + _objectRe
  26221. + _propertyRe
  26222. + '$'
  26223. );
  26224. const _supportedObjectNames = [ 'material', 'materials', 'bones' ];
  26225. class Composite {
  26226. constructor( targetGroup, path, optionalParsedPath ) {
  26227. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  26228. this._targetGroup = targetGroup;
  26229. this._bindings = targetGroup.subscribe_( path, parsedPath );
  26230. }
  26231. getValue( array, offset ) {
  26232. this.bind(); // bind all binding
  26233. const firstValidIndex = this._targetGroup.nCachedObjects_,
  26234. binding = this._bindings[ firstValidIndex ];
  26235. // and only call .getValue on the first
  26236. if ( binding !== undefined ) binding.getValue( array, offset );
  26237. }
  26238. setValue( array, offset ) {
  26239. const bindings = this._bindings;
  26240. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26241. bindings[ i ].setValue( array, offset );
  26242. }
  26243. }
  26244. bind() {
  26245. const bindings = this._bindings;
  26246. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26247. bindings[ i ].bind();
  26248. }
  26249. }
  26250. unbind() {
  26251. const bindings = this._bindings;
  26252. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  26253. bindings[ i ].unbind();
  26254. }
  26255. }
  26256. }
  26257. // Note: This class uses a State pattern on a per-method basis:
  26258. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  26259. // prototype version of these methods with one that represents
  26260. // the bound state. When the property is not found, the methods
  26261. // become no-ops.
  26262. class PropertyBinding {
  26263. constructor( rootNode, path, parsedPath ) {
  26264. this.path = path;
  26265. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  26266. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  26267. this.rootNode = rootNode;
  26268. // initial state of these methods that calls 'bind'
  26269. this.getValue = this._getValue_unbound;
  26270. this.setValue = this._setValue_unbound;
  26271. }
  26272. static create( root, path, parsedPath ) {
  26273. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  26274. return new PropertyBinding( root, path, parsedPath );
  26275. } else {
  26276. return new PropertyBinding.Composite( root, path, parsedPath );
  26277. }
  26278. }
  26279. /**
  26280. * Replaces spaces with underscores and removes unsupported characters from
  26281. * node names, to ensure compatibility with parseTrackName().
  26282. *
  26283. * @param {string} name Node name to be sanitized.
  26284. * @return {string}
  26285. */
  26286. static sanitizeNodeName( name ) {
  26287. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  26288. }
  26289. static parseTrackName( trackName ) {
  26290. const matches = _trackRe.exec( trackName );
  26291. if ( matches === null ) {
  26292. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  26293. }
  26294. const results = {
  26295. // directoryName: matches[ 1 ], // (tschw) currently unused
  26296. nodeName: matches[ 2 ],
  26297. objectName: matches[ 3 ],
  26298. objectIndex: matches[ 4 ],
  26299. propertyName: matches[ 5 ], // required
  26300. propertyIndex: matches[ 6 ]
  26301. };
  26302. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  26303. if ( lastDot !== undefined && lastDot !== - 1 ) {
  26304. const objectName = results.nodeName.substring( lastDot + 1 );
  26305. // Object names must be checked against an allowlist. Otherwise, there
  26306. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  26307. // 'bar' could be the objectName, or part of a nodeName (which can
  26308. // include '.' characters).
  26309. if ( _supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  26310. results.nodeName = results.nodeName.substring( 0, lastDot );
  26311. results.objectName = objectName;
  26312. }
  26313. }
  26314. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  26315. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  26316. }
  26317. return results;
  26318. }
  26319. static findNode( root, nodeName ) {
  26320. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  26321. return root;
  26322. }
  26323. // search into skeleton bones.
  26324. if ( root.skeleton ) {
  26325. const bone = root.skeleton.getBoneByName( nodeName );
  26326. if ( bone !== undefined ) {
  26327. return bone;
  26328. }
  26329. }
  26330. // search into node subtree.
  26331. if ( root.children ) {
  26332. const searchNodeSubtree = function ( children ) {
  26333. for ( let i = 0; i < children.length; i ++ ) {
  26334. const childNode = children[ i ];
  26335. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  26336. return childNode;
  26337. }
  26338. const result = searchNodeSubtree( childNode.children );
  26339. if ( result ) return result;
  26340. }
  26341. return null;
  26342. };
  26343. const subTreeNode = searchNodeSubtree( root.children );
  26344. if ( subTreeNode ) {
  26345. return subTreeNode;
  26346. }
  26347. }
  26348. return null;
  26349. }
  26350. // these are used to "bind" a nonexistent property
  26351. _getValue_unavailable() {}
  26352. _setValue_unavailable() {}
  26353. // Getters
  26354. _getValue_direct( buffer, offset ) {
  26355. buffer[ offset ] = this.targetObject[ this.propertyName ];
  26356. }
  26357. _getValue_array( buffer, offset ) {
  26358. const source = this.resolvedProperty;
  26359. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  26360. buffer[ offset ++ ] = source[ i ];
  26361. }
  26362. }
  26363. _getValue_arrayElement( buffer, offset ) {
  26364. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  26365. }
  26366. _getValue_toArray( buffer, offset ) {
  26367. this.resolvedProperty.toArray( buffer, offset );
  26368. }
  26369. // Direct
  26370. _setValue_direct( buffer, offset ) {
  26371. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26372. }
  26373. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  26374. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26375. this.targetObject.needsUpdate = true;
  26376. }
  26377. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26378. this.targetObject[ this.propertyName ] = buffer[ offset ];
  26379. this.targetObject.matrixWorldNeedsUpdate = true;
  26380. }
  26381. // EntireArray
  26382. _setValue_array( buffer, offset ) {
  26383. const dest = this.resolvedProperty;
  26384. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26385. dest[ i ] = buffer[ offset ++ ];
  26386. }
  26387. }
  26388. _setValue_array_setNeedsUpdate( buffer, offset ) {
  26389. const dest = this.resolvedProperty;
  26390. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26391. dest[ i ] = buffer[ offset ++ ];
  26392. }
  26393. this.targetObject.needsUpdate = true;
  26394. }
  26395. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26396. const dest = this.resolvedProperty;
  26397. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  26398. dest[ i ] = buffer[ offset ++ ];
  26399. }
  26400. this.targetObject.matrixWorldNeedsUpdate = true;
  26401. }
  26402. // ArrayElement
  26403. _setValue_arrayElement( buffer, offset ) {
  26404. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26405. }
  26406. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  26407. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26408. this.targetObject.needsUpdate = true;
  26409. }
  26410. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26411. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26412. this.targetObject.matrixWorldNeedsUpdate = true;
  26413. }
  26414. // HasToFromArray
  26415. _setValue_fromArray( buffer, offset ) {
  26416. this.resolvedProperty.fromArray( buffer, offset );
  26417. }
  26418. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  26419. this.resolvedProperty.fromArray( buffer, offset );
  26420. this.targetObject.needsUpdate = true;
  26421. }
  26422. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26423. this.resolvedProperty.fromArray( buffer, offset );
  26424. this.targetObject.matrixWorldNeedsUpdate = true;
  26425. }
  26426. _getValue_unbound( targetArray, offset ) {
  26427. this.bind();
  26428. this.getValue( targetArray, offset );
  26429. }
  26430. _setValue_unbound( sourceArray, offset ) {
  26431. this.bind();
  26432. this.setValue( sourceArray, offset );
  26433. }
  26434. // create getter / setter pair for a property in the scene graph
  26435. bind() {
  26436. let targetObject = this.node;
  26437. const parsedPath = this.parsedPath;
  26438. const objectName = parsedPath.objectName;
  26439. const propertyName = parsedPath.propertyName;
  26440. let propertyIndex = parsedPath.propertyIndex;
  26441. if ( ! targetObject ) {
  26442. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  26443. this.node = targetObject;
  26444. }
  26445. // set fail state so we can just 'return' on error
  26446. this.getValue = this._getValue_unavailable;
  26447. this.setValue = this._setValue_unavailable;
  26448. // ensure there is a value node
  26449. if ( ! targetObject ) {
  26450. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  26451. return;
  26452. }
  26453. if ( objectName ) {
  26454. let objectIndex = parsedPath.objectIndex;
  26455. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  26456. switch ( objectName ) {
  26457. case 'materials':
  26458. if ( ! targetObject.material ) {
  26459. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  26460. return;
  26461. }
  26462. if ( ! targetObject.material.materials ) {
  26463. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  26464. return;
  26465. }
  26466. targetObject = targetObject.material.materials;
  26467. break;
  26468. case 'bones':
  26469. if ( ! targetObject.skeleton ) {
  26470. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  26471. return;
  26472. }
  26473. // potential future optimization: skip this if propertyIndex is already an integer
  26474. // and convert the integer string to a true integer.
  26475. targetObject = targetObject.skeleton.bones;
  26476. // support resolving morphTarget names into indices.
  26477. for ( let i = 0; i < targetObject.length; i ++ ) {
  26478. if ( targetObject[ i ].name === objectIndex ) {
  26479. objectIndex = i;
  26480. break;
  26481. }
  26482. }
  26483. break;
  26484. default:
  26485. if ( targetObject[ objectName ] === undefined ) {
  26486. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  26487. return;
  26488. }
  26489. targetObject = targetObject[ objectName ];
  26490. }
  26491. if ( objectIndex !== undefined ) {
  26492. if ( targetObject[ objectIndex ] === undefined ) {
  26493. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  26494. return;
  26495. }
  26496. targetObject = targetObject[ objectIndex ];
  26497. }
  26498. }
  26499. // resolve property
  26500. const nodeProperty = targetObject[ propertyName ];
  26501. if ( nodeProperty === undefined ) {
  26502. const nodeName = parsedPath.nodeName;
  26503. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  26504. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  26505. return;
  26506. }
  26507. // determine versioning scheme
  26508. let versioning = this.Versioning.None;
  26509. this.targetObject = targetObject;
  26510. if ( targetObject.needsUpdate !== undefined ) { // material
  26511. versioning = this.Versioning.NeedsUpdate;
  26512. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  26513. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26514. }
  26515. // determine how the property gets bound
  26516. let bindingType = this.BindingType.Direct;
  26517. if ( propertyIndex !== undefined ) {
  26518. // access a sub element of the property array (only primitives are supported right now)
  26519. if ( propertyName === 'morphTargetInfluences' ) {
  26520. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26521. // support resolving morphTarget names into indices.
  26522. if ( ! targetObject.geometry ) {
  26523. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  26524. return;
  26525. }
  26526. if ( ! targetObject.geometry.morphAttributes ) {
  26527. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  26528. return;
  26529. }
  26530. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  26531. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  26532. }
  26533. }
  26534. bindingType = this.BindingType.ArrayElement;
  26535. this.resolvedProperty = nodeProperty;
  26536. this.propertyIndex = propertyIndex;
  26537. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  26538. // must use copy for Object3D.Euler/Quaternion
  26539. bindingType = this.BindingType.HasFromToArray;
  26540. this.resolvedProperty = nodeProperty;
  26541. } else if ( Array.isArray( nodeProperty ) ) {
  26542. bindingType = this.BindingType.EntireArray;
  26543. this.resolvedProperty = nodeProperty;
  26544. } else {
  26545. this.propertyName = propertyName;
  26546. }
  26547. // select getter / setter
  26548. this.getValue = this.GetterByBindingType[ bindingType ];
  26549. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  26550. }
  26551. unbind() {
  26552. this.node = null;
  26553. // back to the prototype version of getValue / setValue
  26554. // note: avoiding to mutate the shape of 'this' via 'delete'
  26555. this.getValue = this._getValue_unbound;
  26556. this.setValue = this._setValue_unbound;
  26557. }
  26558. }
  26559. PropertyBinding.Composite = Composite;
  26560. PropertyBinding.prototype.BindingType = {
  26561. Direct: 0,
  26562. EntireArray: 1,
  26563. ArrayElement: 2,
  26564. HasFromToArray: 3
  26565. };
  26566. PropertyBinding.prototype.Versioning = {
  26567. None: 0,
  26568. NeedsUpdate: 1,
  26569. MatrixWorldNeedsUpdate: 2
  26570. };
  26571. PropertyBinding.prototype.GetterByBindingType = [
  26572. PropertyBinding.prototype._getValue_direct,
  26573. PropertyBinding.prototype._getValue_array,
  26574. PropertyBinding.prototype._getValue_arrayElement,
  26575. PropertyBinding.prototype._getValue_toArray,
  26576. ];
  26577. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  26578. [
  26579. // Direct
  26580. PropertyBinding.prototype._setValue_direct,
  26581. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  26582. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  26583. ], [
  26584. // EntireArray
  26585. PropertyBinding.prototype._setValue_array,
  26586. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  26587. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  26588. ], [
  26589. // ArrayElement
  26590. PropertyBinding.prototype._setValue_arrayElement,
  26591. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  26592. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  26593. ], [
  26594. // HasToFromArray
  26595. PropertyBinding.prototype._setValue_fromArray,
  26596. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  26597. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  26598. ]
  26599. ];
  26600. /**
  26601. *
  26602. * A group of objects that receives a shared animation state.
  26603. *
  26604. * Usage:
  26605. *
  26606. * - Add objects you would otherwise pass as 'root' to the
  26607. * constructor or the .clipAction method of AnimationMixer.
  26608. *
  26609. * - Instead pass this object as 'root'.
  26610. *
  26611. * - You can also add and remove objects later when the mixer
  26612. * is running.
  26613. *
  26614. * Note:
  26615. *
  26616. * Objects of this class appear as one object to the mixer,
  26617. * so cache control of the individual objects must be done
  26618. * on the group.
  26619. *
  26620. * Limitation:
  26621. *
  26622. * - The animated properties must be compatible among the
  26623. * all objects in the group.
  26624. *
  26625. * - A single property can either be controlled through a
  26626. * target group or directly, but not both.
  26627. */
  26628. class AnimationObjectGroup {
  26629. constructor() {
  26630. this.isAnimationObjectGroup = true;
  26631. this.uuid = generateUUID();
  26632. // cached objects followed by the active ones
  26633. this._objects = Array.prototype.slice.call( arguments );
  26634. this.nCachedObjects_ = 0; // threshold
  26635. // note: read by PropertyBinding.Composite
  26636. const indices = {};
  26637. this._indicesByUUID = indices; // for bookkeeping
  26638. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26639. indices[ arguments[ i ].uuid ] = i;
  26640. }
  26641. this._paths = []; // inside: string
  26642. this._parsedPaths = []; // inside: { we don't care, here }
  26643. this._bindings = []; // inside: Array< PropertyBinding >
  26644. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26645. const scope = this;
  26646. this.stats = {
  26647. objects: {
  26648. get total() {
  26649. return scope._objects.length;
  26650. },
  26651. get inUse() {
  26652. return this.total - scope.nCachedObjects_;
  26653. }
  26654. },
  26655. get bindingsPerObject() {
  26656. return scope._bindings.length;
  26657. }
  26658. };
  26659. }
  26660. add() {
  26661. const objects = this._objects,
  26662. indicesByUUID = this._indicesByUUID,
  26663. paths = this._paths,
  26664. parsedPaths = this._parsedPaths,
  26665. bindings = this._bindings,
  26666. nBindings = bindings.length;
  26667. let knownObject = undefined,
  26668. nObjects = objects.length,
  26669. nCachedObjects = this.nCachedObjects_;
  26670. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26671. const object = arguments[ i ],
  26672. uuid = object.uuid;
  26673. let index = indicesByUUID[ uuid ];
  26674. if ( index === undefined ) {
  26675. // unknown object -> add it to the ACTIVE region
  26676. index = nObjects ++;
  26677. indicesByUUID[ uuid ] = index;
  26678. objects.push( object );
  26679. // accounting is done, now do the same for all bindings
  26680. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26681. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  26682. }
  26683. } else if ( index < nCachedObjects ) {
  26684. knownObject = objects[ index ];
  26685. // move existing object to the ACTIVE region
  26686. const firstActiveIndex = -- nCachedObjects,
  26687. lastCachedObject = objects[ firstActiveIndex ];
  26688. indicesByUUID[ lastCachedObject.uuid ] = index;
  26689. objects[ index ] = lastCachedObject;
  26690. indicesByUUID[ uuid ] = firstActiveIndex;
  26691. objects[ firstActiveIndex ] = object;
  26692. // accounting is done, now do the same for all bindings
  26693. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26694. const bindingsForPath = bindings[ j ],
  26695. lastCached = bindingsForPath[ firstActiveIndex ];
  26696. let binding = bindingsForPath[ index ];
  26697. bindingsForPath[ index ] = lastCached;
  26698. if ( binding === undefined ) {
  26699. // since we do not bother to create new bindings
  26700. // for objects that are cached, the binding may
  26701. // or may not exist
  26702. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  26703. }
  26704. bindingsForPath[ firstActiveIndex ] = binding;
  26705. }
  26706. } else if ( objects[ index ] !== knownObject ) {
  26707. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  26708. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  26709. } // else the object is already where we want it to be
  26710. } // for arguments
  26711. this.nCachedObjects_ = nCachedObjects;
  26712. }
  26713. remove() {
  26714. const objects = this._objects,
  26715. indicesByUUID = this._indicesByUUID,
  26716. bindings = this._bindings,
  26717. nBindings = bindings.length;
  26718. let nCachedObjects = this.nCachedObjects_;
  26719. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26720. const object = arguments[ i ],
  26721. uuid = object.uuid,
  26722. index = indicesByUUID[ uuid ];
  26723. if ( index !== undefined && index >= nCachedObjects ) {
  26724. // move existing object into the CACHED region
  26725. const lastCachedIndex = nCachedObjects ++,
  26726. firstActiveObject = objects[ lastCachedIndex ];
  26727. indicesByUUID[ firstActiveObject.uuid ] = index;
  26728. objects[ index ] = firstActiveObject;
  26729. indicesByUUID[ uuid ] = lastCachedIndex;
  26730. objects[ lastCachedIndex ] = object;
  26731. // accounting is done, now do the same for all bindings
  26732. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26733. const bindingsForPath = bindings[ j ],
  26734. firstActive = bindingsForPath[ lastCachedIndex ],
  26735. binding = bindingsForPath[ index ];
  26736. bindingsForPath[ index ] = firstActive;
  26737. bindingsForPath[ lastCachedIndex ] = binding;
  26738. }
  26739. }
  26740. } // for arguments
  26741. this.nCachedObjects_ = nCachedObjects;
  26742. }
  26743. // remove & forget
  26744. uncache() {
  26745. const objects = this._objects,
  26746. indicesByUUID = this._indicesByUUID,
  26747. bindings = this._bindings,
  26748. nBindings = bindings.length;
  26749. let nCachedObjects = this.nCachedObjects_,
  26750. nObjects = objects.length;
  26751. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  26752. const object = arguments[ i ],
  26753. uuid = object.uuid,
  26754. index = indicesByUUID[ uuid ];
  26755. if ( index !== undefined ) {
  26756. delete indicesByUUID[ uuid ];
  26757. if ( index < nCachedObjects ) {
  26758. // object is cached, shrink the CACHED region
  26759. const firstActiveIndex = -- nCachedObjects,
  26760. lastCachedObject = objects[ firstActiveIndex ],
  26761. lastIndex = -- nObjects,
  26762. lastObject = objects[ lastIndex ];
  26763. // last cached object takes this object's place
  26764. indicesByUUID[ lastCachedObject.uuid ] = index;
  26765. objects[ index ] = lastCachedObject;
  26766. // last object goes to the activated slot and pop
  26767. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  26768. objects[ firstActiveIndex ] = lastObject;
  26769. objects.pop();
  26770. // accounting is done, now do the same for all bindings
  26771. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26772. const bindingsForPath = bindings[ j ],
  26773. lastCached = bindingsForPath[ firstActiveIndex ],
  26774. last = bindingsForPath[ lastIndex ];
  26775. bindingsForPath[ index ] = lastCached;
  26776. bindingsForPath[ firstActiveIndex ] = last;
  26777. bindingsForPath.pop();
  26778. }
  26779. } else {
  26780. // object is active, just swap with the last and pop
  26781. const lastIndex = -- nObjects,
  26782. lastObject = objects[ lastIndex ];
  26783. if ( lastIndex > 0 ) {
  26784. indicesByUUID[ lastObject.uuid ] = index;
  26785. }
  26786. objects[ index ] = lastObject;
  26787. objects.pop();
  26788. // accounting is done, now do the same for all bindings
  26789. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  26790. const bindingsForPath = bindings[ j ];
  26791. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  26792. bindingsForPath.pop();
  26793. }
  26794. } // cached or active
  26795. } // if object is known
  26796. } // for arguments
  26797. this.nCachedObjects_ = nCachedObjects;
  26798. }
  26799. // Internal interface used by befriended PropertyBinding.Composite:
  26800. subscribe_( path, parsedPath ) {
  26801. // returns an array of bindings for the given path that is changed
  26802. // according to the contained objects in the group
  26803. const indicesByPath = this._bindingsIndicesByPath;
  26804. let index = indicesByPath[ path ];
  26805. const bindings = this._bindings;
  26806. if ( index !== undefined ) return bindings[ index ];
  26807. const paths = this._paths,
  26808. parsedPaths = this._parsedPaths,
  26809. objects = this._objects,
  26810. nObjects = objects.length,
  26811. nCachedObjects = this.nCachedObjects_,
  26812. bindingsForPath = new Array( nObjects );
  26813. index = bindings.length;
  26814. indicesByPath[ path ] = index;
  26815. paths.push( path );
  26816. parsedPaths.push( parsedPath );
  26817. bindings.push( bindingsForPath );
  26818. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  26819. const object = objects[ i ];
  26820. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  26821. }
  26822. return bindingsForPath;
  26823. }
  26824. unsubscribe_( path ) {
  26825. // tells the group to forget about a property path and no longer
  26826. // update the array previously obtained with 'subscribe_'
  26827. const indicesByPath = this._bindingsIndicesByPath,
  26828. index = indicesByPath[ path ];
  26829. if ( index !== undefined ) {
  26830. const paths = this._paths,
  26831. parsedPaths = this._parsedPaths,
  26832. bindings = this._bindings,
  26833. lastBindingsIndex = bindings.length - 1,
  26834. lastBindings = bindings[ lastBindingsIndex ],
  26835. lastBindingsPath = path[ lastBindingsIndex ];
  26836. indicesByPath[ lastBindingsPath ] = index;
  26837. bindings[ index ] = lastBindings;
  26838. bindings.pop();
  26839. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  26840. parsedPaths.pop();
  26841. paths[ index ] = paths[ lastBindingsIndex ];
  26842. paths.pop();
  26843. }
  26844. }
  26845. }
  26846. class AnimationAction {
  26847. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  26848. this._mixer = mixer;
  26849. this._clip = clip;
  26850. this._localRoot = localRoot;
  26851. this.blendMode = blendMode;
  26852. const tracks = clip.tracks,
  26853. nTracks = tracks.length,
  26854. interpolants = new Array( nTracks );
  26855. const interpolantSettings = {
  26856. endingStart: ZeroCurvatureEnding,
  26857. endingEnd: ZeroCurvatureEnding
  26858. };
  26859. for ( let i = 0; i !== nTracks; ++ i ) {
  26860. const interpolant = tracks[ i ].createInterpolant( null );
  26861. interpolants[ i ] = interpolant;
  26862. interpolant.settings = interpolantSettings;
  26863. }
  26864. this._interpolantSettings = interpolantSettings;
  26865. this._interpolants = interpolants; // bound by the mixer
  26866. // inside: PropertyMixer (managed by the mixer)
  26867. this._propertyBindings = new Array( nTracks );
  26868. this._cacheIndex = null; // for the memory manager
  26869. this._byClipCacheIndex = null; // for the memory manager
  26870. this._timeScaleInterpolant = null;
  26871. this._weightInterpolant = null;
  26872. this.loop = LoopRepeat;
  26873. this._loopCount = - 1;
  26874. // global mixer time when the action is to be started
  26875. // it's set back to 'null' upon start of the action
  26876. this._startTime = null;
  26877. // scaled local time of the action
  26878. // gets clamped or wrapped to 0..clip.duration according to loop
  26879. this.time = 0;
  26880. this.timeScale = 1;
  26881. this._effectiveTimeScale = 1;
  26882. this.weight = 1;
  26883. this._effectiveWeight = 1;
  26884. this.repetitions = Infinity; // no. of repetitions when looping
  26885. this.paused = false; // true -> zero effective time scale
  26886. this.enabled = true; // false -> zero effective weight
  26887. this.clampWhenFinished = false;// keep feeding the last frame?
  26888. this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
  26889. this.zeroSlopeAtEnd = true;// clips for start, loop and end
  26890. }
  26891. // State & Scheduling
  26892. play() {
  26893. this._mixer._activateAction( this );
  26894. return this;
  26895. }
  26896. stop() {
  26897. this._mixer._deactivateAction( this );
  26898. return this.reset();
  26899. }
  26900. reset() {
  26901. this.paused = false;
  26902. this.enabled = true;
  26903. this.time = 0; // restart clip
  26904. this._loopCount = - 1;// forget previous loops
  26905. this._startTime = null;// forget scheduling
  26906. return this.stopFading().stopWarping();
  26907. }
  26908. isRunning() {
  26909. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  26910. this._startTime === null && this._mixer._isActiveAction( this );
  26911. }
  26912. // return true when play has been called
  26913. isScheduled() {
  26914. return this._mixer._isActiveAction( this );
  26915. }
  26916. startAt( time ) {
  26917. this._startTime = time;
  26918. return this;
  26919. }
  26920. setLoop( mode, repetitions ) {
  26921. this.loop = mode;
  26922. this.repetitions = repetitions;
  26923. return this;
  26924. }
  26925. // Weight
  26926. // set the weight stopping any scheduled fading
  26927. // although .enabled = false yields an effective weight of zero, this
  26928. // method does *not* change .enabled, because it would be confusing
  26929. setEffectiveWeight( weight ) {
  26930. this.weight = weight;
  26931. // note: same logic as when updated at runtime
  26932. this._effectiveWeight = this.enabled ? weight : 0;
  26933. return this.stopFading();
  26934. }
  26935. // return the weight considering fading and .enabled
  26936. getEffectiveWeight() {
  26937. return this._effectiveWeight;
  26938. }
  26939. fadeIn( duration ) {
  26940. return this._scheduleFading( duration, 0, 1 );
  26941. }
  26942. fadeOut( duration ) {
  26943. return this._scheduleFading( duration, 1, 0 );
  26944. }
  26945. crossFadeFrom( fadeOutAction, duration, warp ) {
  26946. fadeOutAction.fadeOut( duration );
  26947. this.fadeIn( duration );
  26948. if ( warp ) {
  26949. const fadeInDuration = this._clip.duration,
  26950. fadeOutDuration = fadeOutAction._clip.duration,
  26951. startEndRatio = fadeOutDuration / fadeInDuration,
  26952. endStartRatio = fadeInDuration / fadeOutDuration;
  26953. fadeOutAction.warp( 1.0, startEndRatio, duration );
  26954. this.warp( endStartRatio, 1.0, duration );
  26955. }
  26956. return this;
  26957. }
  26958. crossFadeTo( fadeInAction, duration, warp ) {
  26959. return fadeInAction.crossFadeFrom( this, duration, warp );
  26960. }
  26961. stopFading() {
  26962. const weightInterpolant = this._weightInterpolant;
  26963. if ( weightInterpolant !== null ) {
  26964. this._weightInterpolant = null;
  26965. this._mixer._takeBackControlInterpolant( weightInterpolant );
  26966. }
  26967. return this;
  26968. }
  26969. // Time Scale Control
  26970. // set the time scale stopping any scheduled warping
  26971. // although .paused = true yields an effective time scale of zero, this
  26972. // method does *not* change .paused, because it would be confusing
  26973. setEffectiveTimeScale( timeScale ) {
  26974. this.timeScale = timeScale;
  26975. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  26976. return this.stopWarping();
  26977. }
  26978. // return the time scale considering warping and .paused
  26979. getEffectiveTimeScale() {
  26980. return this._effectiveTimeScale;
  26981. }
  26982. setDuration( duration ) {
  26983. this.timeScale = this._clip.duration / duration;
  26984. return this.stopWarping();
  26985. }
  26986. syncWith( action ) {
  26987. this.time = action.time;
  26988. this.timeScale = action.timeScale;
  26989. return this.stopWarping();
  26990. }
  26991. halt( duration ) {
  26992. return this.warp( this._effectiveTimeScale, 0, duration );
  26993. }
  26994. warp( startTimeScale, endTimeScale, duration ) {
  26995. const mixer = this._mixer,
  26996. now = mixer.time,
  26997. timeScale = this.timeScale;
  26998. let interpolant = this._timeScaleInterpolant;
  26999. if ( interpolant === null ) {
  27000. interpolant = mixer._lendControlInterpolant();
  27001. this._timeScaleInterpolant = interpolant;
  27002. }
  27003. const times = interpolant.parameterPositions,
  27004. values = interpolant.sampleValues;
  27005. times[ 0 ] = now;
  27006. times[ 1 ] = now + duration;
  27007. values[ 0 ] = startTimeScale / timeScale;
  27008. values[ 1 ] = endTimeScale / timeScale;
  27009. return this;
  27010. }
  27011. stopWarping() {
  27012. const timeScaleInterpolant = this._timeScaleInterpolant;
  27013. if ( timeScaleInterpolant !== null ) {
  27014. this._timeScaleInterpolant = null;
  27015. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  27016. }
  27017. return this;
  27018. }
  27019. // Object Accessors
  27020. getMixer() {
  27021. return this._mixer;
  27022. }
  27023. getClip() {
  27024. return this._clip;
  27025. }
  27026. getRoot() {
  27027. return this._localRoot || this._mixer._root;
  27028. }
  27029. // Interna
  27030. _update( time, deltaTime, timeDirection, accuIndex ) {
  27031. // called by the mixer
  27032. if ( ! this.enabled ) {
  27033. // call ._updateWeight() to update ._effectiveWeight
  27034. this._updateWeight( time );
  27035. return;
  27036. }
  27037. const startTime = this._startTime;
  27038. if ( startTime !== null ) {
  27039. // check for scheduled start of action
  27040. const timeRunning = ( time - startTime ) * timeDirection;
  27041. if ( timeRunning < 0 || timeDirection === 0 ) {
  27042. deltaTime = 0;
  27043. } else {
  27044. this._startTime = null; // unschedule
  27045. deltaTime = timeDirection * timeRunning;
  27046. }
  27047. }
  27048. // apply time scale and advance time
  27049. deltaTime *= this._updateTimeScale( time );
  27050. const clipTime = this._updateTime( deltaTime );
  27051. // note: _updateTime may disable the action resulting in
  27052. // an effective weight of 0
  27053. const weight = this._updateWeight( time );
  27054. if ( weight > 0 ) {
  27055. const interpolants = this._interpolants;
  27056. const propertyMixers = this._propertyBindings;
  27057. switch ( this.blendMode ) {
  27058. case AdditiveAnimationBlendMode:
  27059. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27060. interpolants[ j ].evaluate( clipTime );
  27061. propertyMixers[ j ].accumulateAdditive( weight );
  27062. }
  27063. break;
  27064. case NormalAnimationBlendMode:
  27065. default:
  27066. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  27067. interpolants[ j ].evaluate( clipTime );
  27068. propertyMixers[ j ].accumulate( accuIndex, weight );
  27069. }
  27070. }
  27071. }
  27072. }
  27073. _updateWeight( time ) {
  27074. let weight = 0;
  27075. if ( this.enabled ) {
  27076. weight = this.weight;
  27077. const interpolant = this._weightInterpolant;
  27078. if ( interpolant !== null ) {
  27079. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27080. weight *= interpolantValue;
  27081. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27082. this.stopFading();
  27083. if ( interpolantValue === 0 ) {
  27084. // faded out, disable
  27085. this.enabled = false;
  27086. }
  27087. }
  27088. }
  27089. }
  27090. this._effectiveWeight = weight;
  27091. return weight;
  27092. }
  27093. _updateTimeScale( time ) {
  27094. let timeScale = 0;
  27095. if ( ! this.paused ) {
  27096. timeScale = this.timeScale;
  27097. const interpolant = this._timeScaleInterpolant;
  27098. if ( interpolant !== null ) {
  27099. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  27100. timeScale *= interpolantValue;
  27101. if ( time > interpolant.parameterPositions[ 1 ] ) {
  27102. this.stopWarping();
  27103. if ( timeScale === 0 ) {
  27104. // motion has halted, pause
  27105. this.paused = true;
  27106. } else {
  27107. // warp done - apply final time scale
  27108. this.timeScale = timeScale;
  27109. }
  27110. }
  27111. }
  27112. }
  27113. this._effectiveTimeScale = timeScale;
  27114. return timeScale;
  27115. }
  27116. _updateTime( deltaTime ) {
  27117. const duration = this._clip.duration;
  27118. const loop = this.loop;
  27119. let time = this.time + deltaTime;
  27120. let loopCount = this._loopCount;
  27121. const pingPong = ( loop === LoopPingPong );
  27122. if ( deltaTime === 0 ) {
  27123. if ( loopCount === - 1 ) return time;
  27124. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  27125. }
  27126. if ( loop === LoopOnce ) {
  27127. if ( loopCount === - 1 ) {
  27128. // just started
  27129. this._loopCount = 0;
  27130. this._setEndings( true, true, false );
  27131. }
  27132. handle_stop: {
  27133. if ( time >= duration ) {
  27134. time = duration;
  27135. } else if ( time < 0 ) {
  27136. time = 0;
  27137. } else {
  27138. this.time = time;
  27139. break handle_stop;
  27140. }
  27141. if ( this.clampWhenFinished ) this.paused = true;
  27142. else this.enabled = false;
  27143. this.time = time;
  27144. this._mixer.dispatchEvent( {
  27145. type: 'finished', action: this,
  27146. direction: deltaTime < 0 ? - 1 : 1
  27147. } );
  27148. }
  27149. } else { // repetitive Repeat or PingPong
  27150. if ( loopCount === - 1 ) {
  27151. // just started
  27152. if ( deltaTime >= 0 ) {
  27153. loopCount = 0;
  27154. this._setEndings( true, this.repetitions === 0, pingPong );
  27155. } else {
  27156. // when looping in reverse direction, the initial
  27157. // transition through zero counts as a repetition,
  27158. // so leave loopCount at -1
  27159. this._setEndings( this.repetitions === 0, true, pingPong );
  27160. }
  27161. }
  27162. if ( time >= duration || time < 0 ) {
  27163. // wrap around
  27164. const loopDelta = Math.floor( time / duration ); // signed
  27165. time -= duration * loopDelta;
  27166. loopCount += Math.abs( loopDelta );
  27167. const pending = this.repetitions - loopCount;
  27168. if ( pending <= 0 ) {
  27169. // have to stop (switch state, clamp time, fire event)
  27170. if ( this.clampWhenFinished ) this.paused = true;
  27171. else this.enabled = false;
  27172. time = deltaTime > 0 ? duration : 0;
  27173. this.time = time;
  27174. this._mixer.dispatchEvent( {
  27175. type: 'finished', action: this,
  27176. direction: deltaTime > 0 ? 1 : - 1
  27177. } );
  27178. } else {
  27179. // keep running
  27180. if ( pending === 1 ) {
  27181. // entering the last round
  27182. const atStart = deltaTime < 0;
  27183. this._setEndings( atStart, ! atStart, pingPong );
  27184. } else {
  27185. this._setEndings( false, false, pingPong );
  27186. }
  27187. this._loopCount = loopCount;
  27188. this.time = time;
  27189. this._mixer.dispatchEvent( {
  27190. type: 'loop', action: this, loopDelta: loopDelta
  27191. } );
  27192. }
  27193. } else {
  27194. this.time = time;
  27195. }
  27196. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  27197. // invert time for the "pong round"
  27198. return duration - time;
  27199. }
  27200. }
  27201. return time;
  27202. }
  27203. _setEndings( atStart, atEnd, pingPong ) {
  27204. const settings = this._interpolantSettings;
  27205. if ( pingPong ) {
  27206. settings.endingStart = ZeroSlopeEnding;
  27207. settings.endingEnd = ZeroSlopeEnding;
  27208. } else {
  27209. // assuming for LoopOnce atStart == atEnd == true
  27210. if ( atStart ) {
  27211. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27212. } else {
  27213. settings.endingStart = WrapAroundEnding;
  27214. }
  27215. if ( atEnd ) {
  27216. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  27217. } else {
  27218. settings.endingEnd = WrapAroundEnding;
  27219. }
  27220. }
  27221. }
  27222. _scheduleFading( duration, weightNow, weightThen ) {
  27223. const mixer = this._mixer, now = mixer.time;
  27224. let interpolant = this._weightInterpolant;
  27225. if ( interpolant === null ) {
  27226. interpolant = mixer._lendControlInterpolant();
  27227. this._weightInterpolant = interpolant;
  27228. }
  27229. const times = interpolant.parameterPositions,
  27230. values = interpolant.sampleValues;
  27231. times[ 0 ] = now;
  27232. values[ 0 ] = weightNow;
  27233. times[ 1 ] = now + duration;
  27234. values[ 1 ] = weightThen;
  27235. return this;
  27236. }
  27237. }
  27238. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  27239. class AnimationMixer extends EventDispatcher {
  27240. constructor( root ) {
  27241. super();
  27242. this._root = root;
  27243. this._initMemoryManager();
  27244. this._accuIndex = 0;
  27245. this.time = 0;
  27246. this.timeScale = 1.0;
  27247. }
  27248. _bindAction( action, prototypeAction ) {
  27249. const root = action._localRoot || this._root,
  27250. tracks = action._clip.tracks,
  27251. nTracks = tracks.length,
  27252. bindings = action._propertyBindings,
  27253. interpolants = action._interpolants,
  27254. rootUuid = root.uuid,
  27255. bindingsByRoot = this._bindingsByRootAndName;
  27256. let bindingsByName = bindingsByRoot[ rootUuid ];
  27257. if ( bindingsByName === undefined ) {
  27258. bindingsByName = {};
  27259. bindingsByRoot[ rootUuid ] = bindingsByName;
  27260. }
  27261. for ( let i = 0; i !== nTracks; ++ i ) {
  27262. const track = tracks[ i ],
  27263. trackName = track.name;
  27264. let binding = bindingsByName[ trackName ];
  27265. if ( binding !== undefined ) {
  27266. ++ binding.referenceCount;
  27267. bindings[ i ] = binding;
  27268. } else {
  27269. binding = bindings[ i ];
  27270. if ( binding !== undefined ) {
  27271. // existing binding, make sure the cache knows
  27272. if ( binding._cacheIndex === null ) {
  27273. ++ binding.referenceCount;
  27274. this._addInactiveBinding( binding, rootUuid, trackName );
  27275. }
  27276. continue;
  27277. }
  27278. const path = prototypeAction && prototypeAction.
  27279. _propertyBindings[ i ].binding.parsedPath;
  27280. binding = new PropertyMixer(
  27281. PropertyBinding.create( root, trackName, path ),
  27282. track.ValueTypeName, track.getValueSize() );
  27283. ++ binding.referenceCount;
  27284. this._addInactiveBinding( binding, rootUuid, trackName );
  27285. bindings[ i ] = binding;
  27286. }
  27287. interpolants[ i ].resultBuffer = binding.buffer;
  27288. }
  27289. }
  27290. _activateAction( action ) {
  27291. if ( ! this._isActiveAction( action ) ) {
  27292. if ( action._cacheIndex === null ) {
  27293. // this action has been forgotten by the cache, but the user
  27294. // appears to be still using it -> rebind
  27295. const rootUuid = ( action._localRoot || this._root ).uuid,
  27296. clipUuid = action._clip.uuid,
  27297. actionsForClip = this._actionsByClip[ clipUuid ];
  27298. this._bindAction( action,
  27299. actionsForClip && actionsForClip.knownActions[ 0 ] );
  27300. this._addInactiveAction( action, clipUuid, rootUuid );
  27301. }
  27302. const bindings = action._propertyBindings;
  27303. // increment reference counts / sort out state
  27304. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27305. const binding = bindings[ i ];
  27306. if ( binding.useCount ++ === 0 ) {
  27307. this._lendBinding( binding );
  27308. binding.saveOriginalState();
  27309. }
  27310. }
  27311. this._lendAction( action );
  27312. }
  27313. }
  27314. _deactivateAction( action ) {
  27315. if ( this._isActiveAction( action ) ) {
  27316. const bindings = action._propertyBindings;
  27317. // decrement reference counts / sort out state
  27318. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27319. const binding = bindings[ i ];
  27320. if ( -- binding.useCount === 0 ) {
  27321. binding.restoreOriginalState();
  27322. this._takeBackBinding( binding );
  27323. }
  27324. }
  27325. this._takeBackAction( action );
  27326. }
  27327. }
  27328. // Memory manager
  27329. _initMemoryManager() {
  27330. this._actions = []; // 'nActiveActions' followed by inactive ones
  27331. this._nActiveActions = 0;
  27332. this._actionsByClip = {};
  27333. // inside:
  27334. // {
  27335. // knownActions: Array< AnimationAction > - used as prototypes
  27336. // actionByRoot: AnimationAction - lookup
  27337. // }
  27338. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27339. this._nActiveBindings = 0;
  27340. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27341. this._controlInterpolants = []; // same game as above
  27342. this._nActiveControlInterpolants = 0;
  27343. const scope = this;
  27344. this.stats = {
  27345. actions: {
  27346. get total() {
  27347. return scope._actions.length;
  27348. },
  27349. get inUse() {
  27350. return scope._nActiveActions;
  27351. }
  27352. },
  27353. bindings: {
  27354. get total() {
  27355. return scope._bindings.length;
  27356. },
  27357. get inUse() {
  27358. return scope._nActiveBindings;
  27359. }
  27360. },
  27361. controlInterpolants: {
  27362. get total() {
  27363. return scope._controlInterpolants.length;
  27364. },
  27365. get inUse() {
  27366. return scope._nActiveControlInterpolants;
  27367. }
  27368. }
  27369. };
  27370. }
  27371. // Memory management for AnimationAction objects
  27372. _isActiveAction( action ) {
  27373. const index = action._cacheIndex;
  27374. return index !== null && index < this._nActiveActions;
  27375. }
  27376. _addInactiveAction( action, clipUuid, rootUuid ) {
  27377. const actions = this._actions,
  27378. actionsByClip = this._actionsByClip;
  27379. let actionsForClip = actionsByClip[ clipUuid ];
  27380. if ( actionsForClip === undefined ) {
  27381. actionsForClip = {
  27382. knownActions: [ action ],
  27383. actionByRoot: {}
  27384. };
  27385. action._byClipCacheIndex = 0;
  27386. actionsByClip[ clipUuid ] = actionsForClip;
  27387. } else {
  27388. const knownActions = actionsForClip.knownActions;
  27389. action._byClipCacheIndex = knownActions.length;
  27390. knownActions.push( action );
  27391. }
  27392. action._cacheIndex = actions.length;
  27393. actions.push( action );
  27394. actionsForClip.actionByRoot[ rootUuid ] = action;
  27395. }
  27396. _removeInactiveAction( action ) {
  27397. const actions = this._actions,
  27398. lastInactiveAction = actions[ actions.length - 1 ],
  27399. cacheIndex = action._cacheIndex;
  27400. lastInactiveAction._cacheIndex = cacheIndex;
  27401. actions[ cacheIndex ] = lastInactiveAction;
  27402. actions.pop();
  27403. action._cacheIndex = null;
  27404. const clipUuid = action._clip.uuid,
  27405. actionsByClip = this._actionsByClip,
  27406. actionsForClip = actionsByClip[ clipUuid ],
  27407. knownActionsForClip = actionsForClip.knownActions,
  27408. lastKnownAction =
  27409. knownActionsForClip[ knownActionsForClip.length - 1 ],
  27410. byClipCacheIndex = action._byClipCacheIndex;
  27411. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27412. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  27413. knownActionsForClip.pop();
  27414. action._byClipCacheIndex = null;
  27415. const actionByRoot = actionsForClip.actionByRoot,
  27416. rootUuid = ( action._localRoot || this._root ).uuid;
  27417. delete actionByRoot[ rootUuid ];
  27418. if ( knownActionsForClip.length === 0 ) {
  27419. delete actionsByClip[ clipUuid ];
  27420. }
  27421. this._removeInactiveBindingsForAction( action );
  27422. }
  27423. _removeInactiveBindingsForAction( action ) {
  27424. const bindings = action._propertyBindings;
  27425. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  27426. const binding = bindings[ i ];
  27427. if ( -- binding.referenceCount === 0 ) {
  27428. this._removeInactiveBinding( binding );
  27429. }
  27430. }
  27431. }
  27432. _lendAction( action ) {
  27433. // [ active actions | inactive actions ]
  27434. // [ active actions >| inactive actions ]
  27435. // s a
  27436. // <-swap->
  27437. // a s
  27438. const actions = this._actions,
  27439. prevIndex = action._cacheIndex,
  27440. lastActiveIndex = this._nActiveActions ++,
  27441. firstInactiveAction = actions[ lastActiveIndex ];
  27442. action._cacheIndex = lastActiveIndex;
  27443. actions[ lastActiveIndex ] = action;
  27444. firstInactiveAction._cacheIndex = prevIndex;
  27445. actions[ prevIndex ] = firstInactiveAction;
  27446. }
  27447. _takeBackAction( action ) {
  27448. // [ active actions | inactive actions ]
  27449. // [ active actions |< inactive actions ]
  27450. // a s
  27451. // <-swap->
  27452. // s a
  27453. const actions = this._actions,
  27454. prevIndex = action._cacheIndex,
  27455. firstInactiveIndex = -- this._nActiveActions,
  27456. lastActiveAction = actions[ firstInactiveIndex ];
  27457. action._cacheIndex = firstInactiveIndex;
  27458. actions[ firstInactiveIndex ] = action;
  27459. lastActiveAction._cacheIndex = prevIndex;
  27460. actions[ prevIndex ] = lastActiveAction;
  27461. }
  27462. // Memory management for PropertyMixer objects
  27463. _addInactiveBinding( binding, rootUuid, trackName ) {
  27464. const bindingsByRoot = this._bindingsByRootAndName,
  27465. bindings = this._bindings;
  27466. let bindingByName = bindingsByRoot[ rootUuid ];
  27467. if ( bindingByName === undefined ) {
  27468. bindingByName = {};
  27469. bindingsByRoot[ rootUuid ] = bindingByName;
  27470. }
  27471. bindingByName[ trackName ] = binding;
  27472. binding._cacheIndex = bindings.length;
  27473. bindings.push( binding );
  27474. }
  27475. _removeInactiveBinding( binding ) {
  27476. const bindings = this._bindings,
  27477. propBinding = binding.binding,
  27478. rootUuid = propBinding.rootNode.uuid,
  27479. trackName = propBinding.path,
  27480. bindingsByRoot = this._bindingsByRootAndName,
  27481. bindingByName = bindingsByRoot[ rootUuid ],
  27482. lastInactiveBinding = bindings[ bindings.length - 1 ],
  27483. cacheIndex = binding._cacheIndex;
  27484. lastInactiveBinding._cacheIndex = cacheIndex;
  27485. bindings[ cacheIndex ] = lastInactiveBinding;
  27486. bindings.pop();
  27487. delete bindingByName[ trackName ];
  27488. if ( Object.keys( bindingByName ).length === 0 ) {
  27489. delete bindingsByRoot[ rootUuid ];
  27490. }
  27491. }
  27492. _lendBinding( binding ) {
  27493. const bindings = this._bindings,
  27494. prevIndex = binding._cacheIndex,
  27495. lastActiveIndex = this._nActiveBindings ++,
  27496. firstInactiveBinding = bindings[ lastActiveIndex ];
  27497. binding._cacheIndex = lastActiveIndex;
  27498. bindings[ lastActiveIndex ] = binding;
  27499. firstInactiveBinding._cacheIndex = prevIndex;
  27500. bindings[ prevIndex ] = firstInactiveBinding;
  27501. }
  27502. _takeBackBinding( binding ) {
  27503. const bindings = this._bindings,
  27504. prevIndex = binding._cacheIndex,
  27505. firstInactiveIndex = -- this._nActiveBindings,
  27506. lastActiveBinding = bindings[ firstInactiveIndex ];
  27507. binding._cacheIndex = firstInactiveIndex;
  27508. bindings[ firstInactiveIndex ] = binding;
  27509. lastActiveBinding._cacheIndex = prevIndex;
  27510. bindings[ prevIndex ] = lastActiveBinding;
  27511. }
  27512. // Memory management of Interpolants for weight and time scale
  27513. _lendControlInterpolant() {
  27514. const interpolants = this._controlInterpolants,
  27515. lastActiveIndex = this._nActiveControlInterpolants ++;
  27516. let interpolant = interpolants[ lastActiveIndex ];
  27517. if ( interpolant === undefined ) {
  27518. interpolant = new LinearInterpolant(
  27519. new Float32Array( 2 ), new Float32Array( 2 ),
  27520. 1, _controlInterpolantsResultBuffer );
  27521. interpolant.__cacheIndex = lastActiveIndex;
  27522. interpolants[ lastActiveIndex ] = interpolant;
  27523. }
  27524. return interpolant;
  27525. }
  27526. _takeBackControlInterpolant( interpolant ) {
  27527. const interpolants = this._controlInterpolants,
  27528. prevIndex = interpolant.__cacheIndex,
  27529. firstInactiveIndex = -- this._nActiveControlInterpolants,
  27530. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  27531. interpolant.__cacheIndex = firstInactiveIndex;
  27532. interpolants[ firstInactiveIndex ] = interpolant;
  27533. lastActiveInterpolant.__cacheIndex = prevIndex;
  27534. interpolants[ prevIndex ] = lastActiveInterpolant;
  27535. }
  27536. // return an action for a clip optionally using a custom root target
  27537. // object (this method allocates a lot of dynamic memory in case a
  27538. // previously unknown clip/root combination is specified)
  27539. clipAction( clip, optionalRoot, blendMode ) {
  27540. const root = optionalRoot || this._root,
  27541. rootUuid = root.uuid;
  27542. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  27543. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  27544. const actionsForClip = this._actionsByClip[ clipUuid ];
  27545. let prototypeAction = null;
  27546. if ( blendMode === undefined ) {
  27547. if ( clipObject !== null ) {
  27548. blendMode = clipObject.blendMode;
  27549. } else {
  27550. blendMode = NormalAnimationBlendMode;
  27551. }
  27552. }
  27553. if ( actionsForClip !== undefined ) {
  27554. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  27555. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  27556. return existingAction;
  27557. }
  27558. // we know the clip, so we don't have to parse all
  27559. // the bindings again but can just copy
  27560. prototypeAction = actionsForClip.knownActions[ 0 ];
  27561. // also, take the clip from the prototype action
  27562. if ( clipObject === null )
  27563. clipObject = prototypeAction._clip;
  27564. }
  27565. // clip must be known when specified via string
  27566. if ( clipObject === null ) return null;
  27567. // allocate all resources required to run it
  27568. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  27569. this._bindAction( newAction, prototypeAction );
  27570. // and make the action known to the memory manager
  27571. this._addInactiveAction( newAction, clipUuid, rootUuid );
  27572. return newAction;
  27573. }
  27574. // get an existing action
  27575. existingAction( clip, optionalRoot ) {
  27576. const root = optionalRoot || this._root,
  27577. rootUuid = root.uuid,
  27578. clipObject = typeof clip === 'string' ?
  27579. AnimationClip.findByName( root, clip ) : clip,
  27580. clipUuid = clipObject ? clipObject.uuid : clip,
  27581. actionsForClip = this._actionsByClip[ clipUuid ];
  27582. if ( actionsForClip !== undefined ) {
  27583. return actionsForClip.actionByRoot[ rootUuid ] || null;
  27584. }
  27585. return null;
  27586. }
  27587. // deactivates all previously scheduled actions
  27588. stopAllAction() {
  27589. const actions = this._actions,
  27590. nActions = this._nActiveActions;
  27591. for ( let i = nActions - 1; i >= 0; -- i ) {
  27592. actions[ i ].stop();
  27593. }
  27594. return this;
  27595. }
  27596. // advance the time and update apply the animation
  27597. update( deltaTime ) {
  27598. deltaTime *= this.timeScale;
  27599. const actions = this._actions,
  27600. nActions = this._nActiveActions,
  27601. time = this.time += deltaTime,
  27602. timeDirection = Math.sign( deltaTime ),
  27603. accuIndex = this._accuIndex ^= 1;
  27604. // run active actions
  27605. for ( let i = 0; i !== nActions; ++ i ) {
  27606. const action = actions[ i ];
  27607. action._update( time, deltaTime, timeDirection, accuIndex );
  27608. }
  27609. // update scene graph
  27610. const bindings = this._bindings,
  27611. nBindings = this._nActiveBindings;
  27612. for ( let i = 0; i !== nBindings; ++ i ) {
  27613. bindings[ i ].apply( accuIndex );
  27614. }
  27615. return this;
  27616. }
  27617. // Allows you to seek to a specific time in an animation.
  27618. setTime( timeInSeconds ) {
  27619. this.time = 0; // Zero out time attribute for AnimationMixer object;
  27620. for ( let i = 0; i < this._actions.length; i ++ ) {
  27621. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  27622. }
  27623. return this.update( timeInSeconds ); // Update used to set exact time. Returns "this" AnimationMixer object.
  27624. }
  27625. // return this mixer's root target object
  27626. getRoot() {
  27627. return this._root;
  27628. }
  27629. // free all resources specific to a particular clip
  27630. uncacheClip( clip ) {
  27631. const actions = this._actions,
  27632. clipUuid = clip.uuid,
  27633. actionsByClip = this._actionsByClip,
  27634. actionsForClip = actionsByClip[ clipUuid ];
  27635. if ( actionsForClip !== undefined ) {
  27636. // note: just calling _removeInactiveAction would mess up the
  27637. // iteration state and also require updating the state we can
  27638. // just throw away
  27639. const actionsToRemove = actionsForClip.knownActions;
  27640. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  27641. const action = actionsToRemove[ i ];
  27642. this._deactivateAction( action );
  27643. const cacheIndex = action._cacheIndex,
  27644. lastInactiveAction = actions[ actions.length - 1 ];
  27645. action._cacheIndex = null;
  27646. action._byClipCacheIndex = null;
  27647. lastInactiveAction._cacheIndex = cacheIndex;
  27648. actions[ cacheIndex ] = lastInactiveAction;
  27649. actions.pop();
  27650. this._removeInactiveBindingsForAction( action );
  27651. }
  27652. delete actionsByClip[ clipUuid ];
  27653. }
  27654. }
  27655. // free all resources specific to a particular root target object
  27656. uncacheRoot( root ) {
  27657. const rootUuid = root.uuid,
  27658. actionsByClip = this._actionsByClip;
  27659. for ( const clipUuid in actionsByClip ) {
  27660. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  27661. action = actionByRoot[ rootUuid ];
  27662. if ( action !== undefined ) {
  27663. this._deactivateAction( action );
  27664. this._removeInactiveAction( action );
  27665. }
  27666. }
  27667. const bindingsByRoot = this._bindingsByRootAndName,
  27668. bindingByName = bindingsByRoot[ rootUuid ];
  27669. if ( bindingByName !== undefined ) {
  27670. for ( const trackName in bindingByName ) {
  27671. const binding = bindingByName[ trackName ];
  27672. binding.restoreOriginalState();
  27673. this._removeInactiveBinding( binding );
  27674. }
  27675. }
  27676. }
  27677. // remove a targeted clip from the cache
  27678. uncacheAction( clip, optionalRoot ) {
  27679. const action = this.existingAction( clip, optionalRoot );
  27680. if ( action !== null ) {
  27681. this._deactivateAction( action );
  27682. this._removeInactiveAction( action );
  27683. }
  27684. }
  27685. }
  27686. class Uniform {
  27687. constructor( value ) {
  27688. this.value = value;
  27689. }
  27690. clone() {
  27691. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  27692. }
  27693. }
  27694. let id = 0;
  27695. class UniformsGroup extends EventDispatcher {
  27696. constructor() {
  27697. super();
  27698. this.isUniformsGroup = true;
  27699. Object.defineProperty( this, 'id', { value: id ++ } );
  27700. this.name = '';
  27701. this.usage = StaticDrawUsage;
  27702. this.uniforms = [];
  27703. }
  27704. add( uniform ) {
  27705. this.uniforms.push( uniform );
  27706. return this;
  27707. }
  27708. remove( uniform ) {
  27709. const index = this.uniforms.indexOf( uniform );
  27710. if ( index !== - 1 ) this.uniforms.splice( index, 1 );
  27711. return this;
  27712. }
  27713. setName( name ) {
  27714. this.name = name;
  27715. return this;
  27716. }
  27717. setUsage( value ) {
  27718. this.usage = value;
  27719. return this;
  27720. }
  27721. dispose() {
  27722. this.dispatchEvent( { type: 'dispose' } );
  27723. return this;
  27724. }
  27725. copy( source ) {
  27726. this.name = source.name;
  27727. this.usage = source.usage;
  27728. const uniformsSource = source.uniforms;
  27729. this.uniforms.length = 0;
  27730. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  27731. this.uniforms.push( uniformsSource[ i ].clone() );
  27732. }
  27733. return this;
  27734. }
  27735. clone() {
  27736. return new this.constructor().copy( this );
  27737. }
  27738. }
  27739. class InstancedInterleavedBuffer extends InterleavedBuffer {
  27740. constructor( array, stride, meshPerAttribute = 1 ) {
  27741. super( array, stride );
  27742. this.isInstancedInterleavedBuffer = true;
  27743. this.meshPerAttribute = meshPerAttribute;
  27744. }
  27745. copy( source ) {
  27746. super.copy( source );
  27747. this.meshPerAttribute = source.meshPerAttribute;
  27748. return this;
  27749. }
  27750. clone( data ) {
  27751. const ib = super.clone( data );
  27752. ib.meshPerAttribute = this.meshPerAttribute;
  27753. return ib;
  27754. }
  27755. toJSON( data ) {
  27756. const json = super.toJSON( data );
  27757. json.isInstancedInterleavedBuffer = true;
  27758. json.meshPerAttribute = this.meshPerAttribute;
  27759. return json;
  27760. }
  27761. }
  27762. class GLBufferAttribute {
  27763. constructor( buffer, type, itemSize, elementSize, count ) {
  27764. this.isGLBufferAttribute = true;
  27765. this.buffer = buffer;
  27766. this.type = type;
  27767. this.itemSize = itemSize;
  27768. this.elementSize = elementSize;
  27769. this.count = count;
  27770. this.version = 0;
  27771. }
  27772. set needsUpdate( value ) {
  27773. if ( value === true ) this.version ++;
  27774. }
  27775. setBuffer( buffer ) {
  27776. this.buffer = buffer;
  27777. return this;
  27778. }
  27779. setType( type, elementSize ) {
  27780. this.type = type;
  27781. this.elementSize = elementSize;
  27782. return this;
  27783. }
  27784. setItemSize( itemSize ) {
  27785. this.itemSize = itemSize;
  27786. return this;
  27787. }
  27788. setCount( count ) {
  27789. this.count = count;
  27790. return this;
  27791. }
  27792. }
  27793. class Raycaster {
  27794. constructor( origin, direction, near = 0, far = Infinity ) {
  27795. this.ray = new Ray( origin, direction );
  27796. // direction is assumed to be normalized (for accurate distance calculations)
  27797. this.near = near;
  27798. this.far = far;
  27799. this.camera = null;
  27800. this.layers = new Layers();
  27801. this.params = {
  27802. Mesh: {},
  27803. Line: { threshold: 1 },
  27804. LOD: {},
  27805. Points: { threshold: 1 },
  27806. Sprite: {}
  27807. };
  27808. }
  27809. set( origin, direction ) {
  27810. // direction is assumed to be normalized (for accurate distance calculations)
  27811. this.ray.set( origin, direction );
  27812. }
  27813. setFromCamera( coords, camera ) {
  27814. if ( camera.isPerspectiveCamera ) {
  27815. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  27816. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  27817. this.camera = camera;
  27818. } else if ( camera.isOrthographicCamera ) {
  27819. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  27820. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  27821. this.camera = camera;
  27822. } else {
  27823. console.error( 'THREE.Raycaster: Unsupported camera type: ' + camera.type );
  27824. }
  27825. }
  27826. intersectObject( object, recursive = true, intersects = [] ) {
  27827. intersectObject( object, this, intersects, recursive );
  27828. intersects.sort( ascSort );
  27829. return intersects;
  27830. }
  27831. intersectObjects( objects, recursive = true, intersects = [] ) {
  27832. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  27833. intersectObject( objects[ i ], this, intersects, recursive );
  27834. }
  27835. intersects.sort( ascSort );
  27836. return intersects;
  27837. }
  27838. }
  27839. function ascSort( a, b ) {
  27840. return a.distance - b.distance;
  27841. }
  27842. function intersectObject( object, raycaster, intersects, recursive ) {
  27843. if ( object.layers.test( raycaster.layers ) ) {
  27844. object.raycast( raycaster, intersects );
  27845. }
  27846. if ( recursive === true ) {
  27847. const children = object.children;
  27848. for ( let i = 0, l = children.length; i < l; i ++ ) {
  27849. intersectObject( children[ i ], raycaster, intersects, true );
  27850. }
  27851. }
  27852. }
  27853. /**
  27854. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27855. *
  27856. * The polar angle (phi) is measured from the positive y-axis. The positive y-axis is up.
  27857. * The azimuthal angle (theta) is measured from the positive z-axis.
  27858. */
  27859. class Spherical {
  27860. constructor( radius = 1, phi = 0, theta = 0 ) {
  27861. this.radius = radius;
  27862. this.phi = phi; // polar angle
  27863. this.theta = theta; // azimuthal angle
  27864. return this;
  27865. }
  27866. set( radius, phi, theta ) {
  27867. this.radius = radius;
  27868. this.phi = phi;
  27869. this.theta = theta;
  27870. return this;
  27871. }
  27872. copy( other ) {
  27873. this.radius = other.radius;
  27874. this.phi = other.phi;
  27875. this.theta = other.theta;
  27876. return this;
  27877. }
  27878. // restrict phi to be between EPS and PI-EPS
  27879. makeSafe() {
  27880. const EPS = 0.000001;
  27881. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  27882. return this;
  27883. }
  27884. setFromVector3( v ) {
  27885. return this.setFromCartesianCoords( v.x, v.y, v.z );
  27886. }
  27887. setFromCartesianCoords( x, y, z ) {
  27888. this.radius = Math.sqrt( x * x + y * y + z * z );
  27889. if ( this.radius === 0 ) {
  27890. this.theta = 0;
  27891. this.phi = 0;
  27892. } else {
  27893. this.theta = Math.atan2( x, z );
  27894. this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
  27895. }
  27896. return this;
  27897. }
  27898. clone() {
  27899. return new this.constructor().copy( this );
  27900. }
  27901. }
  27902. /**
  27903. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  27904. */
  27905. class Cylindrical {
  27906. constructor( radius = 1, theta = 0, y = 0 ) {
  27907. this.radius = radius; // distance from the origin to a point in the x-z plane
  27908. this.theta = theta; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  27909. this.y = y; // height above the x-z plane
  27910. return this;
  27911. }
  27912. set( radius, theta, y ) {
  27913. this.radius = radius;
  27914. this.theta = theta;
  27915. this.y = y;
  27916. return this;
  27917. }
  27918. copy( other ) {
  27919. this.radius = other.radius;
  27920. this.theta = other.theta;
  27921. this.y = other.y;
  27922. return this;
  27923. }
  27924. setFromVector3( v ) {
  27925. return this.setFromCartesianCoords( v.x, v.y, v.z );
  27926. }
  27927. setFromCartesianCoords( x, y, z ) {
  27928. this.radius = Math.sqrt( x * x + z * z );
  27929. this.theta = Math.atan2( x, z );
  27930. this.y = y;
  27931. return this;
  27932. }
  27933. clone() {
  27934. return new this.constructor().copy( this );
  27935. }
  27936. }
  27937. const _vector$4 = /*@__PURE__*/ new Vector2();
  27938. class Box2 {
  27939. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  27940. this.isBox2 = true;
  27941. this.min = min;
  27942. this.max = max;
  27943. }
  27944. set( min, max ) {
  27945. this.min.copy( min );
  27946. this.max.copy( max );
  27947. return this;
  27948. }
  27949. setFromPoints( points ) {
  27950. this.makeEmpty();
  27951. for ( let i = 0, il = points.length; i < il; i ++ ) {
  27952. this.expandByPoint( points[ i ] );
  27953. }
  27954. return this;
  27955. }
  27956. setFromCenterAndSize( center, size ) {
  27957. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  27958. this.min.copy( center ).sub( halfSize );
  27959. this.max.copy( center ).add( halfSize );
  27960. return this;
  27961. }
  27962. clone() {
  27963. return new this.constructor().copy( this );
  27964. }
  27965. copy( box ) {
  27966. this.min.copy( box.min );
  27967. this.max.copy( box.max );
  27968. return this;
  27969. }
  27970. makeEmpty() {
  27971. this.min.x = this.min.y = + Infinity;
  27972. this.max.x = this.max.y = - Infinity;
  27973. return this;
  27974. }
  27975. isEmpty() {
  27976. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  27977. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  27978. }
  27979. getCenter( target ) {
  27980. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  27981. }
  27982. getSize( target ) {
  27983. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  27984. }
  27985. expandByPoint( point ) {
  27986. this.min.min( point );
  27987. this.max.max( point );
  27988. return this;
  27989. }
  27990. expandByVector( vector ) {
  27991. this.min.sub( vector );
  27992. this.max.add( vector );
  27993. return this;
  27994. }
  27995. expandByScalar( scalar ) {
  27996. this.min.addScalar( - scalar );
  27997. this.max.addScalar( scalar );
  27998. return this;
  27999. }
  28000. containsPoint( point ) {
  28001. return point.x < this.min.x || point.x > this.max.x ||
  28002. point.y < this.min.y || point.y > this.max.y ? false : true;
  28003. }
  28004. containsBox( box ) {
  28005. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  28006. this.min.y <= box.min.y && box.max.y <= this.max.y;
  28007. }
  28008. getParameter( point, target ) {
  28009. // This can potentially have a divide by zero if the box
  28010. // has a size dimension of 0.
  28011. return target.set(
  28012. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  28013. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  28014. );
  28015. }
  28016. intersectsBox( box ) {
  28017. // using 4 splitting planes to rule out intersections
  28018. return box.max.x < this.min.x || box.min.x > this.max.x ||
  28019. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  28020. }
  28021. clampPoint( point, target ) {
  28022. return target.copy( point ).clamp( this.min, this.max );
  28023. }
  28024. distanceToPoint( point ) {
  28025. const clampedPoint = _vector$4.copy( point ).clamp( this.min, this.max );
  28026. return clampedPoint.sub( point ).length();
  28027. }
  28028. intersect( box ) {
  28029. this.min.max( box.min );
  28030. this.max.min( box.max );
  28031. return this;
  28032. }
  28033. union( box ) {
  28034. this.min.min( box.min );
  28035. this.max.max( box.max );
  28036. return this;
  28037. }
  28038. translate( offset ) {
  28039. this.min.add( offset );
  28040. this.max.add( offset );
  28041. return this;
  28042. }
  28043. equals( box ) {
  28044. return box.min.equals( this.min ) && box.max.equals( this.max );
  28045. }
  28046. }
  28047. const _startP = /*@__PURE__*/ new Vector3();
  28048. const _startEnd = /*@__PURE__*/ new Vector3();
  28049. class Line3 {
  28050. constructor( start = new Vector3(), end = new Vector3() ) {
  28051. this.start = start;
  28052. this.end = end;
  28053. }
  28054. set( start, end ) {
  28055. this.start.copy( start );
  28056. this.end.copy( end );
  28057. return this;
  28058. }
  28059. copy( line ) {
  28060. this.start.copy( line.start );
  28061. this.end.copy( line.end );
  28062. return this;
  28063. }
  28064. getCenter( target ) {
  28065. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  28066. }
  28067. delta( target ) {
  28068. return target.subVectors( this.end, this.start );
  28069. }
  28070. distanceSq() {
  28071. return this.start.distanceToSquared( this.end );
  28072. }
  28073. distance() {
  28074. return this.start.distanceTo( this.end );
  28075. }
  28076. at( t, target ) {
  28077. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28078. }
  28079. closestPointToPointParameter( point, clampToLine ) {
  28080. _startP.subVectors( point, this.start );
  28081. _startEnd.subVectors( this.end, this.start );
  28082. const startEnd2 = _startEnd.dot( _startEnd );
  28083. const startEnd_startP = _startEnd.dot( _startP );
  28084. let t = startEnd_startP / startEnd2;
  28085. if ( clampToLine ) {
  28086. t = clamp( t, 0, 1 );
  28087. }
  28088. return t;
  28089. }
  28090. closestPointToPoint( point, clampToLine, target ) {
  28091. const t = this.closestPointToPointParameter( point, clampToLine );
  28092. return this.delta( target ).multiplyScalar( t ).add( this.start );
  28093. }
  28094. applyMatrix4( matrix ) {
  28095. this.start.applyMatrix4( matrix );
  28096. this.end.applyMatrix4( matrix );
  28097. return this;
  28098. }
  28099. equals( line ) {
  28100. return line.start.equals( this.start ) && line.end.equals( this.end );
  28101. }
  28102. clone() {
  28103. return new this.constructor().copy( this );
  28104. }
  28105. }
  28106. const _vector$3 = /*@__PURE__*/ new Vector3();
  28107. class SpotLightHelper extends Object3D {
  28108. constructor( light, color ) {
  28109. super();
  28110. this.light = light;
  28111. this.light.updateMatrixWorld();
  28112. this.matrix = light.matrixWorld;
  28113. this.matrixAutoUpdate = false;
  28114. this.color = color;
  28115. const geometry = new BufferGeometry();
  28116. const positions = [
  28117. 0, 0, 0, 0, 0, 1,
  28118. 0, 0, 0, 1, 0, 1,
  28119. 0, 0, 0, - 1, 0, 1,
  28120. 0, 0, 0, 0, 1, 1,
  28121. 0, 0, 0, 0, - 1, 1
  28122. ];
  28123. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  28124. const p1 = ( i / l ) * Math.PI * 2;
  28125. const p2 = ( j / l ) * Math.PI * 2;
  28126. positions.push(
  28127. Math.cos( p1 ), Math.sin( p1 ), 1,
  28128. Math.cos( p2 ), Math.sin( p2 ), 1
  28129. );
  28130. }
  28131. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28132. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28133. this.cone = new LineSegments( geometry, material );
  28134. this.add( this.cone );
  28135. this.update();
  28136. }
  28137. dispose() {
  28138. this.cone.geometry.dispose();
  28139. this.cone.material.dispose();
  28140. }
  28141. update() {
  28142. this.light.updateMatrixWorld();
  28143. const coneLength = this.light.distance ? this.light.distance : 1000;
  28144. const coneWidth = coneLength * Math.tan( this.light.angle );
  28145. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  28146. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  28147. this.cone.lookAt( _vector$3 );
  28148. if ( this.color !== undefined ) {
  28149. this.cone.material.color.set( this.color );
  28150. } else {
  28151. this.cone.material.color.copy( this.light.color );
  28152. }
  28153. }
  28154. }
  28155. const _vector$2 = /*@__PURE__*/ new Vector3();
  28156. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  28157. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  28158. class SkeletonHelper extends LineSegments {
  28159. constructor( object ) {
  28160. const bones = getBoneList( object );
  28161. const geometry = new BufferGeometry();
  28162. const vertices = [];
  28163. const colors = [];
  28164. const color1 = new Color( 0, 0, 1 );
  28165. const color2 = new Color( 0, 1, 0 );
  28166. for ( let i = 0; i < bones.length; i ++ ) {
  28167. const bone = bones[ i ];
  28168. if ( bone.parent && bone.parent.isBone ) {
  28169. vertices.push( 0, 0, 0 );
  28170. vertices.push( 0, 0, 0 );
  28171. colors.push( color1.r, color1.g, color1.b );
  28172. colors.push( color2.r, color2.g, color2.b );
  28173. }
  28174. }
  28175. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28176. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28177. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  28178. super( geometry, material );
  28179. this.isSkeletonHelper = true;
  28180. this.type = 'SkeletonHelper';
  28181. this.root = object;
  28182. this.bones = bones;
  28183. this.matrix = object.matrixWorld;
  28184. this.matrixAutoUpdate = false;
  28185. }
  28186. updateMatrixWorld( force ) {
  28187. const bones = this.bones;
  28188. const geometry = this.geometry;
  28189. const position = geometry.getAttribute( 'position' );
  28190. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  28191. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  28192. const bone = bones[ i ];
  28193. if ( bone.parent && bone.parent.isBone ) {
  28194. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  28195. _vector$2.setFromMatrixPosition( _boneMatrix );
  28196. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  28197. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  28198. _vector$2.setFromMatrixPosition( _boneMatrix );
  28199. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  28200. j += 2;
  28201. }
  28202. }
  28203. geometry.getAttribute( 'position' ).needsUpdate = true;
  28204. super.updateMatrixWorld( force );
  28205. }
  28206. }
  28207. function getBoneList( object ) {
  28208. const boneList = [];
  28209. if ( object.isBone === true ) {
  28210. boneList.push( object );
  28211. }
  28212. for ( let i = 0; i < object.children.length; i ++ ) {
  28213. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  28214. }
  28215. return boneList;
  28216. }
  28217. class PointLightHelper extends Mesh {
  28218. constructor( light, sphereSize, color ) {
  28219. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  28220. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28221. super( geometry, material );
  28222. this.light = light;
  28223. this.light.updateMatrixWorld();
  28224. this.color = color;
  28225. this.type = 'PointLightHelper';
  28226. this.matrix = this.light.matrixWorld;
  28227. this.matrixAutoUpdate = false;
  28228. this.update();
  28229. /*
  28230. // TODO: delete this comment?
  28231. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  28232. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28233. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28234. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28235. const d = light.distance;
  28236. if ( d === 0.0 ) {
  28237. this.lightDistance.visible = false;
  28238. } else {
  28239. this.lightDistance.scale.set( d, d, d );
  28240. }
  28241. this.add( this.lightDistance );
  28242. */
  28243. }
  28244. dispose() {
  28245. this.geometry.dispose();
  28246. this.material.dispose();
  28247. }
  28248. update() {
  28249. if ( this.color !== undefined ) {
  28250. this.material.color.set( this.color );
  28251. } else {
  28252. this.material.color.copy( this.light.color );
  28253. }
  28254. /*
  28255. const d = this.light.distance;
  28256. if ( d === 0.0 ) {
  28257. this.lightDistance.visible = false;
  28258. } else {
  28259. this.lightDistance.visible = true;
  28260. this.lightDistance.scale.set( d, d, d );
  28261. }
  28262. */
  28263. }
  28264. }
  28265. const _vector$1 = /*@__PURE__*/ new Vector3();
  28266. const _color1 = /*@__PURE__*/ new Color();
  28267. const _color2 = /*@__PURE__*/ new Color();
  28268. class HemisphereLightHelper extends Object3D {
  28269. constructor( light, size, color ) {
  28270. super();
  28271. this.light = light;
  28272. this.light.updateMatrixWorld();
  28273. this.matrix = light.matrixWorld;
  28274. this.matrixAutoUpdate = false;
  28275. this.color = color;
  28276. const geometry = new OctahedronGeometry( size );
  28277. geometry.rotateY( Math.PI * 0.5 );
  28278. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  28279. if ( this.color === undefined ) this.material.vertexColors = true;
  28280. const position = geometry.getAttribute( 'position' );
  28281. const colors = new Float32Array( position.count * 3 );
  28282. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  28283. this.add( new Mesh( geometry, this.material ) );
  28284. this.update();
  28285. }
  28286. dispose() {
  28287. this.children[ 0 ].geometry.dispose();
  28288. this.children[ 0 ].material.dispose();
  28289. }
  28290. update() {
  28291. const mesh = this.children[ 0 ];
  28292. if ( this.color !== undefined ) {
  28293. this.material.color.set( this.color );
  28294. } else {
  28295. const colors = mesh.geometry.getAttribute( 'color' );
  28296. _color1.copy( this.light.color );
  28297. _color2.copy( this.light.groundColor );
  28298. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  28299. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  28300. colors.setXYZ( i, color.r, color.g, color.b );
  28301. }
  28302. colors.needsUpdate = true;
  28303. }
  28304. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  28305. }
  28306. }
  28307. class GridHelper extends LineSegments {
  28308. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  28309. color1 = new Color( color1 );
  28310. color2 = new Color( color2 );
  28311. const center = divisions / 2;
  28312. const step = size / divisions;
  28313. const halfSize = size / 2;
  28314. const vertices = [], colors = [];
  28315. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  28316. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  28317. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  28318. const color = i === center ? color1 : color2;
  28319. color.toArray( colors, j ); j += 3;
  28320. color.toArray( colors, j ); j += 3;
  28321. color.toArray( colors, j ); j += 3;
  28322. color.toArray( colors, j ); j += 3;
  28323. }
  28324. const geometry = new BufferGeometry();
  28325. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28326. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28327. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28328. super( geometry, material );
  28329. this.type = 'GridHelper';
  28330. }
  28331. }
  28332. class PolarGridHelper extends LineSegments {
  28333. constructor( radius = 10, radials = 16, circles = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  28334. color1 = new Color( color1 );
  28335. color2 = new Color( color2 );
  28336. const vertices = [];
  28337. const colors = [];
  28338. // create the radials
  28339. for ( let i = 0; i <= radials; i ++ ) {
  28340. const v = ( i / radials ) * ( Math.PI * 2 );
  28341. const x = Math.sin( v ) * radius;
  28342. const z = Math.cos( v ) * radius;
  28343. vertices.push( 0, 0, 0 );
  28344. vertices.push( x, 0, z );
  28345. const color = ( i & 1 ) ? color1 : color2;
  28346. colors.push( color.r, color.g, color.b );
  28347. colors.push( color.r, color.g, color.b );
  28348. }
  28349. // create the circles
  28350. for ( let i = 0; i <= circles; i ++ ) {
  28351. const color = ( i & 1 ) ? color1 : color2;
  28352. const r = radius - ( radius / circles * i );
  28353. for ( let j = 0; j < divisions; j ++ ) {
  28354. // first vertex
  28355. let v = ( j / divisions ) * ( Math.PI * 2 );
  28356. let x = Math.sin( v ) * r;
  28357. let z = Math.cos( v ) * r;
  28358. vertices.push( x, 0, z );
  28359. colors.push( color.r, color.g, color.b );
  28360. // second vertex
  28361. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  28362. x = Math.sin( v ) * r;
  28363. z = Math.cos( v ) * r;
  28364. vertices.push( x, 0, z );
  28365. colors.push( color.r, color.g, color.b );
  28366. }
  28367. }
  28368. const geometry = new BufferGeometry();
  28369. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28370. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28371. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28372. super( geometry, material );
  28373. this.type = 'PolarGridHelper';
  28374. }
  28375. }
  28376. const _v1 = /*@__PURE__*/ new Vector3();
  28377. const _v2 = /*@__PURE__*/ new Vector3();
  28378. const _v3 = /*@__PURE__*/ new Vector3();
  28379. class DirectionalLightHelper extends Object3D {
  28380. constructor( light, size, color ) {
  28381. super();
  28382. this.light = light;
  28383. this.light.updateMatrixWorld();
  28384. this.matrix = light.matrixWorld;
  28385. this.matrixAutoUpdate = false;
  28386. this.color = color;
  28387. if ( size === undefined ) size = 1;
  28388. let geometry = new BufferGeometry();
  28389. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  28390. - size, size, 0,
  28391. size, size, 0,
  28392. size, - size, 0,
  28393. - size, - size, 0,
  28394. - size, size, 0
  28395. ], 3 ) );
  28396. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  28397. this.lightPlane = new Line( geometry, material );
  28398. this.add( this.lightPlane );
  28399. geometry = new BufferGeometry();
  28400. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  28401. this.targetLine = new Line( geometry, material );
  28402. this.add( this.targetLine );
  28403. this.update();
  28404. }
  28405. dispose() {
  28406. this.lightPlane.geometry.dispose();
  28407. this.lightPlane.material.dispose();
  28408. this.targetLine.geometry.dispose();
  28409. this.targetLine.material.dispose();
  28410. }
  28411. update() {
  28412. _v1.setFromMatrixPosition( this.light.matrixWorld );
  28413. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  28414. _v3.subVectors( _v2, _v1 );
  28415. this.lightPlane.lookAt( _v2 );
  28416. if ( this.color !== undefined ) {
  28417. this.lightPlane.material.color.set( this.color );
  28418. this.targetLine.material.color.set( this.color );
  28419. } else {
  28420. this.lightPlane.material.color.copy( this.light.color );
  28421. this.targetLine.material.color.copy( this.light.color );
  28422. }
  28423. this.targetLine.lookAt( _v2 );
  28424. this.targetLine.scale.z = _v3.length();
  28425. }
  28426. }
  28427. const _vector = /*@__PURE__*/ new Vector3();
  28428. const _camera = /*@__PURE__*/ new Camera();
  28429. /**
  28430. * - shows frustum, line of sight and up of the camera
  28431. * - suitable for fast updates
  28432. * - based on frustum visualization in lightgl.js shadowmap example
  28433. * https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html
  28434. */
  28435. class CameraHelper extends LineSegments {
  28436. constructor( camera ) {
  28437. const geometry = new BufferGeometry();
  28438. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  28439. const vertices = [];
  28440. const colors = [];
  28441. const pointMap = {};
  28442. // near
  28443. addLine( 'n1', 'n2' );
  28444. addLine( 'n2', 'n4' );
  28445. addLine( 'n4', 'n3' );
  28446. addLine( 'n3', 'n1' );
  28447. // far
  28448. addLine( 'f1', 'f2' );
  28449. addLine( 'f2', 'f4' );
  28450. addLine( 'f4', 'f3' );
  28451. addLine( 'f3', 'f1' );
  28452. // sides
  28453. addLine( 'n1', 'f1' );
  28454. addLine( 'n2', 'f2' );
  28455. addLine( 'n3', 'f3' );
  28456. addLine( 'n4', 'f4' );
  28457. // cone
  28458. addLine( 'p', 'n1' );
  28459. addLine( 'p', 'n2' );
  28460. addLine( 'p', 'n3' );
  28461. addLine( 'p', 'n4' );
  28462. // up
  28463. addLine( 'u1', 'u2' );
  28464. addLine( 'u2', 'u3' );
  28465. addLine( 'u3', 'u1' );
  28466. // target
  28467. addLine( 'c', 't' );
  28468. addLine( 'p', 'c' );
  28469. // cross
  28470. addLine( 'cn1', 'cn2' );
  28471. addLine( 'cn3', 'cn4' );
  28472. addLine( 'cf1', 'cf2' );
  28473. addLine( 'cf3', 'cf4' );
  28474. function addLine( a, b ) {
  28475. addPoint( a );
  28476. addPoint( b );
  28477. }
  28478. function addPoint( id ) {
  28479. vertices.push( 0, 0, 0 );
  28480. colors.push( 0, 0, 0 );
  28481. if ( pointMap[ id ] === undefined ) {
  28482. pointMap[ id ] = [];
  28483. }
  28484. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  28485. }
  28486. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28487. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28488. super( geometry, material );
  28489. this.type = 'CameraHelper';
  28490. this.camera = camera;
  28491. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  28492. this.matrix = camera.matrixWorld;
  28493. this.matrixAutoUpdate = false;
  28494. this.pointMap = pointMap;
  28495. this.update();
  28496. // colors
  28497. const colorFrustum = new Color( 0xffaa00 );
  28498. const colorCone = new Color( 0xff0000 );
  28499. const colorUp = new Color( 0x00aaff );
  28500. const colorTarget = new Color( 0xffffff );
  28501. const colorCross = new Color( 0x333333 );
  28502. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  28503. }
  28504. setColors( frustum, cone, up, target, cross ) {
  28505. const geometry = this.geometry;
  28506. const colorAttribute = geometry.getAttribute( 'color' );
  28507. // near
  28508. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  28509. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  28510. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  28511. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  28512. // far
  28513. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  28514. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  28515. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  28516. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  28517. // sides
  28518. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  28519. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  28520. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  28521. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  28522. // cone
  28523. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  28524. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  28525. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  28526. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  28527. // up
  28528. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  28529. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  28530. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  28531. // target
  28532. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  28533. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  28534. // cross
  28535. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  28536. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  28537. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  28538. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  28539. colorAttribute.needsUpdate = true;
  28540. }
  28541. update() {
  28542. const geometry = this.geometry;
  28543. const pointMap = this.pointMap;
  28544. const w = 1, h = 1;
  28545. // we need just camera projection matrix inverse
  28546. // world matrix must be identity
  28547. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  28548. // center / target
  28549. setPoint( 'c', pointMap, geometry, _camera, 0, 0, - 1 );
  28550. setPoint( 't', pointMap, geometry, _camera, 0, 0, 1 );
  28551. // near
  28552. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, - 1 );
  28553. setPoint( 'n2', pointMap, geometry, _camera, w, - h, - 1 );
  28554. setPoint( 'n3', pointMap, geometry, _camera, - w, h, - 1 );
  28555. setPoint( 'n4', pointMap, geometry, _camera, w, h, - 1 );
  28556. // far
  28557. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, 1 );
  28558. setPoint( 'f2', pointMap, geometry, _camera, w, - h, 1 );
  28559. setPoint( 'f3', pointMap, geometry, _camera, - w, h, 1 );
  28560. setPoint( 'f4', pointMap, geometry, _camera, w, h, 1 );
  28561. // up
  28562. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, - 1 );
  28563. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, - 1 );
  28564. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, - 1 );
  28565. // cross
  28566. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, 1 );
  28567. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, 1 );
  28568. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, 1 );
  28569. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, 1 );
  28570. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, - 1 );
  28571. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, - 1 );
  28572. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, - 1 );
  28573. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, - 1 );
  28574. geometry.getAttribute( 'position' ).needsUpdate = true;
  28575. }
  28576. dispose() {
  28577. this.geometry.dispose();
  28578. this.material.dispose();
  28579. }
  28580. }
  28581. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  28582. _vector.set( x, y, z ).unproject( camera );
  28583. const points = pointMap[ point ];
  28584. if ( points !== undefined ) {
  28585. const position = geometry.getAttribute( 'position' );
  28586. for ( let i = 0, l = points.length; i < l; i ++ ) {
  28587. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  28588. }
  28589. }
  28590. }
  28591. const _box = /*@__PURE__*/ new Box3();
  28592. class BoxHelper extends LineSegments {
  28593. constructor( object, color = 0xffff00 ) {
  28594. 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 ] );
  28595. const positions = new Float32Array( 8 * 3 );
  28596. const geometry = new BufferGeometry();
  28597. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  28598. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  28599. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28600. this.object = object;
  28601. this.type = 'BoxHelper';
  28602. this.matrixAutoUpdate = false;
  28603. this.update();
  28604. }
  28605. update( object ) {
  28606. if ( object !== undefined ) {
  28607. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  28608. }
  28609. if ( this.object !== undefined ) {
  28610. _box.setFromObject( this.object );
  28611. }
  28612. if ( _box.isEmpty() ) return;
  28613. const min = _box.min;
  28614. const max = _box.max;
  28615. /*
  28616. 5____4
  28617. 1/___0/|
  28618. | 6__|_7
  28619. 2/___3/
  28620. 0: max.x, max.y, max.z
  28621. 1: min.x, max.y, max.z
  28622. 2: min.x, min.y, max.z
  28623. 3: max.x, min.y, max.z
  28624. 4: max.x, max.y, min.z
  28625. 5: min.x, max.y, min.z
  28626. 6: min.x, min.y, min.z
  28627. 7: max.x, min.y, min.z
  28628. */
  28629. const position = this.geometry.attributes.position;
  28630. const array = position.array;
  28631. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  28632. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  28633. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  28634. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  28635. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  28636. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  28637. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  28638. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  28639. position.needsUpdate = true;
  28640. this.geometry.computeBoundingSphere();
  28641. }
  28642. setFromObject( object ) {
  28643. this.object = object;
  28644. this.update();
  28645. return this;
  28646. }
  28647. copy( source, recursive ) {
  28648. super.copy( source, recursive );
  28649. this.object = source.object;
  28650. return this;
  28651. }
  28652. }
  28653. class Box3Helper extends LineSegments {
  28654. constructor( box, color = 0xffff00 ) {
  28655. 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 ] );
  28656. 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 ];
  28657. const geometry = new BufferGeometry();
  28658. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  28659. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28660. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28661. this.box = box;
  28662. this.type = 'Box3Helper';
  28663. this.geometry.computeBoundingSphere();
  28664. }
  28665. updateMatrixWorld( force ) {
  28666. const box = this.box;
  28667. if ( box.isEmpty() ) return;
  28668. box.getCenter( this.position );
  28669. box.getSize( this.scale );
  28670. this.scale.multiplyScalar( 0.5 );
  28671. super.updateMatrixWorld( force );
  28672. }
  28673. }
  28674. class PlaneHelper extends Line {
  28675. constructor( plane, size = 1, hex = 0xffff00 ) {
  28676. const color = hex;
  28677. 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 ];
  28678. const geometry = new BufferGeometry();
  28679. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28680. geometry.computeBoundingSphere();
  28681. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28682. this.type = 'PlaneHelper';
  28683. this.plane = plane;
  28684. this.size = size;
  28685. const positions2 = [ 1, 1, 0, - 1, 1, 0, - 1, - 1, 0, 1, 1, 0, - 1, - 1, 0, 1, - 1, 0 ];
  28686. const geometry2 = new BufferGeometry();
  28687. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  28688. geometry2.computeBoundingSphere();
  28689. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  28690. }
  28691. updateMatrixWorld( force ) {
  28692. this.position.set( 0, 0, 0 );
  28693. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  28694. this.lookAt( this.plane.normal );
  28695. this.translateZ( - this.plane.constant );
  28696. super.updateMatrixWorld( force );
  28697. }
  28698. }
  28699. const _axis = /*@__PURE__*/ new Vector3();
  28700. let _lineGeometry, _coneGeometry;
  28701. class ArrowHelper extends Object3D {
  28702. // dir is assumed to be normalized
  28703. 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 ) {
  28704. super();
  28705. this.type = 'ArrowHelper';
  28706. if ( _lineGeometry === undefined ) {
  28707. _lineGeometry = new BufferGeometry();
  28708. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  28709. _coneGeometry = new CylinderGeometry( 0, 0.5, 1, 5, 1 );
  28710. _coneGeometry.translate( 0, - 0.5, 0 );
  28711. }
  28712. this.position.copy( origin );
  28713. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  28714. this.line.matrixAutoUpdate = false;
  28715. this.add( this.line );
  28716. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  28717. this.cone.matrixAutoUpdate = false;
  28718. this.add( this.cone );
  28719. this.setDirection( dir );
  28720. this.setLength( length, headLength, headWidth );
  28721. }
  28722. setDirection( dir ) {
  28723. // dir is assumed to be normalized
  28724. if ( dir.y > 0.99999 ) {
  28725. this.quaternion.set( 0, 0, 0, 1 );
  28726. } else if ( dir.y < - 0.99999 ) {
  28727. this.quaternion.set( 1, 0, 0, 0 );
  28728. } else {
  28729. _axis.set( dir.z, 0, - dir.x ).normalize();
  28730. const radians = Math.acos( dir.y );
  28731. this.quaternion.setFromAxisAngle( _axis, radians );
  28732. }
  28733. }
  28734. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  28735. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  28736. this.line.updateMatrix();
  28737. this.cone.scale.set( headWidth, headLength, headWidth );
  28738. this.cone.position.y = length;
  28739. this.cone.updateMatrix();
  28740. }
  28741. setColor( color ) {
  28742. this.line.material.color.set( color );
  28743. this.cone.material.color.set( color );
  28744. }
  28745. copy( source ) {
  28746. super.copy( source, false );
  28747. this.line.copy( source.line );
  28748. this.cone.copy( source.cone );
  28749. return this;
  28750. }
  28751. }
  28752. class AxesHelper extends LineSegments {
  28753. constructor( size = 1 ) {
  28754. const vertices = [
  28755. 0, 0, 0, size, 0, 0,
  28756. 0, 0, 0, 0, size, 0,
  28757. 0, 0, 0, 0, 0, size
  28758. ];
  28759. const colors = [
  28760. 1, 0, 0, 1, 0.6, 0,
  28761. 0, 1, 0, 0.6, 1, 0,
  28762. 0, 0, 1, 0, 0.6, 1
  28763. ];
  28764. const geometry = new BufferGeometry();
  28765. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28766. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28767. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  28768. super( geometry, material );
  28769. this.type = 'AxesHelper';
  28770. }
  28771. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  28772. const color = new Color();
  28773. const array = this.geometry.attributes.color.array;
  28774. color.set( xAxisColor );
  28775. color.toArray( array, 0 );
  28776. color.toArray( array, 3 );
  28777. color.set( yAxisColor );
  28778. color.toArray( array, 6 );
  28779. color.toArray( array, 9 );
  28780. color.set( zAxisColor );
  28781. color.toArray( array, 12 );
  28782. color.toArray( array, 15 );
  28783. this.geometry.attributes.color.needsUpdate = true;
  28784. return this;
  28785. }
  28786. dispose() {
  28787. this.geometry.dispose();
  28788. this.material.dispose();
  28789. }
  28790. }
  28791. class ShapePath {
  28792. constructor() {
  28793. this.type = 'ShapePath';
  28794. this.color = new Color();
  28795. this.subPaths = [];
  28796. this.currentPath = null;
  28797. }
  28798. moveTo( x, y ) {
  28799. this.currentPath = new Path();
  28800. this.subPaths.push( this.currentPath );
  28801. this.currentPath.moveTo( x, y );
  28802. return this;
  28803. }
  28804. lineTo( x, y ) {
  28805. this.currentPath.lineTo( x, y );
  28806. return this;
  28807. }
  28808. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  28809. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  28810. return this;
  28811. }
  28812. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  28813. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  28814. return this;
  28815. }
  28816. splineThru( pts ) {
  28817. this.currentPath.splineThru( pts );
  28818. return this;
  28819. }
  28820. toShapes( isCCW, noHoles ) {
  28821. function toShapesNoHoles( inSubpaths ) {
  28822. const shapes = [];
  28823. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  28824. const tmpPath = inSubpaths[ i ];
  28825. const tmpShape = new Shape();
  28826. tmpShape.curves = tmpPath.curves;
  28827. shapes.push( tmpShape );
  28828. }
  28829. return shapes;
  28830. }
  28831. function isPointInsidePolygon( inPt, inPolygon ) {
  28832. const polyLen = inPolygon.length;
  28833. // inPt on polygon contour => immediate success or
  28834. // toggling of inside/outside at every single! intersection point of an edge
  28835. // with the horizontal line through inPt, left of inPt
  28836. // not counting lowerY endpoints of edges and whole edges on that line
  28837. let inside = false;
  28838. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  28839. let edgeLowPt = inPolygon[ p ];
  28840. let edgeHighPt = inPolygon[ q ];
  28841. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  28842. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  28843. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  28844. // not parallel
  28845. if ( edgeDy < 0 ) {
  28846. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  28847. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  28848. }
  28849. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  28850. if ( inPt.y === edgeLowPt.y ) {
  28851. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  28852. // continue; // no intersection or edgeLowPt => doesn't count !!!
  28853. } else {
  28854. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  28855. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  28856. if ( perpEdge < 0 ) continue;
  28857. inside = ! inside; // true intersection left of inPt
  28858. }
  28859. } else {
  28860. // parallel or collinear
  28861. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  28862. // edge lies on the same horizontal line as inPt
  28863. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  28864. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  28865. // continue;
  28866. }
  28867. }
  28868. return inside;
  28869. }
  28870. const isClockWise = ShapeUtils.isClockWise;
  28871. const subPaths = this.subPaths;
  28872. if ( subPaths.length === 0 ) return [];
  28873. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  28874. let solid, tmpPath, tmpShape;
  28875. const shapes = [];
  28876. if ( subPaths.length === 1 ) {
  28877. tmpPath = subPaths[ 0 ];
  28878. tmpShape = new Shape();
  28879. tmpShape.curves = tmpPath.curves;
  28880. shapes.push( tmpShape );
  28881. return shapes;
  28882. }
  28883. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  28884. holesFirst = isCCW ? ! holesFirst : holesFirst;
  28885. // console.log("Holes first", holesFirst);
  28886. const betterShapeHoles = [];
  28887. const newShapes = [];
  28888. let newShapeHoles = [];
  28889. let mainIdx = 0;
  28890. let tmpPoints;
  28891. newShapes[ mainIdx ] = undefined;
  28892. newShapeHoles[ mainIdx ] = [];
  28893. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  28894. tmpPath = subPaths[ i ];
  28895. tmpPoints = tmpPath.getPoints();
  28896. solid = isClockWise( tmpPoints );
  28897. solid = isCCW ? ! solid : solid;
  28898. if ( solid ) {
  28899. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  28900. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  28901. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  28902. if ( holesFirst ) mainIdx ++;
  28903. newShapeHoles[ mainIdx ] = [];
  28904. //console.log('cw', i);
  28905. } else {
  28906. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  28907. //console.log('ccw', i);
  28908. }
  28909. }
  28910. // only Holes? -> probably all Shapes with wrong orientation
  28911. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  28912. if ( newShapes.length > 1 ) {
  28913. let ambiguous = false;
  28914. let toChange = 0;
  28915. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  28916. betterShapeHoles[ sIdx ] = [];
  28917. }
  28918. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  28919. const sho = newShapeHoles[ sIdx ];
  28920. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  28921. const ho = sho[ hIdx ];
  28922. let hole_unassigned = true;
  28923. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  28924. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  28925. if ( sIdx !== s2Idx ) toChange ++;
  28926. if ( hole_unassigned ) {
  28927. hole_unassigned = false;
  28928. betterShapeHoles[ s2Idx ].push( ho );
  28929. } else {
  28930. ambiguous = true;
  28931. }
  28932. }
  28933. }
  28934. if ( hole_unassigned ) {
  28935. betterShapeHoles[ sIdx ].push( ho );
  28936. }
  28937. }
  28938. }
  28939. if ( toChange > 0 && ambiguous === false ) {
  28940. newShapeHoles = betterShapeHoles;
  28941. }
  28942. }
  28943. let tmpHoles;
  28944. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  28945. tmpShape = newShapes[ i ].s;
  28946. shapes.push( tmpShape );
  28947. tmpHoles = newShapeHoles[ i ];
  28948. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  28949. tmpShape.holes.push( tmpHoles[ j ].h );
  28950. }
  28951. }
  28952. //console.log("shape", shapes);
  28953. return shapes;
  28954. }
  28955. }
  28956. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  28957. const _tables = /*@__PURE__*/ _generateTables();
  28958. function _generateTables() {
  28959. // float32 to float16 helpers
  28960. const buffer = new ArrayBuffer( 4 );
  28961. const floatView = new Float32Array( buffer );
  28962. const uint32View = new Uint32Array( buffer );
  28963. const baseTable = new Uint32Array( 512 );
  28964. const shiftTable = new Uint32Array( 512 );
  28965. for ( let i = 0; i < 256; ++ i ) {
  28966. const e = i - 127;
  28967. // very small number (0, -0)
  28968. if ( e < - 27 ) {
  28969. baseTable[ i ] = 0x0000;
  28970. baseTable[ i | 0x100 ] = 0x8000;
  28971. shiftTable[ i ] = 24;
  28972. shiftTable[ i | 0x100 ] = 24;
  28973. // small number (denorm)
  28974. } else if ( e < - 14 ) {
  28975. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  28976. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  28977. shiftTable[ i ] = - e - 1;
  28978. shiftTable[ i | 0x100 ] = - e - 1;
  28979. // normal number
  28980. } else if ( e <= 15 ) {
  28981. baseTable[ i ] = ( e + 15 ) << 10;
  28982. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  28983. shiftTable[ i ] = 13;
  28984. shiftTable[ i | 0x100 ] = 13;
  28985. // large number (Infinity, -Infinity)
  28986. } else if ( e < 128 ) {
  28987. baseTable[ i ] = 0x7c00;
  28988. baseTable[ i | 0x100 ] = 0xfc00;
  28989. shiftTable[ i ] = 24;
  28990. shiftTable[ i | 0x100 ] = 24;
  28991. // stay (NaN, Infinity, -Infinity)
  28992. } else {
  28993. baseTable[ i ] = 0x7c00;
  28994. baseTable[ i | 0x100 ] = 0xfc00;
  28995. shiftTable[ i ] = 13;
  28996. shiftTable[ i | 0x100 ] = 13;
  28997. }
  28998. }
  28999. // float16 to float32 helpers
  29000. const mantissaTable = new Uint32Array( 2048 );
  29001. const exponentTable = new Uint32Array( 64 );
  29002. const offsetTable = new Uint32Array( 64 );
  29003. for ( let i = 1; i < 1024; ++ i ) {
  29004. let m = i << 13; // zero pad mantissa bits
  29005. let e = 0; // zero exponent
  29006. // normalized
  29007. while ( ( m & 0x00800000 ) === 0 ) {
  29008. m <<= 1;
  29009. e -= 0x00800000; // decrement exponent
  29010. }
  29011. m &= ~ 0x00800000; // clear leading 1 bit
  29012. e += 0x38800000; // adjust bias
  29013. mantissaTable[ i ] = m | e;
  29014. }
  29015. for ( let i = 1024; i < 2048; ++ i ) {
  29016. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  29017. }
  29018. for ( let i = 1; i < 31; ++ i ) {
  29019. exponentTable[ i ] = i << 23;
  29020. }
  29021. exponentTable[ 31 ] = 0x47800000;
  29022. exponentTable[ 32 ] = 0x80000000;
  29023. for ( let i = 33; i < 63; ++ i ) {
  29024. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  29025. }
  29026. exponentTable[ 63 ] = 0xc7800000;
  29027. for ( let i = 1; i < 64; ++ i ) {
  29028. if ( i !== 32 ) {
  29029. offsetTable[ i ] = 1024;
  29030. }
  29031. }
  29032. return {
  29033. floatView: floatView,
  29034. uint32View: uint32View,
  29035. baseTable: baseTable,
  29036. shiftTable: shiftTable,
  29037. mantissaTable: mantissaTable,
  29038. exponentTable: exponentTable,
  29039. offsetTable: offsetTable
  29040. };
  29041. }
  29042. // float32 to float16
  29043. function toHalfFloat( val ) {
  29044. if ( Math.abs( val ) > 65504 ) console.warn( 'THREE.DataUtils.toHalfFloat(): Value out of range.' );
  29045. val = clamp( val, - 65504, 65504 );
  29046. _tables.floatView[ 0 ] = val;
  29047. const f = _tables.uint32View[ 0 ];
  29048. const e = ( f >> 23 ) & 0x1ff;
  29049. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  29050. }
  29051. // float16 to float32
  29052. function fromHalfFloat( val ) {
  29053. const m = val >> 10;
  29054. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  29055. return _tables.floatView[ 0 ];
  29056. }
  29057. var DataUtils = /*#__PURE__*/Object.freeze({
  29058. __proto__: null,
  29059. toHalfFloat: toHalfFloat,
  29060. fromHalfFloat: fromHalfFloat
  29061. });
  29062. // r134, d65e0af06644fe5a84a6fc0e372f4318f95a04c0
  29063. function ImmediateRenderObject() {
  29064. console.error( 'THREE.ImmediateRenderObject has been removed.' );
  29065. }
  29066. // r138, 48b05d3500acc084df50be9b4c90781ad9b8cb17
  29067. class WebGLMultisampleRenderTarget extends WebGLRenderTarget {
  29068. constructor( width, height, options ) {
  29069. console.error( 'THREE.WebGLMultisampleRenderTarget has been removed. Use a normal render target and set the "samples" property to greater 0 to enable multisampling.' );
  29070. super( width, height, options );
  29071. this.samples = 4;
  29072. }
  29073. }
  29074. // r138, f9cd9cab03b7b64244e304900a3a2eeaa3a588ce
  29075. class DataTexture2DArray extends DataArrayTexture {
  29076. constructor( data, width, height, depth ) {
  29077. console.warn( 'THREE.DataTexture2DArray has been renamed to DataArrayTexture.' );
  29078. super( data, width, height, depth );
  29079. }
  29080. }
  29081. // r138, f9cd9cab03b7b64244e304900a3a2eeaa3a588ce
  29082. class DataTexture3D extends Data3DTexture {
  29083. constructor( data, width, height, depth ) {
  29084. console.warn( 'THREE.DataTexture3D has been renamed to Data3DTexture.' );
  29085. super( data, width, height, depth );
  29086. }
  29087. }
  29088. // r144
  29089. class BoxBufferGeometry extends BoxGeometry {
  29090. constructor( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  29091. console.warn( 'THREE.BoxBufferGeometry has been renamed to THREE.BoxGeometry.' );
  29092. super( width, height, depth, widthSegments, heightSegments, depthSegments );
  29093. }
  29094. }
  29095. // r144
  29096. class CapsuleBufferGeometry extends CapsuleGeometry {
  29097. constructor( radius, length, capSegments, radialSegments ) {
  29098. console.warn( 'THREE.CapsuleBufferGeometry has been renamed to THREE.CapsuleGeometry.' );
  29099. super( radius, length, capSegments, radialSegments );
  29100. }
  29101. }
  29102. // r144
  29103. class CircleBufferGeometry extends CircleGeometry {
  29104. constructor( radius, segments, thetaStart, thetaLength ) {
  29105. console.warn( 'THREE.CircleBufferGeometry has been renamed to THREE.CircleGeometry.' );
  29106. super( radius, segments, thetaStart, thetaLength );
  29107. }
  29108. }
  29109. // r144
  29110. class ConeBufferGeometry extends ConeGeometry {
  29111. constructor( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  29112. console.warn( 'THREE.ConeBufferGeometry has been renamed to THREE.ConeGeometry.' );
  29113. super( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  29114. }
  29115. }
  29116. // r144
  29117. class CylinderBufferGeometry extends CylinderGeometry {
  29118. constructor( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  29119. console.warn( 'THREE.CylinderBufferGeometry has been renamed to THREE.CylinderGeometry.' );
  29120. super( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  29121. }
  29122. }
  29123. // r144
  29124. class DodecahedronBufferGeometry extends DodecahedronGeometry {
  29125. constructor( radius, detail ) {
  29126. console.warn( 'THREE.DodecahedronBufferGeometry has been renamed to THREE.DodecahedronGeometry.' );
  29127. super( radius, detail );
  29128. }
  29129. }
  29130. // r144
  29131. class ExtrudeBufferGeometry extends ExtrudeGeometry {
  29132. constructor( shapes, options ) {
  29133. console.warn( 'THREE.ExtrudeBufferGeometry has been renamed to THREE.ExtrudeGeometry.' );
  29134. super( shapes, options );
  29135. }
  29136. }
  29137. // r144
  29138. class IcosahedronBufferGeometry extends IcosahedronGeometry {
  29139. constructor( radius, detail ) {
  29140. console.warn( 'THREE.IcosahedronBufferGeometry has been renamed to THREE.IcosahedronGeometry.' );
  29141. super( radius, detail );
  29142. }
  29143. }
  29144. // r144
  29145. class LatheBufferGeometry extends LatheGeometry {
  29146. constructor( points, segments, phiStart, phiLength ) {
  29147. console.warn( 'THREE.LatheBufferGeometry has been renamed to THREE.LatheGeometry.' );
  29148. super( points, segments, phiStart, phiLength );
  29149. }
  29150. }
  29151. // r144
  29152. class OctahedronBufferGeometry extends OctahedronGeometry {
  29153. constructor( radius, detail ) {
  29154. console.warn( 'THREE.OctahedronBufferGeometry has been renamed to THREE.OctahedronGeometry.' );
  29155. super( radius, detail );
  29156. }
  29157. }
  29158. // r144
  29159. class PlaneBufferGeometry extends PlaneGeometry {
  29160. constructor( width, height, widthSegments, heightSegments ) {
  29161. console.warn( 'THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry.' );
  29162. super( width, height, widthSegments, heightSegments );
  29163. }
  29164. }
  29165. // r144
  29166. class PolyhedronBufferGeometry extends PolyhedronGeometry {
  29167. constructor( vertices, indices, radius, detail ) {
  29168. console.warn( 'THREE.PolyhedronBufferGeometry has been renamed to THREE.PolyhedronGeometry.' );
  29169. super( vertices, indices, radius, detail );
  29170. }
  29171. }
  29172. // r144
  29173. class RingBufferGeometry extends RingGeometry {
  29174. constructor( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  29175. console.warn( 'THREE.RingBufferGeometry has been renamed to THREE.RingGeometry.' );
  29176. super( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength );
  29177. }
  29178. }
  29179. // r144
  29180. class ShapeBufferGeometry extends ShapeGeometry {
  29181. constructor( shapes, curveSegments ) {
  29182. console.warn( 'THREE.ShapeBufferGeometry has been renamed to THREE.ShapeGeometry.' );
  29183. super( shapes, curveSegments );
  29184. }
  29185. }
  29186. // r144
  29187. class SphereBufferGeometry extends SphereGeometry {
  29188. constructor( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  29189. console.warn( 'THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry.' );
  29190. super( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength );
  29191. }
  29192. }
  29193. // r144
  29194. class TetrahedronBufferGeometry extends TetrahedronGeometry {
  29195. constructor( radius, detail ) {
  29196. console.warn( 'THREE.TetrahedronBufferGeometry has been renamed to THREE.TetrahedronGeometry.' );
  29197. super( radius, detail );
  29198. }
  29199. }
  29200. // r144
  29201. class TorusBufferGeometry extends TorusGeometry {
  29202. constructor( radius, tube, radialSegments, tubularSegments, arc ) {
  29203. console.warn( 'THREE.TorusBufferGeometry has been renamed to THREE.TorusGeometry.' );
  29204. super( radius, tube, radialSegments, tubularSegments, arc );
  29205. }
  29206. }
  29207. // r144
  29208. class TorusKnotBufferGeometry extends TorusKnotGeometry {
  29209. constructor( radius, tube, tubularSegments, radialSegments, p, q ) {
  29210. console.warn( 'THREE.TorusKnotBufferGeometry has been renamed to THREE.TorusKnotGeometry.' );
  29211. super( radius, tube, tubularSegments, radialSegments, p, q );
  29212. }
  29213. }
  29214. // r144
  29215. class TubeBufferGeometry extends TubeGeometry {
  29216. constructor( path, tubularSegments, radius, radialSegments, closed ) {
  29217. console.warn( 'THREE.TubeBufferGeometry has been renamed to THREE.TubeGeometry.' );
  29218. super( path, tubularSegments, radius, radialSegments, closed );
  29219. }
  29220. }
  29221. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  29222. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  29223. revision: REVISION,
  29224. } } ) );
  29225. }
  29226. if ( typeof window !== 'undefined' ) {
  29227. if ( window.__THREE__ ) {
  29228. console.warn( 'WARNING: Multiple instances of Three.js being imported.' );
  29229. } else {
  29230. window.__THREE__ = REVISION;
  29231. }
  29232. }
  29233. 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, 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, DataTexture2DArray, DataTexture3D, DataTextureLoader, DataUtils, DecrementStencilOp, DecrementWrapStencilOp, DefaultLoadingManager, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightHelper, DiscreteInterpolant, DodecahedronBufferGeometry, DodecahedronGeometry, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicCopyUsage, DynamicDrawUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, EqualDepth, EqualStencilFunc, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExtrudeBufferGeometry, ExtrudeGeometry, FileLoader, Float16BufferAttribute, Float32BufferAttribute, Float64BufferAttribute, FloatType, Fog, FogExp2, FramebufferTexture, FrontSide, Frustum, GLBufferAttribute, GLSL1, GLSL3, GreaterDepth, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, GridHelper, Group, HalfFloatType, HemisphereLight, HemisphereLightHelper, HemisphereLightProbe, IcosahedronBufferGeometry, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, ImmediateRenderObject, 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, 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, RGBFormat, 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, 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, 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, WebGLMultisampleRenderTarget, WebGLRenderTarget, WebGLRenderer, WebGLUtils, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroFactor, ZeroSlopeEnding, ZeroStencilOp, _SRGBAFormat, sRGBEncoding };